How-to: Run a powershell script on a remote computer

To enable PowerShell Remoting, on the PC to which you want to make remote connections run the following command:

PS C:\> Enable-PSRemoting -Force

This should be done from a PowerShell session with Elevation/administrative privileges.

If you don’t have easy physical access to the remote machine and don’t want to RDP onto it, you can perform this step using PsExec (assuming you have admin rights to the remote machine). From an elevated command prompt:

C:\Demo> PSEXEC \\workstation64 -h powershell
C:\WINDOWS\system32> Enable-PSRemoting -Force
C:\WINDOWS\system32> Exit

The exit command will end the remote session and return you to a local command session.

Enabling PSRemoting will start the WinRM service, set it to start automatically, and create a firewall rule that allows incoming connections. To check that this is running, use Test-WSMan, which should return the product version, if the command fails, you’ll see an error message instead.

PS C:\> Test-wsman -computername workstation64

To start an interactive session with the remote computer, use Enter-PSSession:

PS C:\> Enter-PSSession -ComputerName workstation64

From there you will notice the prompt will change to indicate the remote computer name, and you can run multiple commands. When finished use Exit-PSSession to terminate the connection:

workstation64\PS> exit-pssession

An alternative to using Enter-PSSession/Exit-pssession, if you just need to run one command, is to use Invoke-Command:

PS C:\> Invoke-Command -ComputerName workstation64 -ScriptBlock { Get-ChildItem C:\ }

Invoke-Command will also accept a list of computers for the -ComputerName parameter, this enables you to run the same PowerShell script remotely on multiple computers at once.

If the remote computer is in a workgroup (not joined to an Active Directory domain), and a Public network profile is applied to it, you will need to explicitly allow incoming WinRM traffic in Windows Firewall.

The cmdlets for remote connections have options to specify alternate credentials, see the individual pages for examples of that.

“Why do we travel to remote locations? To prove our adventurous spirit or to tell stories about incredible things? We do it to be alone amongst friends and to find ourselves in a land without man” ~ George Mallory (Mountain climber)

Related PowerShell Cmdlets

Enable-PSRemoting - Configure the computer to receive remote commands.
Enter-PSSession - Start an interactive session with a remote computer.
Exit-PSSession - End an interactive session with a remote computer.
About WS-Management Cmdlets.

Copyright © 1999-2023
Some rights reserved