Run PowerShell Commands On Remote Computer

In this post we are going to look at running commands on a remote server using PSRemoting sent using the WS-Managment technology WinRM protocol.

Firstly you need to make sure WinRM is enabled:

WinRM is enabled by default on Windows Server 2012 R2 but disabled on all client operating systems earlier than Windows Server 2012.

WinRM is a Microsoft implementation of WS-Management Protocol. Read more

It allows for better inventory of systems running Windows compared to WMI and is relatively easy to setup. It can be done through a GPO in your Active Directory.

If PSRemoting is not enabled via GPO or isn’t set to default enabled you can run thee commands below-

Enable-PSRemoting force

# Set WinRM to automatic
Set-Service WinRM -StartMode Automatic
 
# Check startmode and run service
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}

# Trust all hosts
Set-Item WSMan:localhost\client\trustedhosts -value *
 
# Verify trusted hosts config
Get-Item WSMan:\localhost\Client\TrustedHosts
 

PSRemoting brief:

  1. Invoke-Command if you’re only going to run one command against a system
  2. Enter-PSSession if you want to create a session with a computer
  3. Use PowerShell sessions when you’re going to run multiple commands on multiple systems

Start remote PowerShell interactive session on remote computer:

Enter-PSSession -ComputerName COMPUTER -Credential “myDomain\adminusername

Start remote PowerShell interactive session using your current account (most PSRemote commands can be run as just the default user)

Enter-PSSession -ComputerName COMPUTER

To run a script located on a remote computer –

Invoke-Command -ComputerName COMPUTER -ScriptBlock {Invoke-Expression “C:\scripts\leavedomain.ps1” } -credential “myDomain\adminusername

Run single commands –

Invoke-Command -ComputerName COMPUTER -ScriptBlock {Invoke-Expression “shutdown -r” } -credential “myDomain\adminusername

Test WinRM connection:

Test-WsMan COMPUTER

Remote connection to Exchange server console:

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ServerHostName/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session
Creating background sessions:
Background sessions can come in handy if you want to execute multiple commands against many systems.
New-PSSession –ComputerName server1.domain.com –Credentials “myDomain\adminusername
List of background sessions:
Get-PSSession
Interacting with background sessions:
Enter-PsSession –id 3
Exit Session:
Exit-PsSession
Executing commands through background sessions
Invoke-Command -Session (Get-PSSession) -ScriptBlock {ComputerHostname}
Remove all background Sessions
Get-PSSession | Disconnect-PSSession
Hope this is helpful – let your psremoting adventures begin!

One thought on “Run PowerShell Commands On Remote Computer

Leave a comment