Bobcares

Run Scripts on Remote Computers – PowerShell Remoting

by | Apr 1, 2021

Don’t know how to run Scripts on Remote Computers? We can help you.

PowerShell helps us to run commands remotely on one or more computers in our network.

As part of our Server Management Services, we assist our customers with several such queries.

Today, let us see how to run scripts on Remote Computers.

 

Run Scripts on Remote Computers

The Invoke-Command cmdlet uses remote management features from PowerShell Remoting.

PowerShell Remoting allows connecting remotely to PowerShell sessions on computers via WinRM service and WS-Management protocol.

In this article, our Support Techs shows how to use the Invoke-Command cmdlet to run PowerShell commands remotely.

 

Configure WinRM for PowerShell Remoting

PowerShell Remoting uses HTTP or HTTPS to communicate between computers.

In order to begin, the remote computer we are going to connect should run WinRM.

To check the WinRM service status, we run:

Get-Service -Name “*WinRM*” | fl

We start the service if it is not:

Enable-PSRemoting
WinRM has been updated to receive requests.
WinRM service started.
WinRM is already set up for remote management on this computer.

This command starts the WinRM service, sets the default winrm settings, and adds exception rules to Windows Firewall.

Then we can connect to the computer remotely using PowerShell Remoting.

However, if the network type is Public, the command returns the following error:

Set-WSManQuickConfig : … WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.

In such a case, we change the network location to Private or use the command:

Enable-PSRemoting –SkipNetworkProfileCheck.

Also, enable the Windows Defender Firewall rule that allows access to WinRM in public networks:

Set-NetFirewallRule -Name ‘WINRM-HTTP-In-TCP’ -RemoteAddress Any

In order to test the connection to a remote computer via PowerShell Remoting, we run:

Test-WsMan compname1

If we do not have an Active Directory domain, we use the NTLM protocol for authentication.

When using NTLM, if we try to run Invoke-Command we may come across the error:

PS C:\> Invoke-Command -ComputerName 192.168.1.201 -ScriptBlock {get-services}
[192.168.1.201] Connecting to remote server 192.168.1.102 failed with the following error message: The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions: thetransport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. + FullyQualifiedErrorId: CannotUseIPAddress,PSSessionStateBroken

To make NTLM authentication work on a computer to connect, we need to issue an SSL certificate or add the hostname/IP address to the trusted host list:

Set-Item wsman:\localhost\Client\TrustedHosts -value 192.168.1.201

Or we can allow connection to all computers.

Set-Item wsman:\localhost\Client\TrustedHosts -value *

We must apply the same settings to remote hosts.

To display the list of trusted hosts, we run:

Get-Item WSMan:\localhost\Client\TrustedHosts

Eventually, to apply the changes, restart WinRM:

Restart-Service WinRM

We can also enable and configure WinRM using Group Policies.

 

Run PowerShell Commands Remotely Using Invoke-Command

The Invoke-Command cmdlet allows us to run a command on more than one remote computer.

For example, to run a single command on a remote computer, use:

Invoke-Command -ComputerName dc01 -ScriptBlock {$PSVersionTable.PSVersion}

This command will display the PowerShell version on the remote computer. Enter the command to be run on a remote computer in the -ScriptBlock {[cmdlet]} block.

By default, a command sent via Invoke-Command executes as the current user on a remote computer. To run it as another user, request the user credentials and save them to a variable:

$cred = Get-Credential
Invoke-Command -ComputerName dc01 -Credential $cred -ScriptBlock {Get-NetAdapter}

This displays the list of network interfaces on a remote computer.

We can enter more than one command in the ScriptBlock. For example, the following command displays the current time zone and change it to another one:

Invoke-Command -Computername dc01 -ScriptBlock {Get-TimeZone| select DisplayName;Set-TimeZone -Name “Central Europe Standard Time”}

Invoke-Command allows to run not only individual commands, but also run PowerShell scripts. To do it, instead of –ScriptBlock it uses the -FilePath argument.

In this case, we specify the path to the local PS1 script file on the computer:

Invoke-Command -ComputerName DC01 -FilePath C:\PS\Scripts\CheckSMBversion.ps1

 

Use Invoke-Command to Run Commands on Multiple Computers

We can use the Invoke-Command to run commands on multiple remote computers simultaneously.

In the simplest case, name the computers to run PowerShell commands separately with commas:

Invoke-Command server1, server2, server3 -ScriptBlock {get-date}

We can place the list of computers into a variable:

$servers = @(“server1″,”server2″,”server3”)
Invoke-Command -ScriptBlock { get-date} -ComputerName $servers

Or get from a text file:

Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName(Get-Content c:\ps\servers.txt)

In addition, we can get a list of computers in AD using the Get-ADComputer cmdlet or the PowerShell module.

To run a command in all Windows Server hosts in the domain, use the following PowerShell code:

$computers = (Get-ADComputer -Filter ‘OperatingSystem -like “*Windows server*” -and Enabled -eq “true”‘).Name
Invoke-Command -ComputerName $computers -ScriptBlock {Get-Date} -ErrorAction SilentlyContinue

If a computer is off or unavailable, the script will not stop due to the SilentlyContinue parameter and will continue to run on other computers.

To understand from where the result came, use the PSComputerNamee environment variable.

$results = Invoke-Command server1, server2, server3 -ScriptBlock {get-date}
$results | Select-Object PSComputerName, DateTime

Invoke-Command on multiple computers run simultaneously. It has a restriction on the maximum number of computers to manage at the same time (the default value is 32).

If we want to run a command on more than 32 computers (128, for example), we can use –ThrottleLimit 128.

[Need help with the process? We are here for you]

 

Conclusion

In short, our Support Techs has shown us how to Run Scripts on Remote Computers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF