Auto reconnect to a server you just rebooted with PowerShell 3.0
Yesterday I saw a tweet that caught my eye:
Sounds familiar? What do you usually do to reconnect to your server once it is back online? How do you monitor it’s availability? In this post, Justin shares a great function (115 lines) that restarts a server, waits for it to come back online and then starts a remote desktop connection to it.
Now, what if I told you that in PowerShell 3.0 you can replace that function with only two lines of code?
In PowerShell 3.0, the Restart-Computer cmdlet got improved (mainly to support Workflow scenarios) and it now supports a few more parameters, notably the –Wait and –For parameters. When –Wait is specified, the command waits for all of the following service types to be available (can take a lot of time) before you can proceed to the next line of code. The following command lists the service types:
Actually, these types are the possible values of the –For parameter. In the previous CTP version, there used to be a ‘Network’ type too, but looks like it was removed. We can specify one of above types, Restart-Computer waits for that component only to be available and then the rest of our code is executed.
In our case, we need to wait for the Remote Desktop Services service to start, but there’s no related service type we can use for that. We can wait for the ‘Wmi’ service. That’s because the WMI and the RDS services are dependent on the Remote Procedure Call (RPC) service, so if the WMI service is started we can assume that the RDS service is up as well.
Restart-Computer –ComputerName Server1 -Wait -For Wmi –Force
mstsc –v Server1 /admin
That’s all it takes to connect to Server1 once it’s back online. Notice that the Restart-Computer command may fail if there are users logged on to the remote computer or if there are opened applications, so make sure you include the –Force switch. One “caveat” though, the command waits until the computer has finished restarting and doesn’t give back your prompt, you’re stuck waiting for it to finish. To continue working you can spin a new background job:
Restart-Computer –ComputerName $args -Wait -For Wmi–Force
mstsc -v $args /admin
} -ArgumentList Server1