重置或删除远程 Powershell 会话

重置或删除远程 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 列出。

答案1

只需等到机器重新上线,然后使用以下命令进行最后清理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

相关内容