PowerShell 技能连载 - 将二进制字符串转为整形

以下是将一段二进制文本字符串转为对应的整形值的方法:

1
2
3
$binary = "110110110"
$int = [Convert]::ToInt32($binary,2)
$int

用另一种方法可以更简单:

1
2
PS> [Convert]::ToString(438,2)
110110110

PowerShell 技能连载 - 使用剪贴板来传输数据和结果

终于,在 PowerShell 5 中原生支持将结果发送到剪贴板中,以及从剪贴板中接收结果:

1
2
3
4
5
6
PS> Get-Command -Noun Clipboard

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-Clipboard 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Set-Clipboard 3.1.0.0 Microsoft.PowerShell.Management

例如,您可以打开一个包含一些数据的 Excel 表格,将一列复制到剪贴板中,然后在 PowerShell 中进一步处理数据,例如过滤它:

1
PS> $list = (Get-ClipBoard) -like '*err*'

PowerShell 技能连载 - 在远程系统中安装 MSI

以下是一些或许对您有用的代码。您需要远程系统的管理员权限。

1
2
3
4
5
$ComputerName = 'NameOfMachineToInstall'
$TargetPathMSI = '\\softwareserver\product\package.msi'

$class = [wmiclass]"\\$ComputerName\ROOT\cimv2:Win32_Product"
$class.Install($TargetPathMSI)

如果权限和网络连接允许,这段代码将在远程系统中安装一个 MSI 包。请在开始之前调整好变量。第一个是需要安装 MSI 的机器名称。第二个是需要安装的 MSI 路径。

PowerShell 技能连载 - .Replace() 和 -replace 的区别

有两种方法可以替换一个字符串中的问本:Replace() 方法,和 -replace 操作符。它们的工作机制是不同的。

Replace() 是大小写敏感的,能够将文本替换为新的文本:

1
2
3
4
5
PS> 'Hello World.'.Replace('o', '0')
Hell0 W0rld

PS> 'Hello World.'.Replace('ell','oo')
Hooo World

-replace 操作符缺省是大小写不敏感的(如果希望大小写敏感,请使用 -creplace)。它接受一个正则表达式输入,很多人忽略了这个功能:

1
2
3
4
5
PS> 'Hello World.' -replace 'ell', 'oo'
Hooo World.

PS> 'Hello World.' -replace '.', '!'
!!!!!!!!!!!!

第二个输出会让不了解正则表达式的人感到惊讶。如果您希望用 -replace 来替换静态文本,请确保对文本进行转义:

1
2
PS> 'Hello World.' -replace [Regex]::Escape('.'), '!'
Hello World!

PowerShell 技能连载 - HTML 高级编码

.NET 静态方法 HtmlEncode 能够较好地将普通字符进行编码,但是对于许多特殊字符会处理失败。要正确地对所有字符编码,我们编写了一个 ConvertTo-EncodedHtml 函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function ConvertTo-EncodedHTML($HtmlText)
{

$chars = [Web.HttpUtility]::HtmlEncode($HtmlText).ToCharArray()
$txt = New-Object System.Text.StringBuilder
$null = . {
foreach($c in $chars)
{
if ([int]$c -gt 127)
{
$txt.Append("&#" + [int]$c + ";")
}
else
{
$txt.Append($c)
}
}
}
return $txt.ToString()
}

这个函数检查所有 ASCII 代码大于 127 的字符并将这些字符转换为编码后的版本:

1
2
PS> Convert-EncodedHTML -HtmlText "A – s ‘Test’"
A – s ‘Test’

PowerShell 技能连载 - HTML 编码

有一个 .NET 的静态方法可以对一段文本进行 HTML 编码,例如如果您希望在 HTML 输出中正常显示一段文本:

1
2
PS>  [System.Web.HttpUtility]::HtmlEncode('Österreich heißt so.')
Österreich heißt so.

PowerShell 技能连载 - 批量打印 Word 文档

这行代码将在您的配置文件中查找所有 Word 文档:

1
Get-ChildItem -Path $home -Filter *.doc* -Recurse

If you’d like, you can easily print them all. Here is how:
如果需要,可以将它们全部打印出来。以下是具体方法:

1
2
3
4
Get-ChildItem -Path $home -Filter *.doc* -Recurse |
ForEach-Object {
Start-Process -FilePath $_.FullName -Verb Print -Wait
}

它最重要的部分是 -Wait 参数:如果缺少了它,PowerShell 将会同时启动多个 Word 的实例,并行打印所有文档。这将耗尽您系统的资源。使用 -Wait 参数以后,PowerShell 将等待前一个 Word 打印完之后再启动下一个实例。

PowerShell 技能连载 - 从德国媒体数据库下载视频

在德国,有一些公开的媒体数据库,里面有公共站点发布的电视内容。只需要用一小段 PowerShell 代码就可以解析 JSON 数据,在一个列表中显示电视节目,并使你能够选择某项来下载。

请注意包含下载链接的 JSON 文件非常大,所以需要过一段时间才能显示出视频列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#requires -Version 3.0

# here is the list of download URLs - get it and
# convert the JSON format
$url = 'http://www.mediathekdirekt.de/good.json'
$web = Invoke-WebRequest -Uri $url -UseBasicParsing
$videos = $web.Content | ConvertFrom-Json

# get all videos, create a nice title to display,
# and attach the original data to each entry
$videos |
ForEach-Object {
$title = '{0} - {1}' -f $_[2], $_[5]
$title | Add-Member -MemberType NoteProperty -Name Data -Value $_ -PassThru
} |
Sort-Object |
Out-GridView -Title 'Video' -OutputMode Multiple |
ForEach-Object {
# get the actual download info from the selected videos
# and do the download
$url = $_.Data[6]
$filename = Split-Path -Path $url -Leaf
# videos are saved into your TEMP folder unless you
# specify a different folder below
$filepath = Join-Path -Path $env:temp -ChildPath $filename
Invoke-WebRequest -Uri $url -OutFile $filepath -UseBasicParsing
Invoke-Item -Path $filepath
}

PowerShell 技能连载 - 翻译错误记录

Whenever PowerShell records an error, it wraps it in an Error Record object. Here is a function that takes such an error record and extracts the useful information:
当 PowerShell 记录一个错误时,它将错误信息包装在一个 Error Record 对象中。以下是一个处理这种错误记录并解析有用信息的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#requires -Version 3.0
function Get-ErrorDetail
{
param
(
[Parameter(Mandatory,ValueFromPipeline)]
$e
)
process
{
if ($e -is [Management.Automation.ErrorRecord])
{
[PSCustomObject]@{
Reason = $e.CategoryInfo.Reason
Exception = $e.Exception.Message
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
Datum = Get-Date
User = $env:USERNAME
}
}
}
}

如果您想知道最后的错误信息是什么,请试试这个:

1
2
3
PS C:\> $error | Get-ErrorDetail | Out-GridView

PS C:\>

或者,您现在可以简单地命令一个 cmdlet 缓存它的错误信息,并在晚些时候处理它们。这个例子递归地在 Windows 文件夹中搜索 PowerShell 脚本。您可以获取结果,以及搜索时发生的所有错误的详细信息:

1
2
3
$files = Get-ChildItem -Path c:\Windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable myErrors

$myErrors| Get-ErrorDetail | Out-GridView

PowerShell 技能连载 - 用 Out-GridView 启用 AD 用户

有些时候在 PowerShell 中只需要几行代码就可以创造出很有用的支持工具。以下是一个显示所有禁用的 AD 用户的例子。您可以选择一个(或按住 CTRL 键选择多个),然后点击 OK,这些用户将会被启用:

1
2
3
4
5
#requires -Version 3.0 -Modules ActiveDirectory
Search-ADAccount -AccountDisabled |
Out-GridView -Title 'Who should be enabled?' -OutputMode Multiple |
# remove -WhatIf to actually enable accounts
Enable-ADAccount -WhatIf