Executing Remote Commands in PowerShell

Updated on November 21, 2023
Executing Remote Commands in PowerShell header image

PowerShell is a powerful command console included with modern versions of Windows. One of its most useful features is the ability to run commands on remote servers. This can be useful to system administrators that manage multiple Windows servers.

Step 1: Allowing remote access

First, we need to allow remote access. On the server that you want to access remotely, open PowerShell with administrative privileges (so right-click PowerShell and click "Run as administrator"). Execute the following command:

Enable-PSRemoting -Force

This starts the WinRM service, makes sure it starts automatically, and configures your firewall so that it allows incoming connections.

On the computer (that you want to connect from), execute the following command with administrative privileges:

Enable-PSRemoting -Force

We will need to make sure both computers trust each other. To do this, we need to configure the "TrustedHosts" setting. If you want to allow connections to your computer/server from all computers, execute:

Set-Item wsman:\localhost\client\trustedhosts *

If you want to restrict this to certain computers, then use the following command. Replace the comma-separated list of 0.0.0.0, 1.1.1.1, 2.2.2.2 and 3.3.3.3 with IP addresses that will get access.

Set-Item wsman:\localhost\client\trustedhosts 0.0.0.0,1.1.1.1,2.2.2.2,3.3.3.3

Now restart WinRM:

Restart-Service WinRM

Step 2: Test the connection

In order to test the connection, go to the computer that you want to connect from, and execute:

Test-WsMan ipaddress

Replace ipaddress with the IP address of the other computer/server.

Step 3: Opening the ports

The first command that we executed (Enable-PSRemoting -Force) will automatically configure the firewall so that it accepts incoming connections for remote access. However, if there is something in front of the firewall (such as your router), you may have to setup port forwarding too. The ports used are:

  • 5985 for HTTP
  • 5986 for HTTPS

Step 4: Executing commands

The following is used to execute commands on a remote server:

Invoke-Command -ComputerName ipaddress -ScriptBlock { command } -credential username

Replace ipaddress with the IP address of the server, command with the command you want to execute on that server, and username with the username of the user that will run the command.

If you do not want to use Invoke-Command for every single command, you can start a session instead. Every command that you type will then will be executed on the remote server with the credentials specified. The syntax to start a session is as follows:

Enter-PSSession -ComputerName ipaddress -Credential username

Replace ipaddress with the IP address of the server and username with user that will run the command. Every command that you type going forward will be executed on the remote server.