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 就能查看完整的信息。

PowerShell 电子书合集

搜集到的所有 PowerShell 电子书 共享链接
将来一旦有更新,就会自动同步、自动更新,再也不用为资料发愁了。如果您也有好料想一起分享,请在群里发个消息,我把读写权限给您。

最好在客户端的 文件夹 / 偏好设定 中的 搜索 DHT 网络 前打上勾,可以提高成功率 :)


PowerShell 技能连载 - 导出服务状态信息

适用于 PowerShell 所有版本

如果您想将一个 PowerShell 命令的结果保存到磁盘上,以便传到另一台机器上,以下是简单的实现方法:

$Path = "$env:temp\mylist.xml"

Get-Service |
  Add-Member -MemberType NoteProperty -Name ComputerName -Value $env:COMPUTERNAME -PassThru |
  Export-Clixml -Depth 1 -Path $Path

explorer.exe "/select,$Path"

这段代码用 Get-Service 获取所有的服务。结果添加了一个“ComputerName”字段,用于保存生成的数据所在的计算机名。

然后,得到的结果被序列化成 XML 并保存到磁盘上。接着在目标文件夹打开资源管理器,并且选中创建的 XML 文件。这样您就可以方便地将它拷到 U 盘中随身带走。

要将结果反序列化成真实的对象,使用以下代码:

$Path = "$env:temp\mylist.xml"

Import-Clixml -Path $Path

PowerShell 技能连载 - 比较服务配置

适用于 PowerShell 3.0 或更高版本

假设您在两台服务器上启用了 PowerShell 远程服务,那么下面这个简单的脚本演示了如何从每台服务器上获取所有服务的状态并且计算两台服务器之间的差异。

$Server1 = 'myServer1'
$Server2 = 'someOtherServer'

$services1 = Invoke-Command { Get-Service } -ComputerName $Server1 |
  Sort-Object -Property Name, Status

$services2 = Invoke-Command { Get-Service } -ComputerName $Server2 |
  Sort-Object -Property Name, Status

Compare-Object -ReferenceObject $services1 -DifferenceObject $services2 -Property Name, Status -PassThru |
  Sort-Object -Property Name

得到的结果是服务配置差异的清单。

PowerShell 技能连载 - 下载 PowerShell 语言规范

适用于 PowerShell 所有版本

在 PowerShell 中,从 Internet 中下载文件十分方便。以下这段代码能够自动将 PowerShell 语言规范——包含 PowerShell 精华和内核知识的很棒的 Word 文档——下载到您的机器上。

$link = 'http://download.microsoft.com/download/3/2/6/326DF7A1-EE5B-491B-9130-F9AA9C23C29A/PowerShell%202%200%20Language%20Specification.docx'

$outfile = "$env:temp\languageref.docx"

Invoke-WebRequest -Uri $link -OutFile $outfile

Invoke-Item -Path $outfile

PowerShell 技能连载 - 等待按键

适用于 PowerShell 所有版本,仅适用于 PowerShell 控制台

若希望脚本执行结束时,保持 PowerShell 控制台程序为打开状态,您也许希望增加一句“按任意键继续”语句。以下是实现方式:

Write-Host 'Press Any Key!' -NoNewline
$null = [Console]::ReadKey('?')

这段代码仅适用于真实的 PowerShell 控制台。它在 ISE 编辑器或其它未使用真实互操作键盘缓冲区的控制台程序中并不适用。

PowerShell 技能连载 - 查找脚本中的错误

适用于 PowerShell 所有版本

没有比这种更简单的方法来查找脚本中的语法错误了。只需要用这个过滤器:

filter Test-SyntaxError
{
   $text = Get-Content -Path $_.FullName
   if ($text.Length -gt 0)
   {
      $err = $null
      $null = [System.Management.Automation.PSParser]::Tokenize($text, [ref] $err)
      if ($err) { $_ }
   }
}

通过使用这个过滤器,您可以快速地扫描文件夹,甚至整台计算机,列出所有包含语法错误的 PowerShell 文件。

以下代码将在您的用户文件夹下遍历并查找所有的 PowerShell 脚本并列出包含语法错误的文件:

PS> dir $home -Filter *.ps1 -Recurse -Exclude *.ps1xml | Test-SyntaxError

PowerShell 技能连载 - 检测文本中是否含有大写字母

适用于 PowerShell 任何版本

可以使用正则表达式来检测一个字符串是否包含至少一个大写字母:

$text1 = 'this is all lower-case'
$text2 = 'this is NOT all lower-case'

$text1 -cmatch '[A-Z]'
$text2 -cmatch '[A-Z]'

得到的结果分别是“Frue”和“False”。

要检测一段文本是否只包含小写字母,请试试这段代码:

$text1 = 'this is all lower-case'
$text2 = 'this is NOT all lower-case'

$text1 -cmatch '^[a-z\s-]*$'
$text2 -cmatch '^[A-Z\s-]*$'

得到的结果分别是“True”和“False”。

实际上检测起来会更麻烦,因为您需要包括所有合法的字符。在这个例子中,我选择了 a-z 的小写字母、空格和减号。

这些“合法”的字符被包含在“^”和“$”(行首符和行尾符)之间。星号是一个量词(任意数量个“合法的”字符)。

PowerShell 技能连载 - 获取字符串的行数

适用于 PowerShell 所有版本

以下是一个获取字符串(而不是字符串数组!)行数的技巧:

$text = @'
This is some
sample text
Let's find out
the number of lines.
'@

$text.Length - $text.Replace("`n",'').Length + 1

技术上来说,这个例子用的是 here-string 来创建多行字符串,不过这只是一个例子。它对所有类型的字符串都有效,无论它的来源是什么。