Wednesday, March 4, 2015

PowerShell: A deep dive into remoting – part 1


One of the most important aspects of PowerShell is remoting. Introduced in PowerShell v2, remoting is a complex technology with a lot of confusion around it. I’ll try to go deep into the concepts of powershell remoting and technologies and see how it all works together with different protocols and implementations.
Classic cmdlets that have the –ComputerName parameter:

These commands use their own proprietary communications protocols, most often DCOM or RPC, and are generally limited to a single task. With this type of remoting, it is up to the cmdlet author to choose and implement the appropriate technology. You can find out these commands by using the Get-Command cmdlet and filtering them based on the parameter containing ComputerName as given below.

Get-Command  -CommandType  Cmdlet|? {$_.Parameters.Keys –contains “ComputerName”}

Lets try to see the behavior of couple of these cmdlets for eg. Get-Process and Get-Service. You can invoke both of these cmdlets on a remote computer by using the ComputerName parameter as
Get-Service –ComputerName “COMP1” | select name
Get-Process –ComputerName “COMP1” | select name

PowerShell will try to authenticate to the remote machine using the current user account. If the current user is also added into the Administrators group on the remote machine, you will not face any issues while executing these cmdlets.
Now lets see the behavior of these cmdlets when RemoteRegistry service is stopped on the remote machine.

For that you can use the Get-WmiObject cmdlet to access the service and stop it.
$remoteReg = Get-WmiObject –Class Win32_Service –ComputerName “COMP1” –Filter ‘name=”RemoteRegistry”’
$remoteReg.StopService()

Check the status code returned as part of the StopService method call.

For more details on the ReturnValue from the StopService method on a Win32_Service object refer to this table https://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx

Now if you try to execute the Get-Service cmdlet on the computer, you’ll see that it still works fine, but the Get-Process will throw an error!!!

As you have seen from the examples given, the technology used to implement remoting in these cmdlets vary and is not very transparent to the user. The error messages can also be very confusing when using these cmdlets. Try the Get-EventLog cmdlet and see the error message while remote registry service is stopped.

With PowerShell v2.0, remoting was introduced, which involves transferring the commands to the remote system making use of WinRM service and executing the command on the remote machine. This introduces our next type of cmdlets using remoting like the Invoke-Command and Enter-PSSession.
I’ll explain the details of these cmdlets and WinRM in the next post of the series.

No comments: