Powershell – Reset or delete remote Powershell sessions

powershellremote

I run a remote Powershell script to add a machine to a domain. Machine reboots, is added to the domain, all good.

$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 }

When trying to use the previously defined domain credentials session after the machine comes back online:

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

this error comes up:

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

How to reset or delete the existing "broken" sessions for this machine only ? They are listed with Get-PSSsesion.

Best Answer

Just wait until the machine comes back online, and then finally cleanup using 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