Thursday, March 5, 2015

PowerShell : A deep dive into remoting - part 3

Windows PowerShell contains a PSProvider implementation for WSMan which exposes the WS-Management configuration settings with a directory structure. The settings are grouped as containers for each group of settings.
For e.g. to see the client settings on the machine.
use the Get-ChildItem wsman:\localhost\client cmdlet and you can find all the properties for the client

This information can be used to configure various aspects of the WS-Management client. The configuration information is stored in the registry. For e.g. from the above screenshot you can see that I have added all the computers to the trustedhosts. This is not a very good practice to follow in a real world scenario. It’s better that you can restrict access to only the computers that you trust to remote access the resources.
To change the value of the trusted hosts and only give access to specific computers, you can use the Set-Item cmdlet on the client settings as

Set-Item wsman:\localhost\client\TrustedHosts "COMP1, COMP2" -Force
This will add the COMP1 and COMP2 machines to the trusted hosts and only allow remote connections from those machines. If you want to trust all the computers in your domain, then you can also make use of the wild card implementation as

Set-Item wsman:\localhost\client\trustedhosts "*.yourdomain" -Force
You can also use the Connect-WSMan cmdlet to connect to the WinRM service on a remote computer. The Connect-WSMan cmdlet accepts the name of computer to connect. By default the logged in user credentials are used to connect to the machine. You can also use the -Credential parameter to specify a PSCredential object to impersonate. The  command also supports -Authentication parameter which is used to specify the AuthenticationMechanism. We'll look into the details of Authentication in the upcoming posts of this series.

After you connect to the WinRM service on the remote computer, the remote computer will appear in the root directory of the WSMan provider. You can now query the remote computer as any other PSProvider using the Get-Item, Get-ChildItem cmdlets and even make changes by using the Set-Item
For e.g. if you want to change the TrustedHosts settings for the remote machine COMP1, you can follow the steps given below

Connect-WSMan -ComputerName COMP1 -Credential (Get-Credential -Username "yourdomain\comp1user" -Message "Provide password for COMP1User")
Get-ChildItem wsman:\COMP1\Client

Set-Item wsman:\COMP1\Client\TrustedHosts "*.yourdomain" -Force

No comments: