我有一个简单的脚本来迭代主机阵列并远程运行命令。
$myHost = @("hostA")
$command = { hostname }
foreach ($i in $myHost) {
Write-Host $i
$session = New-PSSession -ComputerName $i -Credential $cred
$res = Invoke-Command -Session $session -ScriptBlock $command
if ($?) {
$res
}
Remove-PSSession -Session $session
}
当我Get-PSSession
时,我仍然可以看到会话处于活动状态。
答案 0 :(得分:0)
稍微调整一下。有时,Powershell将Invoked运行空间保存为会话。
$myHost = @("localhost")
$command = { hostname }
foreach ($i in $myHost) {
Write-Host $i
$session = New-PSSession -ComputerName $i -Credential $cred
$res = Invoke-Command -Session $session -ScriptBlock $command
if ($?) {
$res
}
# Get all the sessions and remove at once.
Get-PSSession | Remove-PSSession
}
希望有所帮助