You can employ PowerShell Remoting (appeared in PowerShell 2.0) to run commands on one or several remote computers. PS Remoting is based on the Web Services for Direction protocol (WS-Direction). You lot can use the PS remoting interactive session mode, a temporary, or permanent connection to a remote estimator. In this article, we will take a look at several examples of how to execute a PowerShell script remotely.

Configuring WinRM for PowerShell Remoting

To connect to a computer remotely via PowerShell, the WinRM (Windows Remote Management service) must be enabled and configured on the remote client device (it is disabled by default). Communication betwixt computers is performed over HTTP or HTTPS protocols, and all network traffic between computers is encrypted. You can use NTLM and Kerberos to cosign on a remote computer.

To check the condition of the WinRM service, run the Become-service control:

get-service winrm

run powershell script on remote computer

Every bit yous can see, the WS-Management service is running.

If the WinRM service is not running, you must enable information technology on the remote calculator with the control:

Enable-PSRemoting

This command prepares the computer for remote direction: starts the WinRM service, changes startup type to Automated, and adds necessary exceptions to Windows Defender Firewall.

Hint. PowerShell Remoting uses TCP ports HTTP (5985) and HTTPS (5986) for network communications. If Windows Defender Firewall with Advanced Security is enabled on the remote computer, y'all need to enable Windows Remote Direction (HTTP-In) rules:

  • WINRM-HTTP-In-TCP

  • WINRM-HTTP-In-TCP-NoScope

You lot can enable Windows Defender rules from the graphical console or using PowerShell:

Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP" -RemoteAddress Any  Set-NetFirewallRule -Proper noun "WINRM-HTTP-In-TCP-NoScope" -RemoteAddress Any

powershell run script on remote computer

If the remote computer is in a workgroup (not joined to the Active Directory domain), and a Public network contour is practical to information technology (instead of Domain or Private), you demand to explicitly allow incoming WinRM traffic in Windows Firewall:

Set-NetFirewallRule -Proper noun "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

To test the connectedness to a remote server via WinRM use the following command:

Test-WSMan server1

run powershell script remotely

If you go a response, and then the remote computer is attainable through PowerShell Remoting.

Hint. If you are connecting to a remote calculator via PS Remoting by an IP address, y'all may receive an error:

Connecting to remote server 192.168.1.70 failed with the post-obit error message: The WinRM client cannot process the request. Default authentication may be used with an IP accost nether the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided.

In this case, you need to install an HTTPS document for PowerShell Remoting on the remote computer (the long mode), or add this host to the trusted ones on your management computer:

Ready-Particular wsman:\localhost\Client\TrustedHosts -value 192.168.ane.70

And so restart the WinRM service:

Restart-Service WinRM

Running Remote Commands with PowerShell Remoting

To interactively connect to a remote computer (with a hostname Server1) via PowerShell, run the following command:

Enter-PSSession Server1

The PowerShell CLI view will change. At the beginning of the line, at that place will be the name of the remote computer to which you are connected via WinRM. Later the remote session is established, all commands that are existence entered in the PowerShell console are executed on the remote computer. PS Remoting works every bit follows: the commands entered on the local estimator are transmitted to the remote computer and executed at that place, then the upshot is transmitted dorsum. Since all commands are executed locally, at that place is no need to worry about compatibility with the PoSh version and modules.

To end the remote interactive session run the control:

Exit-PSSession

execute powershell script on remote computer

Only the elementary management tasks are typically performed on remote computers in the interactive mode. To run a complex control or run the PowerShell script remotely, use the Invoke-Command cmdlet.

Using Invoke-Control to Run PowerShell Scripts Remotely

The post-obit command volition create a remote connection with the computer Server1 and run the block of commands specified in the ScriptBlock parameter. Later on that, the remote session will automatically close.

Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName server1

If yous need to execute multiple sequential PowerShell commands on a remote machine, split up commands in the ScriptBlock using semicolons:

Invoke-Command -ScriptBlock {Restart-Service spooler;Get-Date; wmic qfe listing} -ComputerName server1

You can run the chore in the background by running Invoke-Control with the -AsJob parameter. Just in this case, the command volition not render the result to the PoSh console. To get the detailed background job data, employ the Receive-Job cmdlet.

how to run powershell script on remote computer

PowerShell allows you to run local PS1 scripts on remote computers. The idea is that yous store all PowerShell instructions in a local .PS1 file on your computer. With PowerShell Remoting, you tin transfer a PS1 file to a remote computer and execute information technology in that location.

To do this, utilize the -FilePath parameter in the Invoke-Command cmdlet instead of -ScriptBlock. For example, to run the c:\ps\tune.ps1 script on iii remote servers, you can use the following command:

Invoke-Command -FilePath c:\ps\tune.ps1 -ComputerName server1,server2,server3

run powershell on remote computer

The PowerShell script file tin can be placed on a local drive or a shared network folder. In this case, to run the PS1 script file you need to specify the full UNC path:

Invoke-Command -FilePath "\\dc03\Share\pstune.ps1" -ComputerName PCS12dd2

execute powershell script remotely

The main reward of this way of running PowerShell scripts is that you don't need to re-create the PS1 script file to remote computers. You tin use not only the local script simply also the PS script in a shared network folder that can be accessed from the local computer.

If PowerShell scripts are non allowed to run on the remote figurer, an mistake will appear:

Invoke-Command : File c:\Share\pstune.ps1 cannot be loaded because running scripts is disabled on this system. For more than information, encounter about_Execution_Policies

powershell execute script on remote computer

Y'all can change the PowerShell Execution Policy settings on a remote computer according to this guide or sign your PowerShell script file with a document.

If you need to run PowerShell scripts with credentials other than the electric current user, you lot need to apply the Credential parameter.

First, yous need to get the credential and salve them to a variable:

$cred = Get-Credential

run a powershell script on a remote computer

At present yous can run the PS script on remote computers nether the saved credential permissions:

Invoke-Control -FilePath c:\ps\tune.ps1 -ComputerName server1,server2,server3 -Credential $cred

Yous can save the list of computers in a text file and run PowerShell script remotely on all computers at once:

Invoke-control -ComputerName (become-content c:\ps\servers.txt) -filepath c:\ps\melody.ps1

By default, the Invoke-Command cmdlet sends the PS1 script to 32 remote computers from the listing at the same time. If at that place are more than 32 computers, then PoSh checks the execution status of the script on the get-go 32 computers. If the script is completed, the command is executed on the side by side computer. With the ThrottleLimit parameter, yous tin increase this limit, but exist careful not to overload your network.

When you run the Invoke-Command cmdlet on multiple computers, you can pre-check if the remote calculator is accessible via WinRM. If the estimator is available, yous can run PowerShell code on it using Invoke-Command:

$RemoteComputers= get-content c:\ps\servers.txt  ForEach $RemoteComputer in $RemoteComputers)  {  If (Test-WSMan -ComputerName $RemoteComputer)  {  Invoke-Command -ComputerName $RemoteComputer -FilePath c:\ps\tune.ps1  }

If you lot want to pass local session variables to a remote PowerShell session utilize the $Using modifier:

$name="script1.ps1"
Invoke-Command -ComputerName dc03 -Scriptblock{ write-host $using:Name}

Yous tin use the ConnectionUri parameter in Invoke-Command to run the control confronting backend applications similar Exchange or Azure/AWS deject services. For example:

$Creds = Get-Credential  $params = @{  ConfigurationName = 'Microsoft.Exchange'  ConnectionUri = 'https://lonexch1.theitbros.com/PowerShell'  Credential = $Creds  Authentication = 'Bones'  ScriptBlock = {Fix-Mailbox BJackson -DisplayName "Brian Jackson"}  }  Invoke-Command @params

Using Persistent PowerShell Connections (Sessions)

Each fourth dimension you run Invoke-Command, a new session is created with the remote computer. This takes time and system resource. In PowerShell, y'all tin create one session and execute all commands and scripts in it.

Using the New-PSSession cmdlet, yous can create persistent PowerShell sessions with remote computers.

For example, let'south create sessions with three computers and save them in the $PSSess variable:

Invoke-Control -FilePath c:\ps\melody.ps1 -ComputerName server1,server2,server3  $PSSess = New-PSSession -ComputerName server1, server2, server3

Later establishing a session, you can apply it to run commands and scripts. Because sessions are persistent, yous can get data from them and use it in other commands and scripts.

For example, the post-obit command will get a list of processes on remote servers and store them in the $RemoteProcesses variable:

Invoke-Control -Session $PSSess {$RemoteProcesses = Get-Process}

Now y'all tin employ this variable in other commands in the same sessions. In the post-obit example, we use the Where-Object cmdlet to find processes that use more than 500MB of RAM):

Invoke-Control -Session $PSSess {$RemoteProcesses | where-object {$_.WorkingSet -GT 500000*1024}|select processname,@{l="Working Memory (MB)"; e={$_.workingset / 1mb}} |sort "Working Memory (MB)" -Descending}

run powershell script on remote computer with parameters

The persistent remote PowerShell session will remain active until yous close the PowerShell console, or forcefully close or delete the session using the Disconnect-PSSession or Remove-PSSession cmdlets, respectively.

As you tin can come across, PowerShell provides ample opportunities for running scripts and commands on remote computers. Windows administrators surely can use PowerShell Remoting in addition to the classic PsExec tool from Sysinternals.

  • Author
  • Recent Posts

Cyril Kardashevsky

I enjoy technology and developing websites. Since 2012 I'm running a few of my ain websites, and share useful content on gadgets, PC administration and website promotion.

Cyril Kardashevsky