Saturday, 28 March 2015

Enable Remote PowerShell and Run Commands

You can enable powershell remoting on computers running Windows 7 and later versions which includes WinRM 2.0 or later. The Windows PowerShell Remoting features are supported by the WS-Management protocol and the Windows Remote Management (WinRM) service that implements WS-Management in Windows.

Follow the below steps to enable PowerShell Remoting:

Start Windows PowerShell with elevated privilege (Run as Administrator) by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator.

Case 1: If your computers (local and remote machine) are in the same domain network, then run the following powershell commands in remote machine to enable PS Remoting in the remote system.
1. Enable-PSRemoting -Force
2. Restart-Service WinRm
Case 2: If your computers (local and remote machine) are in different domain or work group, then you need to configure the Trusted hosts settings in both the systems.

Run the following command in PowerShell (both local and remote machines)
1. Enable-PSRemoting -Force
2. Set-Item wsman:\localhost\client\trustedhosts -Value <IP_ADDRESS_OF_THE_OTHER_SYSTEM>
3. Restart-Service WinRm

Test Powershell Remote Connection:

You can use the Test-WsMan cmdlet to test your remote configuration settings. This command tests whether the WinRM service is running on the remote computer and the computers can communicate with each other.
Test-WsMan MCOM12
Enable PowerShell Remoting and Run commands on Remote Computer

Run Remote Powershell Commands:

Use the powershell cmdlet Invoke-Command to run a command on the remote system.

Syntax of remote powershell command:
Invoke-Command -ComputerName COMPUTER -ScriptBlock { COMMAND } -credential USERNAME
COMPUTER - The name of the computer to connect.
COMMAND - The powershell command to run in remote computer
USERNAME - The user account to run the command as on the remote computer. You will be prompted to enter a password for the username.

The below sample execute the command on the remote computer MCOM12, find the remote host name and display as output.
Invoke-Command -ComputerName MCOM12 -ScriptBlock { 'This command running on {0}.' -f (hostname) } -Credential (Get-Credential)

Advertisements
Advertisements

No comments:

Post a Comment