PowerShell Invoke-Command Tutorial

Windows PowerShell provides the Invoke-Command tutorial in order to run commands locally or the remote systems. The Invoke-Command is used with the PSSession where the New-PSSession is used to create PSSession for the remote system.

Run Command Locally

The Invoke-Command can be used to call and execute a command or script in the local system. The -ComputerName is used to express the computer name. The -ScriptBlock option is used to set the script block of to be executed.

PS> Invoke-Command -ComputerName MyComputer -ScriptBlock {Get-Process -Name 'chrome'}

Run Command On Remote System

The Invoke-Command can be also used to execute commands and scripts on the remote systems. The -ComputerName option is used to specify the remote computer name or IP address.

PS> Invoke-Command -ComputerName 192.168.1.10 -ScriptBlock {Get-Process -Name 'chrome'}

Run Command In Multiple Remote Systems

The -ComputerName can be used to run commands on multiple remote systems. The remote systems domain names or IP addresses can be specified by separating them with commas.

PS> Invoke-Command -ComputerName 192.168.1.10,MyWorkstation1 -ScriptBlock {Get-Process -Name 'chrome'}

Run Local Script

Another useful usage for the Invoke-Command is the ability to run local PowerShell scripts on remote systems. The -FilePath option is used to specify the local PowerShell script.

PS> Invoke-Command -ComputerName 192.168.1.10,MyWorkstation1 -FilePath "C:\Backup.ps1"
See also  How To Install Nmap On Windows?

Leave a Comment