PowerShell 技能连载 - 获取睡眠或休眠的时间

适用于 PowerShell 所有版本

如果您希望确认某台机器是否频繁地进入睡眠或者休眠模式,以下是一个读取对应的日志并返回详细信息的函数。它能汇报计算机何时进入睡眠模式,以及它进入睡眠模式的时长:

function Get-HibernationTime
{

  # get hibernation events
  Get-EventLog -LogName system -InstanceId 1 -Source Microsoft-Windows-Power-TroubleShooter |
  ForEach-Object {
    # create new object for results
    $result = 'dummy' | Select-Object -Property ComputerName, SleepTime, WakeTime, Duration

    # store details in new object, convert datatype where appropriate
    [DateTime]$result.Sleeptime = $_.ReplacementStrings[0]
    [DateTime]$result.WakeTime = $_.ReplacementStrings[1]
    $time = $result.WakeTime - $result.SleepTime
    $result.Duration = ([int]($time.TotalHours * 100))/100
    $result.ComputerName = $_.MachineName

    # return result
    $result
  }
}

PowerShell 技能连载 - 理解顺序过滤

适用于 PowerShell 所有版本

当您在解析基于文本的日志文件时,或是需要过滤其它类型的信息时,往往需要使用 Where-Object 命令。以下是一些常见的场景,演示如何合并过滤器:

# logical AND filter for ALL keywords
Get-Content -Path C:\windows\WindowsUpdate.log |
  Where-Object { $_ -like '*successfully installed*' } |
  Where-Object { $_ -like '*framework*' } |
  Out-GridView

# above example can also be written in one line
# by using the -and operator
# the resulting code is NOT faster, though, just harder to read
Get-Content -Path C:\windows\WindowsUpdate.log |
  Where-Object { ($_ -like '*successfully installed*') -and ($_ -like '*framework*') } |
  Out-GridView

# logical -or (either condition is met) can only be applied in one line
Get-Content -Path C:\windows\WindowsUpdate.log |
  Where-Object { ($_ -like '*successfully installed*') -or ($_ -like '*framework*') } |
  Out-GridView

PowerShell 技能连载 - 过滤 Hotfix 信息

适用于 PowerShell 所有版本

Get-HotFix 是一个用于返回已安装的 hotfix 的 cmdlet。不过它没有可以过滤 hotfix 编号的参数。

通过一个 cmdlet 过滤器,您可以很方便地查看您关注的 hotfix。这个例子只返回编号为“KB25”开头的 hotfix:

Get-HotFix |
  Where-Object {
    $_.HotfixID -like 'KB25*'
  }

请注意 Get-HotFix 有一个 -ComputerName 参数,所以如果您拥有了合适的权限,那么您也可以从远程计算机中获取 hotfix 信息。

PowerShell 技能连载 - 获取关机信息

适用于 PowerShell 所有版本

Windows 在系统事件日志中记录了所有的关机事件。您可以从那儿提取和分析信息。

以下是一个读取适当的事件日志记录、从 ReplacementStrings 数组中读取相关的信息,并以对象数组的方式返回关机信息的函数。

function Get-ShutdownInfo
{

  Get-EventLog -LogName system -InstanceId 2147484722 -Source user32 |
  ForEach-Object {

    $result = 'dummy' | Select-Object -Property ComputerName, TimeWritten, User, Reason, Action, Executable

    $result.TimeWritten = $_.TimeWritten
    $result.User = $_.ReplacementStrings[6]
    $result.Reason = $_.ReplacementStrings[2]
    $result.Action = $_.ReplacementStrings[4]
    $result.Executable = Split-Path -Path $_.ReplacementStrings[0] -Leaf
    $result.ComputerName = $_.MachineName

    $result
  }
}

现在要检查关机问题就容易多了:

PS> Get-ShutdownInfo |  Out-GridView

PowerShell 技能连载 - 复制命令行历史

适用于所有 PowerShell 版本

如果您操作了一阵子 PowerShell,然后突然意识到想保存刚才输入过的命令,那么请试试这行简单的代码:

(Get-History).CommandLine | clip

这段代码将您的所有命令行历史复制到剪贴板中。您可以把它粘贴到任何您喜欢的编辑器中,然后将命令保存到文件中。

如果您将命令粘贴到 PowerShell ISE 编辑器中,那么这些命令将会成为一段 PowerShell 脚本。

用 PowerShell 解析 eD2k 链接

电骡的 eD2k 链接包含了丰富的信息。例如这个:

ed2k://|file|BingPinyinSetup_1.5.24.02.exe|31485072|C8C9282E6112455E624EE82941E5BA00|p=79A822E1788353E0B289D2ADD5DA3BDE:FB9BB40DEDB1D2307E9D734A6416704B:0732B122C4ECF70065B181C92BF72400:437958DF590D764DE1694F91AC085225|h=HLXRQSANEO5MHIVOYNM5FNQOHJG3D5MP|s=http://blog.vichamp.com|s=http://www.baidu.com|/|sources,127.0.0.1:1234,192.168.1.1:8888|/

这给我们的第一感觉是可以用正则表达式来解析。我们观察一下它的规律,发现它是用 | 分割的字符串:

ed2k://
file
BingPinyinSetup_1.5.24.02.exe
31485072
C8C9282E6112455E624EE82941E5BA00
p=79A822E1788353E0B289D2ADD5DA3BDE:FB9BB40DEDB1D2307E9D734A6416704B:0732B122C4ECF70065B181C92BF72400:437958DF590D764DE1694F91AC085225
h=HLXRQSANEO5MHIVOYNM5FNQOHJG3D5MP
s=http://www.abc.com/def.zip
s=http://www.vichamp.com/qq.zip
/
sources,127.0.0.1:1234,192.168.1.1:8888
/

还有一些规律:

  • p= 开始,后面的段都是可选的。
  • p=xxxh=xxxs=xxx看起来像键值对。
  • s= 可以有多个,sources 后面的 IP 和端口可以有多对。

根据这个规律,我们可以很容易地构造出正则表达式,并用 PowerShell 解析它。

function Get-Ed2kLink {
    Param(
        [string]
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Enter an ed2k:// url')]
        $Link
    )

    $regex = [regex]@'
(?x)
\bed2k://
\|file\|(?<FILE_NAME>[^|]+)
\|(?<FILE_SIZE>\d+)
\|(?<FILE_HASH>[0-9a-fA-F]+)
(?:\|p=(?:(?<HASH_SET>[0-9a-fA-F]+):?)+)?
(?:\|h=(?<ROOT_HASH>[0-9a-zA-Z]+))?
(?:\|s=(?<HTTP_SOURCE>[^|]+))*
\|\/
\|sources(?:,(?<SOURCES_HOST>[0-9a-zA-Z.]+):(?<SOURCES_PORT>\d+))*
|\/\b
'@
    $match = $regex.Match($Link)
    if ($match.Success) {
        $sourcesHost = $match.Groups['SOURCES_HOST'].Captures | Select-Object -ExpandProperty Value
        $sourcesPort = $match.Groups['SOURCES_PORT'].Captures | Select-Object -ExpandProperty Value
        $sources = @()
        for ($i = 0; $i -lt $sourcesHost.Length; $i++) {
            $sources += [PSCustomObject][Ordered]@{
                Host = $sourcesHost[$i]
                Port = $sourcesPort[$i]
            }
        }

        $result = [PSCustomObject][Ordered]@{
            File = $match.Groups['FILE_NAME'].Value;
            FileSize = $match.Groups['FILE_SIZE'].Value;
            FileHash = $match.Groups['FILE_HASH'].Value;
            HashSet = $match.Groups['HASH_SET'].Captures | Select-Object -ExpandProperty Value
            RootHash = $match.Groups['ROOT_HASH'].Value;
            HttpSource = $match.Groups['HTTP_SOURCE'].Captures | Select-Object -ExpandProperty Value
            Sources = $sources;
        }
    } else {
        $result = $null
    }

    return $result
}

Get-Ed2kLink 'ed2k://|file|BingPinyinSetup_1.5.24.02.exe|31485072|C8C9282E6112455E624EE82941E5BA00|p=79A822E1788353E0B289D2ADD5DA3BDE:FB9BB40DEDB1D2307E9D734A6416704B:0732B122C4ECF70065B181C92BF72400:437958DF590D764DE1694F91AC085225|h=HLXRQSANEO5MHIVOYNM5FNQOHJG3D5MP|s=http://www.abc.com/def.zip|s=http://www.vichamp.com/qq.zip|/|sources,127.0.0.1:1234,192.168.1.1:8888|/'

执行结果如下:

File       : BingPinyinSetup_1.5.24.02.exe
FileSize   : 31485072
FileHash   : C8C9282E6112455E624EE82941E5BA00
HashSet    : {79A822E1788353E0B289D2ADD5DA3BDE, FB9BB40DEDB1D2307E9D734A6416704B, 0732B122C4ECF70065B181C92BF72400, 437958DF590D764DE1694F91AC085225}
RootHash   : HLXRQSANEO5MHIVOYNM5FNQOHJG3D5MP
HttpSource : {http://www.abc.com/def.zip, http://www.vichamp.com/qq.zip}
Sources    : {@{Host=127.0.0.1; Port=1234}, @{Host=192.168.1.1; Port=8888}}

注意一下,由于 s=sources 节包含循环体,所以不能直接用 PowerShell 的 -cmatch 表达式和 $Matches 变量,必须用 .NET 的 [regex] 类来处理。

参考材料:

您也可以在这里下载完整的源代码。

PowerShell 技能连载 - 用正则表达式搜索文件

适用于 PowerShell 所有版本

Get-ChildItem 不支持高级的文件过滤。当您使用简单的通配符时,无法利用上正则表达式。

要用上正则表达式,需要增加一个过滤用的 cmdlet 和 -match 操作符。

这个例子将在 Windows 目录中查找所有文件名包含至少 2 位数字,且文件名不超过 8 个字符的文件:

Get-ChildItem -Path $env:windir -Recurse -ErrorAction SilentlyContinue |
  Where-Object { $_.BaseName -match '\d{2}' -and $_.Name.Length -le 8 }

请注意 BaseName 属性的使用。它只返回主文件名(不包含扩展名)。通过这种方式,扩展名中的数字不会被包含在内。

PowerShell 技能连载 - 获取指定扩展名的文件

适用于 PowerShell 所有版本

当您使用 Get-ChildItem 来获取一个文件列表时,您可能会注意到 -Filter 参数有时候会导致返回比你预期的更多的文件。

以下是一个例子。这段代码并不只是返回“.ps1”扩展名的文件,而也会返回“.ps1xml”扩展名的文件:

Get-ChildItem -Path C:\windows -Recurse -ErrorAction SilentlyContinue -Filter *.ps1

要限制只返回您需要的扩展名的文件,请用一个 cmdlet 来过滤结果:

Get-ChildItem -Path C:\windows -Recurse -ErrorAction SilentlyContinue -Filter *.ps1 |
  Where-Object { $_.Extension -eq '.ps1' }

这将只返回您指定的扩展名的文件。

PowerShell 技能连载 - 修正 ISE 的编码

适用于所有 PowerShell 版本

当您在 ISE 编辑器中运行一个控制台程序时,非标准字符,例如“ä”或“ß”将会显示不正常。要修正 ISE 和隐藏的控制台之间通信的编码,请使用这段代码:

# Repair encoding. This REQUIRES a console app to run first because only
# then will ISE actually create its hidden background console

$null = cmd.exe /c echo
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# Now all is fine

cmd.exe /c echo ÄÖÜäöüß

PowerShell 技能连载 - 使用“打开文件”对话框

适用于 PowerShell 3.0 及以上版本

以下是一个快捷的函数,可以用在 ISE 编辑器和 PowerShell 控制台中(适用于 PowerShell 3.0 及以上版本):Show-OpenFileDialog

function Show-OpenFileDialog
{
  param
  (
    $StartFolder = [Environment]::GetFolderPath('MyDocuments'),

    $Title = 'Open what?',

    $Filter = 'All|*.*|Scripts|*.ps1|Texts|*.txt|Logs|*.log'
  )


  Add-Type -AssemblyName PresentationFramework

  $dialog = New-Object -TypeName Microsoft.Win32.OpenFileDialog


  $dialog.Title = $Title
  $dialog.InitialDirectory = $StartFolder
  $dialog.Filter = $Filter


  $resultat = $dialog.ShowDialog()
  if ($resultat -eq $true)
  {
    $dialog.FileName
  }
}

这个函数将打开一个“打开文件”对话框。用户可以选择一个文件,并且选择的文件对象将返回给 PowerShell。所以下次您的脚本需要打开一个 CSV 文件时,您可能就能用上。