Tag Archives: try catch

Check which servers have powershell remote enable

Sometimes you need to run a Powershell remote script on a big number of servers or computers. Powershell remoting can often fail and it can be all kinds of reasons of failing, powershell remoting is disabled, a firewall or two is blocking the connection or you don’t have the permission on the remote computer to enter a powershell remote session. I ended up in one of this scenarios the other day were I had local administrator permission on all the servers and an open firewall but still couldn’t enter a remote session on a bunch of servers. I put together this simple script that first collects all of our servers from the Active Directory and then creates an empty array to collect the result from the foreach-loop later in the script:

After that I take the result from the Get-ADComputers and and crunch it through a foreach-loop where I try to enter powershell remote sesssion with all the servers that I collected in the previous step . I use the ErrorAction parameter with the stop switch to get an terminating error. When I get an terminating error that is when Enter-PSSession fail, the code inside the catch braces will run and there I just add the server name to the array I created earlier:

When the script is done I will end up with all the failed servers in the $serversNoPsr variable.

Full script: