PowerShell 技能连载 - 获取变量详细清单

适用于 PowerShell ISE 3 或更高版本

出于写文档等目的,您可能需要获得一份 PowerShell 脚本用到的所有变量的清单。

以下是一个名为 Get-Variable 的函数:

function Get-Variable
{

  $token = $null
  $errors = $null

  $ast = [System.Management.Automation.Language.Parser]::ParseInput($psise.CurrentFile.Editor.Text, [ref] $token, [ref] $errors)

  # not complete, add variables you want to exclude from the list:
  $systemVariables = '_', 'null', 'psitem', 'true', 'false', 'args', 'host'

  $null = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
  $token |
    Where-Object { $_.Kind -eq 'Variable'} |
    Select-Object -ExpandProperty Name |
    Where-Object { $systemVariables -notcontains $_ } |
    Sort-Object -Unique
}

只需要用系统自带的 ISE 编辑器打开这个脚本,然后在交互式控制台中运行 Get-Variable

您将会得到一个排序过的列表,内容是当前打开的脚本用到的所有变量。

如果您将“$psise.CurrentFile.Editor.Text”替换成一个包含脚本代码的变量,那么您可以在 ISE 编辑器之外运行这个函数。只需要用 Get-Content 将任意脚本的内容读取进一个变量,然后就可以在上述代码中使用这个变量。

PowerShell 技能连载 - 重命名变量

适用于 PowerShell ISE 3 或更高版本

以下是一个简单的变量重命名函数,您可以在 PowerShell 3.0 及以上版本的 ISE 编辑器中使用它

它将识别某个变量的所有实例,然后将它重命名为一个新的名字。

function Rename-Variable
{
  param
  (
    [Parameter(Mandatory=$true)]
    $OldName,

    [Parameter(Mandatory=$true)]
    $NewName
  )

  $InputText = $psise.CurrentFile.Editor.Text
  $token = $null
  $errors = $null

  $ast = [System.Management.Automation.Language.Parser]::ParseInput($InputText, [ref] $token, [ref] $errors)

  $token |
  Where-Object { $_.Kind -eq 'Variable'} |
  Where-Object { $_.Name -eq $OldName } |
  Sort-Object { $_.Extent.StartOffset } -Descending |
  ForEach-Object {
    $start = $_.Extent.StartOffset + 1
    $end = $_.Extent.EndOffset
    $InputText = $InputText.Remove($start, $end-$start).Insert($start, $NewName)
  }

  $psise.CurrentFile.Editor.Text = $InputText
}

运行这个函数之后,您将得到一个名为 Rename-Variable 的新命令。

下一步,在 ISE 编辑器中打开一个脚本,然后在控制台面板中,键入以下内容(当然,需要将旧的变量名“_oldVariableName_”改为您当前所打开的 ISE 脚本中实际存在的变量名)。

PS> Rename-Variable -OldName oldVariableName -NewName theNEWname

立刻,旧变量的所有出现的地方都被替换成新的变量名。

注意:这是一个非常简易的变量重命名函数。一定要记得备份您的脚本。它还不能算是一个能用在生产环境的重构方案。

当您重命名变量时,您脚本的许多别处地方也可能需要更新。例如,当一个变量是函数参数时,所有调用该函数的地方都得修改它们的参数名。

PowerShell 技能连载 - 格式化行尾符

适用于 PowerShell 所有版本

当您从 Internet 中下载了文件之后,您也许会遇到文件无法在编辑器中正常打开的情况。最常见的是,由于非正常行尾符导致的。

以下是这个问题的一个例子。在前一个技能里我们演示了如何下载一份 MAC 地址的厂家清单。当下载完成后用记事本打开它时,换行都消失了:

$url = 'http://standards.ieee.org/develop/regauth/oui/oui.txt'
$outfile = "$home\vendorlist.txt"

Invoke-WebRequest -Uri $url -OutFile $outfile

Invoke-Item -Path $outfile

要修复这个文件,只需要使用这段代码:

$OldFile = "$home\vendorlist.txt"
$NewFile = "$home\vendorlistGood.txt"

Get-Content $OldFile | Set-Content -Path $NewFile

notepad $NewFile

Get-Content 能够检测非标准的行尾符,所以结果是各行的字符串数组。当您将这些行写入一个新文件时,一切都会变正常,因为 Set-Content 会使用缺省的行尾符。

PowerShell 技能连载 - 通过 MAC 地址识别网卡厂家

适用于 PowerShell 所有版本

每个 MAC 地址唯一标识了一个网络设备。MAC 地址是由网络设备厂家分配的。所以您可以通过任何一个 MAC 地址反查出厂家信息。

您所需的只是一份大约 2MB 大小的 IEEE 厂家清单。以下是下载该清单的脚本:

$url = 'http://standards.ieee.org/develop/regauth/oui/oui.txt'
$outfile = "$home\vendorlist.txt"

Invoke-WebRequest -Uri $url -OutFile $outfile

下一步,您可以使用该清单来识别厂家信息。首先获取 MAC 地址,例如:

PS> getmac

Physical Address    Transport Name
=================== ==========================================================
5C-51-4F-62-F2-7D   \Device\Tcpip_{FF034A81-CBFE-4B11-9D81-FC8FC889A33C}
5C-51-4F-62-F2-81   Media disconnected

取 MAC 地址的前 3 个 8 进制字符,例如 _5c-51-4f_,然后用它在下载的文件中查询:

PS> Get-Content -Path $outfile | Select-String 5c-51-4f -Context 0,6

>   5C-51-4F   (hex)        Intel Corporate
    5C514F     (base 16)        Intel Corporate
                    Lot 8, Jalan Hi-Tech 2/3
                  Kulim Hi-Tech Park
                  Kulim Kedah 09000
                  MALAYSIA

您不仅可以获取厂家名称(这个例子中是 Intel),而且还可以获取厂家的地址和所在区域。

PowerShell 技能连载 - 获取 MAC 地址

适用于 PowerShell 所有版本

在 PowerShell 中获取网卡的 MAC 地址十分简单。以下是众多方法中的一个:

PS> getmac /FO CSV | ConvertFrom-Csv

Physical Address                        Transport Name
----------------                        --------------
5C-51-4F-62-F2-7D                       \Device\Tcpip_{FF034A81-CBFE-4B11-9D...
5C-51-4F-62-F2-81                       Media disconnected

有挑战性的地方在于实际的列名是本地化的,不同语言文化的值差异很大。由于原始信息是来自于 getmac.exe 生成的 CSV 数据,所以有一个简单的技巧:跳过首行(包含 CSV 头部),然后传入自定义的统一列名,以达到对列重命名的效果。

getmac.exe /FO CSV |
  Select-Object -Skip 1 |
  ConvertFrom-Csv -Header MAC, Transport

这将总是产生“_MAC_”和“_Transport_”的列。

当然,也有面向对象的解决方案,例如通过 WMI 查询或者使用 Windows 8.1 或 Server 2012/2012 R2。不过,我们认为所演示的方法是一个有趣的选择并且展示了如何将原始的 CSV 数据转换为真正有用的和语言文化无关的信息。

PowerShell 技能连载 - 高级文本分隔

适用于 PowerShell 所有版本

当您用 -split 操作符来分隔文本时,分隔符本身会被忽略掉:

PS> 'Hello, this is a text, and it has commas' -split ','
Hello
 this is a text
 and it has commas

如您所见,结果中的逗号被忽略掉了。

分隔符有可能多于一个字符。以下代码将以逗号 + 一个空格作为分隔符:

PS> 'Hello, this is a text, and it has commas' -split ', '
Hello
this is a text
and it has commas

由于 -split 接受的操作数是一个正则表达式,所以以下代码将以逗号 + 至少一个空格作为分隔符:

PS> 'Hello,    this is a    text, and it has commas' -split ',\s{1,}'
Hello
this is a    text
and it has commas

如果您需要的话,可以用 (?=…) 把分隔符包裹起来,以在结果中保留分隔符:

PS> 'Hello,    this is a    text, and it has commas' -split '(?=,\s{1,})'
Hello
,    this is a    text
, and it has commas

PowerShell 技能连载 - 分隔文本

适用于 PowerShell 所有版本

我们可以用 -split 操作符按指定的分隔符来分隔文本。这个操作符接受一个正则表达式作为操作数,所以如果您只是希望用纯文本的表达式来作为分隔的操作数,那么您需要将该纯文本转义一下。

以下是用反斜杠来分隔路径的例子:

$originalText = 'c:\windows\test\file.txt'
$splitText = [RegEx]::Escape('\')

$originalText -split $splitText

结果类似如下,并且它是一个数组:

PS> $originalText -split $splitText
c:
windows
test
file.txt

我们可以将它保存到一个变量中,然后存取单个的数组元素。

PS> $parts = $originalText -split $splitText

PS> $parts[0]
c:

PS> $parts[-1]
file.txt

PowerShell 技能连载 - 替换重复的空格

适用于 PowerShell 所有版本

要删除重复的空格,请使用这个正则表达式:

PS> '[  Man, it    works!   ]' -replace '\s{2,}', ' '
[ Man, it works! ]

您也可以用这种方式将固定宽度的文本表格转成 CSV 数据:

PS> (qprocess) -replace '\s{2,}', ','
>tobias,console,1,3876,taskhostex.exe
>tobias,console,1,3844,explorer.exe
>tobias,console,1,4292,tabtip.exe

当得到 CSV 数据之后,您可以用 ConvertFrom-Csv 将文本数据转换为对象:

PS> (qprocess) -replace '\s{2,}', ',' | ConvertFrom-Csv -Header Name, Session, ID, Pid, Process


Name    : >tobias
Session : console
ID      : 1
Pid     : 3876
Process : taskhostex.exe

Name    : >tobias
Session : console
ID      : 1
Pid     : 3844
Process : explorer.exe

Name    : >tobias
Session : console
ID      : 1
Pid     : 4292
Process : tabtip.exe
(...)

PowerShell 技能连载 - 创建短网址

适用于 PowerShell 所有版本

您也许听说过长网址的缩短服务。有许多这类免费的服务。以下是一个将任何网址转化为短网址的脚本:

$OriginalURL = 'http://www.powertheshell.com/isesteroids2'

$url = "http://tinyurl.com/api-create.php?url=$OriginalURL"
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.DownloadString($url)

只需要将需要缩短的网址赋给 $OriginalURL,运行脚本。它将返回对应的短网址。

PowerShell 技能连载 - 查找 PowerShell 函数

适用于 PowerShell 3.0 或更高版本

要快速扫描您的 PowerShell 脚本仓库并在其中查找某个函数,请使用以下过滤器:

filter Find-Function
{
   $path = $_.FullName
   $lastwrite = $_.LastWriteTime
   $text = Get-Content -Path $path

   if ($text.Length -gt 0)
   {

      $token = $null
      $errors = $null
      $ast = [System.Management.Automation.Language.Parser]::ParseInput($text, [ref] $token, [ref] $errors)
      $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) |
      Select-Object -Property Name, Path, LastWriteTime |
      ForEach-Object {
         $_.Path = $path
         $_.LastWriteTime = $lastwrite
         $_
      }
   }
}

以下是扫描您的用户配置文件中所有定义了函数的 PowerShell 脚本的方法:

PS> dir $home -Filter *.ps1 -Recurse -Exclude *.ps1xml | Find-Function

  Name                       Path                       LastWriteTime
  ----                       ----                       -------------
  Inject-LogonCredentials    C:\Users\Tobias\Desktop... 06.01.2014 02:43:00
  Test-Command               C:\Users\Tobias\Desktop... 06.03.2014 10:17:02
  Test                       C:\Users\Tobias\Desktop... 30.01.2014 09:32:20
  Get-WebPictureOriginal     C:\Users\Tobias\Desktop... 11.12.2013 11:37:53
  Get-ConnectionString       C:\Users\Tobias\Documen... 23.05.2014 10:49:09
  Convert-SID2User           C:\Users\Tobias\Documen... 23.05.2014 15:33:06
  Lock-Screen                C:\Users\Tobias\Documen... 19.03.2014 12:51:54
  Show-OpenFileDialog        C:\Users\Tobias\Documen... 16.05.2014 13:42:16
  Show-UniversalData         C:\Users\Tobias\Documen... 16.05.2014 13:23:20
  Start-TimebombMemory       C:\Users\Tobias\Documen... 23.05.2014 09:12:28
  Stop-TimebombMemory        C:\Users\Tobias\Documen... 23.05.2014 09:12:28
  (...)

只需要将结果通过管道输出到 Out-GridView 就能查看完整的信息。