PowerShell 技能连载 - 解码 PowerShell 命令

当您需要在一个独立的 powershell.exe 以一个 PowerShell 命令的方式执行代码时,并不十分安全。这要看您从哪儿调用 powershell.exe,您的代码参数可能被解析器修改,而且代码中的特殊字符可能会造成宿主混淆。

一个更健壮的传递命令方法是将它们编码并用解码命令提交。这只适用于短的代码。长度必须限制在 8000 字符左右以内。

$code = {
  Get-EventLog -LogName System -EntryType Error |
  Out-GridView
}

$Bytes = [System.Text.Encoding]::Unicode.GetBytes($code.ToString())
$Encoded = [Convert]::ToBase64String($Bytes)

$args = '-noprofile -encodedcommand ' + $Encoded

Start-Process -FilePath powershell.exe -ArgumentList $args

PowerShell 技能连载 - 定义多行文本

当您需要在 PowerShell 中定义多行文本时,通常可以这样使用 here-string:

$text = @"
  I am safe here
  I can even use "quotes"
"@

$text | Out-GridView

值得注意的重点是分隔符包含(不可见的)回车符。必须在开始标记后有一个,在结束标记前有一个。

一个很特殊的另一种用法是使用脚本块来代替:

$text = {
  I am safe here
  I can even use "quotes"
}

$text.ToString() | Out-GridView

虽然代码颜色不同,并且需要将脚本块转为字符串。这种方法有一定局限性,因为脚本块是一段 PowerShell 代码,并且它会被解析器解析。所以您只能包裹一段不会造成解析器混淆的文本。

这个是个不合法的例子,将会造成语法错误,因为非闭合的双引号:

$text = {
  I am safe here
  I can even use "quotes
}

$text.ToString() | Out-GridView

PowerShell 技能连载 - 当前脚本的路径

在 PowerShell 1.0 和 2.0 中,您需要一堆奇怪的代码来获得当前脚本的位置:

# make sure the script is saved and NOT "Untitled"!

$invocation = (Get-Variable MyInvocation).Value
$scriptPath = Split-Path $invocation.MyCommand.Path
$scriptName = $invocation.MyCommand.Name

$scriptPath
$scriptName

只有将它放在脚本的根部,这段代码才能用。

从 PowerShell 3.0 开始,事情变得更简单了,并且这些特殊变量在您脚本的任意地方都可以用。

# make sure the script is saved and NOT "Untitled"!

$ScriptName = Split-Path $PSCommandPath -Leaf
$PSScriptRoot
$PSCommandPath
$ScriptName

PowerShell 技能连载 - 发现动态参数

在前一个技能中我们展示了如何查找暴露了动态参数的 cmdlet。现在让我们来探索什么事动态参数。这个 Get-CmdletDynamicParameter 函数将返回一个动态参数的列表和它们的缺省值:

#requires -Version 2
function Get-CmdletDynamicParameter
{
  param (
    [Parameter(ValueFromPipeline = $true,Mandatory = $true)]
    [String]
    $CmdletName
  )

  process
  {
    $command = Get-Command -Name $CmdletName -CommandType Cmdlet
    if ($command)
    {
      $cmdlet = New-Object -TypeName $command.ImplementingType.FullName
      if ($cmdlet -is [Management.Automation.IDynamicParameters])
      {
        $flags = [Reflection.BindingFlags]'Instance, Nonpublic'
        $field = $ExecutionContext.GetType().GetField('_context', $flags)
        $context = $field.GetValue($ExecutionContext)
        $property = [Management.Automation.Cmdlet].GetProperty('Context', $flags)
        $property.SetValue($cmdlet, $context, $null)

        $cmdlet.GetDynamicParameters()
      }
    }
  }
}

Get-CmdletDynamicParameter -CmdletName Get-ChildItem

该函数使用一些黑客的办法来暴露动态参数,这种方法是受到 Dave Wyatt 的启发。请参见他的文章 https://davewyatt.wordpress.com/2014/09/01/proxy-functions-for-cmdlets-with-dynamic-parameters/

PowerShell 技能连载 - 查找带动态参数的 cmdlet

有些 cmdlet 暴露了动态参数。它们只在特定的环境下可用。例如 Get-ChildItem 只在当前的位置是文件系统路径(并且是 PowerShell 3.0 以上版本)时才暴露 -File-Directory 参数。

要查找所有带动态参数的 cmdlet,请试试这段代码:

#requires -Version 2

$cmdlets = Get-Command -CommandType Cmdlet

$cmdlets.Count

$loaded = $cmdlets |
Where-Object { $_.ImplementingType }

$loaded.Count

$dynamic = $loaded |
Where-Object {
    $cmdlet = New-Object -TypeName $_.ImplementingType.FullName
    $cmdlet -is [System.Management.Automation.IDynamicParameters]
  }

$dynamic.Count

$dynamic | Out-GridView

您将只会获得已加载并且包含动态参数的 cmdlet。

PowerShell 技能连载 - 改变 ISE 缩放比例

PowerShell ISE 的右下角有一个缩放滑竿,您也可以用 PowerShell 代码来控制它。

所以,您可以在 $profile 脚本中设置缺省值:

$psise.Options.Zoom = 120

或者,可以写一些代码来戏弄您的同事:

#requires -Version 2

$zoom = $psise.Options.Zoom

# slide in
for ($i = 20; $i -lt 200; $i++)
{
  $psise.Options.Zoom = $i
}

# slide out
for ($i = 199; $i -gt 20; $i--)
{
  $psise.Options.Zoom = $i
}

# random whacky
1..10 |
ForEach-Object {
  $psise.Options.Zoom = (Get-Random -Minimum 30 -Maximum 400)
  Start-Sleep -Milliseconds (Get-Random -Minimum 100 -Maximum 400)
}

$psise.Options.Zoom = $zoom

PowerShell 技能连载 - 在任意 Powershell 版本中解压 ZIP 文件

如果您没有安装 PowerShell 5.0,并且没有安装 .NET Framework 4.5,以下是一个使用 Windows 原生功能解压 ZIP 文件的办法。

不过,如果您安装了资源管理器自定义的 ZIP 文件扩展,这个方法可能不能用。

$Source = 'C:\somezipfile.zip'
$Destination = 'C:\somefolder'
$ShowDestinationFolder = $true

if ((Test-Path $Destination) -eq $false)
{
  $null = mkdir $Destination
}

$shell = New-Object -ComObject Shell.Application
$sourceFolder = $shell.NameSpace($Source)
$destinationFolder = $shell.NameSpace($Destination)
$DestinationFolder.CopyHere($sourceFolder.Items())

if ($ShowDestinationFolder)
{
  explorer.exe $Destination
}

这个方法的好处是在需要覆盖文件的时候,会弹出 shell 的对话框。这个方法也可以解压 CAB 文件。

PowerShell 技能连载 - 在 PowerShell 3.0 和 4.0 中解压 ZIP 文件

PowerShell 5.0 中引入了 ZIP 文件支持,但是如果您安装了 .NET Framework 4.5 并且希望更多地控制解压的过程,请试试这个方法:

#requires -Version 2
# .NET Framework 4.5 required!

Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop

$Source = 'C:\somezipfile.zip'
$Destination = 'C:\somefolder'
$Overwrite = $true
$ShowDestinationFolder = $true

if ((Test-Path $Destination) -eq $false)
{
 $null = mkdir $Destination
}

$Content = [IO.Compression.ZipFile]::OpenRead($Source).Entries
$Content |
 ForEach-Object -Process {
    $FilePath = Join-Path -Path $Destination -ChildPath $_
                [IO.Compression.ZipFileExtensions]::ExtractToFile($_,$FilePath,$Overwrite)
            }
if ($ShowDestinationFolder)
{
    explorer.exe $Destination
}

PowerShell 技能连载 - 解压 ZIP 文件

在 PowerShell 5.0 中,有一个新的 cmdlet 可以解压 ZIP 文件:

#requires -Version 5

$Source = 'C:\somezipfile.zip'
$Destination = 'C:\somefolder'
$Overwrite = $true
$ShowDestinationFolder = $true

Expand-Archive -Path $Source -DestinationPath $Destination -Force:$Overwrite

if ($ShowDestinationFolder)
{
  explorer.exe $Destination
}

PowerShell 技能连载 - 查找打开了 PowerShell 远程操作功能的计算机

在前一个技能中我们演示了如何如何测试一台计算机的端口。在安装了 Microsoft 免费的 RSAT 工具之后,您可以查询您的 Active Directory,并获取所有计算机用户的列表,或指定范围内的所有计算机账户(例如用 -SearchBase 限制在一个特定的 OU 中搜索)。

下一步,您可以使用该端口来测试这些计算机是否在线,以及 PowerShell 远程操作端口 5985 是否打开:

#requires -Version 1 -Modules ActiveDirectory
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000)

    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one

            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch
    {
        $false
    }
}

Get-ADComputer -Filter * |
Select-Object -ExpandProperty dnsHostName |
ForEach-Object {
    Write-Progress -Activity 'Testing Port' -Status $_
} |
Where-Object -FilterScript {
    Test-Port -ComputerName $_
}