PowerShell Closing open sessions

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:

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-PSSessionto 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:

Source:

PowerShell Closing open sessions by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply