下面的代码将演示 Runspaces 的 Synchronized 变量的用法。您可以为 $ComputerName 使用任何 ip/主机名,只要它可以访问,Powershell 远程处理由 Enter-PSSession 验证,并且您将 $ComputerName 的凭据添加到 Windows 凭据管理器作为主机。
Get-Runspace | ? Id -NE 1 | % { $_.close() ; $_.dispose() }
$Runspace = $powerShell = $connectionInfo = $handle = $hash = $null
$ComputerName = '192.168.0.3'
$hash = [hashtable]::Synchronized(@{})
$hash.One = 1
Write-host ('Value of $Hash.One before background runspace is {0}' -f $hash.one) -ForegroundColor Green -BackgroundColor Black
$Uri = New-Object System.Uri("http://$($ComputerName):5985/wsman")
$connectionInfo = New-Object System.Management.Automation.Runspaces.WSManConnectionInfo -ArgumentList $Uri
$connectionInfo.AuthenticationMechanism = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Negotiate
$connectionInfo.OpenTimeout = 3000
$Runspace = [runspacefactory]::CreateRunspace($connectionInfo) # don't work
#$Runspace = [runspacefactory]::CreateRunspace() # works
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Hash',$hash)
$powershell = [powershell]::Create()
$powershell.Runspace = $runspace
$powershell.AddScript({
$hash.one++
}) | Out-Null #The Out-Null at the end is used to prevent the output of the object that occurs.
$handle = $powershell.BeginInvoke()
While (-Not $handle.IsCompleted) {
Start-Sleep -Milliseconds 100
}
$powershell.EndInvoke($handle)
$runspace.Close()
$powershell.Dispose()
Write-host ('Value of $Hash.One after background runspace is {0}' -f $hash.one) -ForegroundColor Green -BackgroundColor Black
一旦我更换:
$Runspace = [runspacefactory]::CreateRunspace()
和
$Runspace = [runspacefactory]::CreateRunspace($connectionInfo)
(因为我想在远程计算机上执行代码),同步变量 $hash 没有更新。有人知道我错过了什么吗?此功能非常重要且有用,我需要它才能使其适用于远程运行空间。