May 14 2020
Management

A 4-Step Guide to Running Remote Powershell

PowerShell Remoting allows admins to execute scripts remotely, just as if they were on their local computer.

PowerShell is a vital task-automation and configuration management tool for Microsoft whose many features include making it possible for system administrators to connect to remote computers and run scripts on them. Using a feature called PowerShell Remoting, administrators can remotely execute PowerShell scripts just as if they were on their local computer.

Let’s examine how to run a remote PowerShell script in an Active Directory domain on Windows computers. Let’s assume that both the source and destination computers are joined to an Active Directory domain and the logged-in user is a domain user.

1. Enabling Remote PowerShell

PowerShell Remoting is enabled by default on most modern Windows computers. However, if for some reason it’s not already set up, admins may enable it via the Enable-PSRemoting cmdlet. On the remote computer, run Enable-PSRemoting-Force. This command starts the WinRM service, sets it to auto-start and creates a firewall rule to allow WinRM connections without confirmation.

2. Create the Remote Powershell Script

Admins can remotely run any PowerShell script, but they must first build one. Admins should put together the script they’d like to run on the remote Windows computer and save it on the local computer where it will run. Let’s say it’s called myscript.ps1. Write the code just as if it were running on the local computer.

3. Run Powershell Invoke-Command

Once the script is on the local computer, specify the computers it should run on and the path where it’s stored. To do this, run Invoke-Command, providing computer names to the ComputerName parameter and the path to the script to the FilePath parameter like below:

Invoke-Command -ComputerName SRV1,SRV2 -FilePath C:\Scripts\myscript.ps1

When Invoke-Command runs, it will copy the PowerShell script to the remote computer and execute it just as if the administrator was on the remote computer’s local console.

4. Verify the Result

When the script finishes running, an admin can then verify the result. Again, using Invoke-Command, connect to the remote computer. This time, however, use the Scriptblock parameter instead of the file path parameter.

For example, if script.ps1 was supposed to create a file, an admin could verify this file was created using the following command:

Invoke-Command -ComputerName SRV1,SRV2 -Scriptblock { Test-Path -Path 'C:\file.txt' }

loops7/Getty Images
Close

See How Your Peers Are Moving Forward in the Cloud

New research from CDW can help you build on your success and take the next step.