PowerShell 技能连载 - 查找最新的 PowerShell 6 发布

PowerShell 6 是开源的,所以经常发布新的更新。您随时可以访问 https://github.com/PowerShell/PowerShell/releases 来查看这些更新。

对于 PowerShell 来说,可以使这步操作自动化。以下是一小段读取 GitHub 发布的 RSS 供稿的代码,它能够正确地转换数据,然后取出这些更新以及下载信息,并按降序排列:

1
2
3
4
5
$AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'[Net.ServicePointManager]::SecurityProtocol = $AllProtocols $Updated = @{
Name = 'Updated' Expression = { $_.Updated -as [DateTime] }
}$Link = @{
Name = 'URL' Expression = { $_.Link.href }
}Invoke-RestMethod -Uri https://github.com/PowerShell/PowerShell/releases.atom -UseBasicParsing | Sort-Object -Property Updated -Descending | Select-Object -Property Title, $Updated, $Link

结果类似这样:

title                                       Updated             URL
-----                                       -------             ---
v6.2.0 Release of PowerShell Core           28.03.2019 19:52:27 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0
v6.2.0-rc.1 Release of PowerShell Core      05.03.2019 23:47:46 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0-rc.1
v6.1.3 Release of PowerShell Core           19.02.2019 19:32:01 https://github.com/PowerShell/PowerShell/releases/tag/v6.1.3
v6.2.0-preview.4 Release of PowerShell Core 28.01.2019 22:28:01 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0-preview.4
v6.1.2 Release of PowerShell Core           15.01.2019 21:02:39 https://github.com/PowerShell/PowerShell/releases/tag/v6.1.2
v6.2.0-preview.3 Release of PowerShell Core 11.12.2018 01:29:33 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0-preview.3
v6.2.0-preview.2 Release of PowerShell Core 16.11.2018 02:52:53 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0-preview.2
v6.1.1 Release of PowerShell Core           13.11.2018 20:55:45 https://github.com/PowerShell/PowerShell/releases/tag/v6.1.1
v6.0.5 Release of PowerShell Core           13.11.2018 19:00:56 https://github.com/PowerShell/PowerShell/releases/tag/v6.0.5
v6.2.0-preview.1 Release of PowerShell Core 18.10.2018 02:07:32 https://github.com/PowerShell/PowerShell/releases/tag/v6.2.0-preview.1

请注意,只有在 Windows 10 1803 之前才需要显式启用 SSL。

PowerShell 技能连载 - 查找最新的 PowerShell 6 下载地址

PowerShell 6 是开源的,所以经常发布新的更新。以下是如何查找最新的 PowerShell 6 发布地址的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[Net.ServicePointManager]::SecurityProtocol = $AllProtocols


# get the URL for the latest PowerShell 6 release
$url = "https://github.com/PowerShell/PowerShell/releases/latest?dummy=$(Get-Random)"
$request = [System.Net.WebRequest]::Create($url)
$request.AllowAutoRedirect=$false
$response = $request.GetResponse()
$realURL = $response.GetResponseHeader("Location")
$response.Close()
$response.Dispose()

# get the current version from that URL
$v = ($realURL -split '/v')[-1]

# create the download URL for the release of choice
# (adjust the end part to target the desired platform, architecture, and package format)
$platform = "win-x64.zip"
$static = "https://github.com/PowerShell/PowerShell/releases/download"
$url = "$static/v$version/PowerShell-$version-$platform"

这段代码生成 ZIP 格式的 64 位 Windows 版下载链接。如果您需要不同的发行版,只需要调整 $platform 中定义的平台部分。

当获得了下载链接,您可以通过它自动完成剩下的步骤:下载 ZIP 文件,取消禁用并解压,然后执行 PowerShell 6:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# define the place to download to
$destinationFile = "$env:temp\PS6\powershell6.zip"
$destinationFolder = Split-Path -Path $destinationFile

# create destination folder if it is not present
$existsDestination = Test-Path -Path $destinationFolder
if ($existsDestination -eq $false)
{
$null = New-Item -Path $destinationFolder -Force -ItemType Directory
}

# download file
Invoke-WebRequest -Uri $url -OutFile $destinationFile
# unblock downloaded file
Unblock-File -Path $destinationFile
# extract file
Expand-Archive -Path $destinationFile -DestinationPath $destinationFolder -Force

最终,在桌面上创建一个快捷方式,指向 PowerShell 6 这样可以快捷地启动 shell:

1
2
3
4
5
6
7
8
9
10
11
# place a shortcut on your desktop
$path = "$Home\Desktop\powershell6.lnk"
$obj = New-Object -ComObject WScript.Shell
$scut = $obj.CreateShortcut($path)
$scut.TargetPath = "$destinationFolder\pwsh.exe"
$scut.IconLocation = "$destinationFolder\pwsh.exe,0"
$scut.WorkingDirectory = "$home\Documents"
$scut.Save()

# run PowerShell 6
Invoke-Item -Path $path

PowerShell 技能连载 - 查找最新的 PowerShell 6 发行信息(以及下载地址)

PowerShell 6 是开源的并且在 GitHub 上维护了一个公共的仓库。在仓库中频繁发行新版本。

如果您不希望深入到 GitHub 的前端来获取最新版 PowerShell 6 发行的下载地址,那么可以采用这个 PowerShell 的方法:

1
2
3
4
5
6
7
8
9
10
11
$AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[Net.ServicePointManager]::SecurityProtocol = $AllProtocols

# get all releases
Invoke-RestMethod -Uri https://github.com/PowerShell/PowerShell/releases.atom -UseBasicParsing |
# sort in descending order
Sort-Object -Property Updated -Descending |
# pick the first (newest) release and get a link
Select-Object -ExpandProperty Link -First 1 |
# pick a URL
Select-Object -ExpandProperty HRef

(请注意只有在 Windows 10 1803 之前才需要显式启用 SSL。)

这将货渠道最新的 PowerShell 发行页面的 URL。在页面中,您可以获取到不同平台的下载地址。

不过,还有一个更简单的方法:访问 https://github.com/PowerShell/PowerShell/releases/latest

然而,这并不能提供 URL 和标签信息。而只是被跳转到一个对应的 URL。

以下是两者的混合:使用最新发行版的快捷方式,但是不允许跳转。通过这种方式,PowerShell 将返回完整的 URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[Net.ServicePointManager]::SecurityProtocol = $AllProtocols


# add a random number to the URL to trick proxies
$url = "https://github.com/PowerShell/PowerShell/releases/latest?dummy=$(Get-Random)"

$request = [System.Net.WebRequest]::Create($url)
# do not allow to redirect. The result is a "MovedPermanently"
$request.AllowAutoRedirect=$false
# send the request
$response = $request.GetResponse()
# get back the URL of the true destination page, and split off the version
$realURL = $response.GetResponseHeader("Location")
# make sure to clean up
$response.Close()
$response.Dispose()

$realURL

PowerShell 技能连载 - PowerShell ISE 模块浏览器

如果您在使用内置的 PowerShell ISE,您也许发现 “Module Browser Add-on” 很有用。它十分古老了,是 2015 年发布的,然而您可以方便滴从 PowerShell Gallery 中下载安装它:

1
PS C:\> Install-Module ISEModuleBrowserAddOn -Repository PSGallery -Scope CurrentUser

当这个模块安装好,您就可以这样将它加载到 PowerShell ISE 中:

1
PS C:\> Import-Module -Name ISEModuleBrowserAddon -Verbose

这将在 PowerShell 的右侧打开一个新的 Add-on 面板,其中有三个类别:Gallery,Favorites,以及 My Collection。

“Gallery” 将您连接到在线的 PowerShell Gallery,最初创建该库是为了帮助更容易地发现 PowerShell Gallery 中的在线内容。不过这部分看上去不能工作了。

不过当您点击 “My Collection” 时,将会获取到所有模块,并且当您双击列表中的一个模块时,可以获取模块中的内容,例如包含的命令。您也可以讲一个模块标注为 “Favorite”(它就会出现在 “Favorites” 列表中),卸载一个模块,或通过模块列表底部的按钮打开它。

通过顶部的 “New Module” 按钮,您可以创建一个新的空白 PowerShell 模块:一个向导将引导您完成采集元数据并将建有关文件的所有步骤。

PowerShell 技能连载 - 将 SecureString 转换为字符串

有些时候需要将 SecureString 转换为普通字符串,例如因为您使用了由 Read-Host 提供的安全输入:

1
$secret = Read-Host -Prompt 'Enter Keypass' -AsSecureString

这将提示用户输入密码,并且输入的内容将变为一个 SecureString:

1
2
PS> $secret
System.Security.SecureString

要将它还原为纯文本,请使用 SecureString 来创建一个 PSCredential 对象,它包含了一个解密密码的方法:

1
2
$secret = Read-Host -Prompt 'Enter Keypass' -AsSecureString
[System.Management.Automation.PSCredential]::new('hehe',$secret).GetNetworkCredential().Password

PowerShell 技能连载 - Real-Time Processing for Language Structures

In the previous tip we looked at queues and how they can search the entire file system:

# create a new queue
$dirs = [System.Collections.Queue]::new()

# add an initial path to the queue
# any folder path in the queue will later be processed
$dirs.Enqueue('c:\windows')

# process all elements on the queue until all are taken
While ($current = $dirs.Dequeue())
{
    # find subfolders of current folder, and if present,
    # add them all to the queue
    try
    {
        foreach ($_ in [IO.Directory]::GetDirectories($current))
        {
                $dirs.Enqueue($_)
        }
    } catch {}

    try
    {
        # find all files in the folder currently processed
        [IO.Directory]::GetFiles($current, "*.exe")
        [IO.Directory]::GetFiles($current, "*.ps1")
    } catch { }
}

How would you process the data created by the loop though, i.e. to display it in a grid view window? You cannot pipe it in real-time, so this fails:

$dirs = [System.Collections.Queue]::new()
$dirs.Enqueue('c:\windows')

While ($current = $dirs.Dequeue())
{
    try
    {
        foreach ($_ in [IO.Directory]::GetDirectories($current))
        {
                $dirs.Enqueue($_)
        }
    } catch {}

    try
    {
        [IO.Directory]::GetFiles($current, "*.exe")
        [IO.Directory]::GetFiles($current, "*.ps1")
    } catch { }
# this fails
} | Out-GridView

You can save the results produced by do-while to a variable. That works but takes forever because you’d have to wait for the loop to complete until you can do something with the variable:

$dirs = [System.Collections.Queue]::new()
$dirs.Enqueue('c:\windows')

# save results to variable...
$all = while ($current = $dirs.Dequeue())
{
    try
    {
        foreach ($_ in [IO.Directory]::GetDirectories($current))
        {
                $dirs.Enqueue($_)
        }
    } catch {}

    try
    {
        [IO.Directory]::GetFiles($current, "*.exe")
        [IO.Directory]::GetFiles($current, "*.ps1")
    } catch { }
}

# then process or output
$all | Out-GridView

The same limitation applies when you use $() or other constructs. To process the results emitted by do-while in true real-time, use a script block instead:

$dirs = [System.Collections.Queue]::new()
$dirs.Enqueue('c:\windows')

# run the code in a script block
& { while ($current = $dirs.Dequeue())
    {
        try
        {
            foreach ($_ in [IO.Directory]::GetDirectories($current))
            {
                    $dirs.Enqueue($_)
            }
        } catch {}

        try
        {
            [IO.Directory]::GetFiles($current, "*.exe")
            [IO.Directory]::GetFiles($current, "*.ps1")
        } catch { }
    }
} | Out-GridView

With this approach, results start to show in the grid view window almost momentarily, and you don’t have to wait for the loop to complete.


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU - with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip!ReTweet this Tip!

PowerShell 技能连载 - 用队列代替嵌套

与其使用递归函数,您可能会希望使用一个 Queue 对象,这样在加载新的任务时可以卸载已处理的数据。

Lee Homes 最近贴出了以下示例,它不使用递归调用的方式而搜索了整个文件系统的文件夹树:

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
# create a new queue
$dirs = [System.Collections.Queue]::new()

# add an initial path to the queue
# any folder path in the queue will later be processed
$dirs.Enqueue('c:\windows')

# process all elements on the queue until all are taken
While ($current = $dirs.Dequeue())
{
# find subfolders of current folder, and if present,
# add them all to the queue
try
{
foreach ($_ in [IO.Directory]::GetDirectories($current))
{
$dirs.Enqueue($_)
}
} catch {}

try
{
# find all files in the folder currently processed
[IO.Directory]::GetFiles($current, "*.exe")
[IO.Directory]::GetFiles($current, "*.ps1")
} catch { }
}

try-catch 语句块是必要的,因为当没有文件或文件夹权限时,.NET 方法会抛出异常。

PowerShell 技能连载 - 查找服务特权

Get-Service 可以提供 Windows 服务的基础信息但是并不会列出所需要的特权。以下是一段简短的 PowerShell 函数,输入一个服务名并返回服务特权:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function Get-ServicePrivilege
{

param
(
[Parameter(Mandatory)]
[string]
$ServiceName
)

# find the service
$Service = @(Get-Service -Name $ServiceName -ErrorAction Silent)
# bail out if there is no such service
if ($Service.Count -ne 1)
{
Write-Warning "$ServiceName unknown."
return
}

# read the service privileges from registry
$Path = 'HKLM:\SYSTEM\CurrentControlSet\Services\' + $service.Name
$Privs = Get-ItemProperty -Path $Path -Name RequiredPrivileges

# output in custom object
[PSCustomObject]@{
ServiceName = $Service.Name
DisplayName = $Service.DisplayName
Privileges = $privs.RequiredPrivileges
}
}



PS C:\> Get-ServicePrivilege spooler

ServiceName DisplayName Privileges
----------- ----------- ----------
spooler Druckwarteschlange {SeTcbPrivilege, SeImpersonatePrivilege, SeAuditPrivilege, SeChangeNotifyPrivilege...}



PS C:\> Get-ServicePrivilege XboxGipSvc

ServiceName DisplayName Privileges
----------- ----------- ----------
XboxGipSvc Xbox Accessory Management Service {SeTcbPrivilege, SeImpersonatePrivilege, SeChangeNotifyPrivilege, SeCreateGlobalPrivilege}

PowerShell 技能连载 - 使用变量断点(第 2 部分)

在前一个技能中我们试验了用 Set-PSBreakpoint 在 PowerShell 中创建动态变量断点。我们演示了当一个变量改变时,如何触发一个断点。

然而,如果您希望监视对象的属性呢?假设您希望监视数组的大小,当数组元素变多时自动进入调试器。

在这个场景中,PowerShell 变量并没有改变。实际上是变量中的对象发生了改变。所以您需要一个“读”模式的断点而不是一个“写”模式的断点:

1
2
3
4
5
6
7
8
9
10
11
# break when $array’s length is greater than 10
Set-PSBreakpoint -Variable array -Action { if ($array.Length -gt 10) { break }} -Mode Read -Script $PSCommandPath

$array = @()
do
{
$number = Get-Random -Minimum -20 -Maximum 20
"Adding $number to $($array.count) elements"
$array += $number

} while ($true)

$array 数组的元素超过 10 个时,脚本会中断下来并进入调试器。别忘了按 SHIFT+F5 退出调试器。

PowerShell 技能连载 - 使用变量断点(第 1 部分)

在调试过程中,变量断点可能非常有用。当一个变量改变时,变量断点能够自动生效并进入调试器。如果您知道当异常发生时某个变量变为某个设置的值(或是 NULL 值),那么可以让调试器只在那个时候介入。

以下例子演示如何使用变量断点。最好在脚本的顶部定义它们,因为您可以用 $PSCommandPath 来检验断点所需要的实际脚本文件路径:

1
2
3
4
5
6
7
8
9
10
# initialize variable breakpoints (once)
# break when $a is greater than 10
Set-PSBreakpoint -Variable a -Action { if ($a -gt 10) { break }} -Mode Write -Script $PSCommandPath

# run the code to debug
do
{
$a = Get-Random -Minimum -20 -Maximum 20
"Drawing: $a"
} while ($true)

请确保执行之前先保存脚本:调试始终需要一个物理文件。

如您所见,当变量 $a 被赋予一个大于 10 的值时,调试器会自动中断下来。您可以使用 “exit“ 命令继续,用 “?“ 查看所有调试器选项,并且按 SHIFT+F4 停止。

要移除所有断点,运行这行代码:

1
PS C:\> Get-PSBreakpoint | Remove-PSBreakpoint