Tuesday, January 21, 2014

PowerShell Remoting: Invoke-Command

PowerShell remoting allows you to run commands on local and remote computers.

PowerShell Remoting was first introduced with PowerShell v2 which can be installed on any Windows Operating System XP or newer.

     Common problems:
    • Not running an elevated PowerShell prompt.
    • Must be an Administrator to user WinRM.
    • PowerShell Execution is not set
    • PSRemoting is not enabled.
    • The remote computer is not on.
    • Not a member of the domain or a trusted domain.
    • A network adapter is set to public(http & https are blocked by windows firewall) 

First Things First:Don't forget to enable PSRemoting and set a proper execution policy on the computer to want to remotely access.

PS C:\> Set-ExecutionPolicy RemoteSigned -Force
PS C:\> Enable-PSRemoting -Force

To run a command against the local machine:
PS C:\ > Invoke-Command -ScriptBlock{ Hostname } -ComputerName .
PS C:\ >

To run a command against local and remote computers:
Invoke-command -ScriptBlock { Hostname ; Get-Counter '\Processor(_Total)\% Processor Time' } -ComputerName localhost, remoteserver1, remoteserver2

To run a command against a list of computernames:
Invoke-command -ScriptBlock { Hostname ; Get-Counter '\Processor(_Total)\% Processor Time' } -ComputerName (Get-Content $env:USERPROFILE\Desktop\ServerList.txt)

To run a script against remote computers:
Invoke-command -ComputerName localhost, remoteserv1, remoteserver2 -FilePath C:\Scripts\report.ps1 

To run a script against remote computers with alternative credentials:
Invoke-Command -Scriptblock { Hostname ; Get-Counter '\Processor(_Total)\% Processor Time' } -ComputerName SRV-PSWA -Credential kerfoot\matthew

A slightly different remoting method is with the use of Enter-PSSession which will open an interactive session with the remote computer of your choosing.
PS C:\Users\mkerfoot> Enter-PSSession -ComputerName SRV-PSWA
[ SRV-PSWA ] PS C:\ >Get-WmiObject Win32_LogicalDisk | Format-Table -Autosize

DeviceID DriveType ProviderName     FreeSpace          Size VolumeName       
-------- --------- ------------     ---------          ---- ----------       
C:               3               352527327232  479554695168 SSD RAID 0       
E:               3              1079370080256 2000395694080 Kerfoot's Backups
F:               3               499943936000  500109930496 HDD RAID 0       
Z:               5                          0    3406368768 G71-MGD3005      

To exit the remote session type Exit-PSSession or Exit for short.
[ SRV-PSWA ] PS C:\ > Exit-PSSession
PS C:\ >