重置或删除远程Powershell会话

我运行一个远程PowerShell脚本来添加一台机器到一个域。 机器重新启动,被添加到域,都很好。

$Uri = Get-AzureWinRMUri -ServiceName $ServiceName -Name $VMName -Verbose $PSSession = New-PSSession -ConnectionUri $Uri -Credential $Credential -Verbose $PSDomainSession = New-PSSession -ConnectionUri $Uri -Credential $DomainCredential -Verbose Invoke-Command -Session $PSSession -ScriptBlock { Add-Computer -DomainName $Using:DomainName -Credential $Using:DomainCredential -Restart -Passthru -Verbose } 

在机器恢复联机后,尝试使用之前定义的域凭证会话时:

 Invoke-Command -Session $PSDomainSession -ScriptBlock { ps } 

这个错误出现了:

 Cannot invoke pipeline because runspace is not in the Opened state. Current state of runspace is 'Broken'. + CategoryInfo : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], InvalidRunspaceStateException + FullyQualifiedErrorId : InvalidSessionState,myvm.cloudapp.net 

如何重置或删除仅限本机的现有“已损坏”会话? 它们与Get-PSSsesion一起列出。

等待机器恢复联机,然后使用Remove-PSSession进行最后的清理:

 $Uri = Get-AzureWinRMUri -ServiceName $ServiceName -Name $VMName -Verbose $PSSession = New-PSSession -ConnectionUri $Uri -Credential $Credential -Verbose $PSDomainSessionCreate = { New-PSSession -ConnectionUri $Uri -Credential $DomainCredential -Verbose } Invoke-Command -Session $PSSession -ScriptBlock { Add-Computer -DomainName $Using:DomainName -Credential $Using:DomainCredential -Restart -Passthru -Verbose } # Wait for machine to restart $PSDomainSession = &$PSDomainSessionCreate # Use $PSDomainSession to configure the machine # Then cleanup using the Remove-PSSession cmdlet as suggested by @Andy Remove-PSSession -Session $PSSession,$PSDomainSession