Question:
I’m working on a large script where I run a Foreach
loop, define variables in that loop and afterwards check if the $Server
variable is pingable and if it is remotely accessible.
For this I use the following functions coming from the PowerShell help:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# Function to check if $Server is online Function CanPing ($Server) { $error.clear() $tmp = Test-Connection $Server -ErrorAction SilentlyContinue if ($?) { Write-Host "Ping succeeded: $Server"; Return $true } else { Write-Host "Ping failed: $Server."; Return $false } } # Function to check if $Server is remotely accessible Function CanRemote ($Server) { $s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction SilentlyContinue if ($s -is [System.Management.Automation.Runspaces.PSSession]) { Enter-PSSession -Session $s Exit-PSSession Write-Host "Remote test succeeded: $Server."; Return $true } else { Write-Host "Remote test failed: $Server."; Return $false } } # Execute functions to check $Server if ($Server -ne "UNC") { if (CanPing $Server) { if (-Not (CanRemote $Server)) { Write-Host "Exit loop REMOTE" -ForegroundColor Yellow continue } } else { Write-Host "Exit loop PING" -ForegroundColor Yellow continue # 'continue' to the next object and don't execute the rest of the code, 'break' exits the foreach loop completely } } |
Every time when I run this code, there is a process created on the remote server called wsmprovhost.exe
. This process represents the PowerShell session, if the info I found on the web is correct. However, when doing Get-PSSession $Server
there are no open sessions displayed in the PowerShell ISE, even though the processes are visible on the remote server and can only be killed with the Task Manager.
When I run this code often the limit of open sessions is reached because every time a new process wsmprovhost.exe
is added to the $Server
and the command errors out. I’ve tried to solve this by adding Exit-PSSession
to the code, but it doesn’t close the session.
Any help or ideas are more than welcome.
Answer:
The problem is that Enter-PSSession. Enter-PSSession can only be used interactively, you can’t use it in a script. I’d suggest something more like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Function to check if $Server is remotely accessible Function CanRemote ($Server) { Try { $s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction Stop Write-Host "Remote test succeeded: $Server." $true Remove-PSSession $s } Catch { "Remote test failed: $Server." $false } } |