Pages

Sunday 20 February 2011

Remote Powershell

On my travels I picked up this useful method of remoting into another machines powershell. Windows 7 and Server 2008 R2 have WinRm packed inside so you dont need to download anything. If your not sure you can try typing the following:

[PS] Get-Service winrm

On the server you want to remote into (lets call it the target), type the following:

[PS] Enable-PSRemoting

This command will start the WinRM service and sets the startup type to Automatic.  It will also enables a firewall exception for WS-Management communications and create a listener to accept requests on any IP address.
The next step involves establishing which machines can connect to the target (that is your client). On the target type the following:

[PS] cd wsman:
(note the colon:)
[PS] cd localhost\client
[PS] dir

You should see a table displayed indicating that the TrustedHosts has a no value. This has to be changed so that your client can connect. To do this type the following but note you MUST be in the WSMan namespace as shown above!

[PS] Set-Item TrustedHosts *

You should then restart the WinRm service

[PS] Restart-Service winrm 

You could have performed the action by typing one single cmdlet:

[PS] Set-Item WSMan:\localhost\Client\TrustedHosts *


Now that your target is configured, you need to configure the client. Type the following:

[PS] New-PSSession -computername "FQDN of the Target"

You should now see a table displayed referencing your session with an ID number. To display the session created at any time type the following:

[PS] Get-PSsession

To enter the session type the following:

[PS] Enter-PSsession -id (the numerical value of the session e.g. 1)

You should now be in the remote powershell! To end the session type the following:

[PS] Exit-PSsession

and to remove the seesion entirely type the following:

[PS] Remove-PSsession




If you want to connect to the powershell of Exchange 2010, you can do so by doing the following:

You first need to create a session variable (this I've called session) that creates a new PSsession. This time we use a ConnectionUri rather than a computer FQDN like above.Notice the use of the IIS virtual directory. You can see in the command below that you also need to specify a credential of the connecting user.

[PS] $session = New-PSSession -Configurationname Microsoft.Exchange –ConnectionUri http://servername/powershell -Credential (DomainName\UserName)

You should be prompted to provide the password of the account used. Now that your session is stored you can import the server-side powershell session to the client side one. To do this type the following:

[PS] Import-PSSession $session

It takes some time to import the exchange cmdlets. Once it is completed, you can use all exchange cmdlets in your Windows Powershell session.

As before you can remove the session one your done by the typing the following:

[PS] Remove-PSSession $session


No comments:

Post a Comment