Forum Discussion
The strange behavior of PowerShell script in disconnected session
Hello!
Could you please explain the strange behavior of PowerShell script in disconnected session?
During execution of following script PowerShell console hangs after first 32 items been processed and I have no other option than to destroy its process forcibly.
$computers = (Get-ADComputer -Filter *).name | select -First 35
Invoke-Command -ComputerName $computers -InDisconnectedSession -ScriptBlock {
$out = $env:COMPUTERNAME
Start-Sleep -Seconds 10
return $out
}
All listed sessions are in busy state.
If number of selected items is limited by 32 or less everything works fine. Also helps using ThrottleLimit argument.
$computers = (Get-ADComputer -Filter *).name | select -First 35
Invoke-Command -ComputerName $computers -InDisconnectedSession -ThrottleLimit $computers.Count -ScriptBlock {
$out = $env:COMPUTERNAME
Start-Sleep -Seconds 10
return $out
}
I guess somehow it could be connected to that default number of simultaneous sessions are limited by 32.
Can you please explain how to correctly work with disconnected sessions if its number a lot much more than 32?
4 Replies
- Animesh JoshiBrass Contributoryou're using -inDisconnectedSession parameter which, disconnects the sessions as soon as it starts the command.
Surely you can use invoke-command on more than 32 computers.
Look at example 7 and 18 on https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7- Dmitry_PopovCopper Contributor
Example 7 without the inDisconnectedSession parameter.
Example 18 hangs with busy status if the number of computers is more than 32.
I found two working crutches for myself, but I would like to understand why it does not work as expected.Crutch 1
$computers = (Get-ADComputer -Filter *).name | select -First 35 Invoke-Command -ComputerName $computers -InDisconnectedSession -ThrottleLimit $computers.Count -ScriptBlock { $out = $env:COMPUTERNAME Start-Sleep -Seconds 10 return $out }Crutch 2
$computers = (Get-ADComputer -Filter *).name | select -First 35 foreach ($item in $computers) { Invoke-Command -ComputerName $item -InDisconnectedSession -ScriptBlock { $out = $env:COMPUTERNAME Start-Sleep -Seconds 10 return $out } }- Mike ShivtorovCopper Contributor
Dmitry_Popov
Just use "ThrottleLimit" parameter to specify the maximum number of concurrent connections. Its default value is 32.For example, 100 connections at a time:
Invoke-Command -ComputerName $computers -InDisconnectedSession -ThrottleLimit 100 -ScriptBlock { hostname }Don't make too many concurrent connections.
In your latest comment you use "-ThrottleLimit $computers.Count" - it might be too high depending on number of computers in your domain. I guess a hundred or two of concurrent sessions should be more than enough.
Get-Help Invoke-Command -Parameter ThrottleLimit