Let's say we have two Windows computers in our network, PC1 and PC2, and we want to be able to use PC1 to make a remote connection to PC2 using Windows PowerShell. This is often referred to as PowerShell Remoting, which lets you execute PowerShell commands on a remote computer.
Configure PC1 and PC2 for remoting
Ensure the WinRM service is Runnning. If the WinRM service is not running, Start-Service WinRM.
PS C:\> Get-Service WinRM
Status Name DisplayName
------ ---- -----------
Running winrm Windows Remote Management
Configure WinRM to for remote management using the Set-WSManQuickConfig command.
PS C:\> Set-WSManQuickConfig
WinRM Quick Configuration
. . .
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
WinRM is set up to receive requests on this machine.
WinRM is set up for remote management on this machine.
Configure WinRM for remote management using the Enable-PSRemoting command:
PS C:\> Enable-PSRemoting
WinRM Quick Configuration
. . .
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
WinRM is set up to receive requests on this machine.
WinRM is set up for remote management on this machine.
Configure WinRM to trust the target computer. Hostname can be a single PC, numerous PCs, or a wildcard.
PS C:\> Set-Item WSMan:\localhost\Client\TrustedHosts -Value "hostname" -Force
Connect to target PC
When writing a script using PowerShell ISE, the following can be used so that the interactive pop-up box to authenticate does not appear.
$password = ConvertTo-SecureString "SuperSecretPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $password )
Enter-PSSession -computername target_hostname -credential $cred
Send command to target PC
Note: If you plan to run remote commands on remote computers often, instead of having to manually type the remote computer names, you can store the remote computer names in a text file, and then using the following syntax to get the computer names from the text file: Invoke-Command -computername (Get-Content computer-names.txt) -command {hostname}
A variable can be used for the username and password of the target PC.
$password = ConvertTo-SecureString "SuperSecretPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $password )
Invoke-Command -computername hostname -credential $cred -command {the-command}