PowerShell会话不会消失

时间:2016-12-08 22:09:34

标签: windows powershell

我有一个简单的脚本来迭代主机阵列并远程运行命令。

$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时,我仍然可以看到会话处于活动状态。

1 个答案:

答案 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 
}

希望有所帮助