2

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.

Razvan Zoitanu
  • 635
  • 1
  • 10
  • 26
  • Have you tried just recreating it? Call `$PSDomainSession = New-PSSession -ConnectionUri $Uri -Credential $DomainCredential -Verbose` again after the machine comes back online – Mathias R. Jessen Apr 27 '15 at 14:23
  • Thank you, it does work. However I'd like to cleanup the sessions as I'll deploy multiple machines and don't want the list to become too long and confusing. – Razvan Zoitanu Apr 27 '15 at 14:51
  • 1
    Is " Remove-PSSession -Session $PSDomainSession" an option? ( https://technet.microsoft.com/en-us/library/hh849722.aspx) – Andy Apr 27 '15 at 15:20

1 Answers1

2

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
Mathias R. Jessen
  • 24,907
  • 4
  • 62
  • 95
  • 2
    Great, all good now ! Should have figured this out myself with Get-Command *PSSession as I already knew about Get-PSSession. This works as well: Get-PSSession | Where-Object {$_.State -eq "Closed" -or $_.State -eq "Broken"} | Remove-PSSession -Verbose – Razvan Zoitanu Apr 27 '15 at 16:13