PowerShell Basics: Invoke-Command -ScriptBlock with Examples

PowerShell Basics_ Invoke-Command -ScriptBlock

Windows PowerShell Invoke-Command

PowerShell’s Invoke-Command is ideal for running a quick command on a remote computer.  This is similar to using Invoke-Expression for string commands.Windows PowerShell Invoke-Command

Remoting in Microsoft PowerShell v 2.0 with Invoke-Command

Three Key Parameters for Invoke-Command

The secret of success with Invoke-Command is to pay particular attention to these three parameters:

  1. -ComputerName to make that remote connection, (-Computer is unambiguous and works just as well).
  2. -ScriptBlock place the payload of your command is inside the {Braces}.
  3. -FilePath store the PowerShell instructions in a file, then run against multiple machines.

When investigating the scope and parameters for any new command, I call for Get-Help followed by the name of the cmdlet, this is how I learned about the above parameters.

Get-Help Invoke-Command -full

Simple Example of Invoke-Command with -ScriptBlock

Before you run the script block on a remote computer, I always like to get it working on the local machine:

Local Machine

# PowerShell Invoke-Command Local Machine Example
Invoke-Command -ScriptBlock {"C:\Program files" |  Get-ChildItem}

Remote Computer
Now we are ready to progress to a remote computer.  Please substitute a computer on your network for Victim1.

# PowerShell Invoke-Command Remote Computer
Invoke-Command -Computer Victim1 -ScriptBlock {"C:\Program files" |  GCI}

{“C:\Program files” | GCI or Get-ChildItem} is just for illustration, a more common usage would be PowerShell cmdlets such as Get-Service or Get-Eventlog.

Invoke-Command -Computer Srv1, Srv2 -ScriptBlock {Get-Service}
# PowerShell Invoke-Command System Log Example
Invoke-Command -ScriptBlock {Get-EventLog system -Newest 50}

Get-Process Example of Invoke-Command

# Invoke-Command -ScriptBlock example in PowerShell 2.0
Invoke-Command -ComputerName BigServer, LittleServer -ScriptBlock {
Get-Process | Where-Object {$_.name -Like 'W*'}

Note 1: You could also store a list of computer names in a file and call the file with:
Invoke-Command -ComputerName (Get-Content “E:\PowerShell\com\ServerList.txt”)

Note 2: If the ScriptBlock does not do what you want, and you wish to append string commands, try Invoke-Expression instead.

Note 3: If you format the ScriptBlock with { at the end of the line, you don’t need the backtick `, PowerShell can deduce that the command continues on the next line.

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

Invoke-Command -FilePath

Using the -FilePath parameter is an alternative technique to employing -ScriptBlock.  The idea is that you store all the PowerShell instructions in a .ps1 file.  Then instead of looking for a ScriptBlock, you point Invoke-Command at the -FilePath.  The benefit is that you don’t have to keep a copy of the file on all the remote servers for which you want to run the script.

# PowerShell Invoke-Command -FilePath example
Invoke-Command -ComputerName BigServer `
-FilePath "C:\Services.ps1"

Note 4: Naturally for this to work you need suitable PowerShell instructions in the file that I have called Services.ps1.

Note 5: I find that you always need the name of a server, even when testing on the local machine.

Note 6: Talking of files, you could also store a list the servers, which you want to run the instructions, in a file and then call that file.

# Invoke-Command -FilePath example in PowerShell 2.0
-ComputerName (Get-Content "C:\ServerList.txt")  `
-FilePath "C:\Services.ps1"

Other Useful Techniques

Jobs and -asJob
For scripts that take a long time to complete you could consider appending the –asJob parameter.  This has the pleasant effect of running the commands in the background.  However, to actually see the results, you need to master the cmdlet receive-Job.

As an alternative to -asJob you could be to employ the -session parameter then run Start-job.  However, from a learning perspective, I normally like to concentrate on one technique at a time and combining Invoke-Command with start-Job is a tricky task for a beginner.

Guy Recommends: SolarWinds Engineer’s Toolset (FREE TRIAL)Engineer's Toolset v10

This Engineer’s Toolset provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset on a 14-day free trial now!

SolarWinds Engineer's Toolset Download 14-day FREE Trial


Invoke-Expression is a sister PowerShell cmdlet useful for mimicking the CMD dos box.  A typical scenario is where you can typing command-line instructions, but now you want to execute the same string using PowerShell.

With Invoke-Expression you can either save the string values in a text file, then execute them, else append the string directly to Invoke-Expression.  See more about Invoke-Expression here.

Introduction to the Rest of the PowerShell Invoke Family

To investigate PowerShell’s ‘invoke’ verb, let us start with the trusty Get-Command, thus:

Get-Command -Verb invoke

Summary of PowerShell Invoke-Command

Here is handy remoting technique for running PowerShell commands on a batch of network machines.  Learn more about the syntax and parameters with help Invoke-Command, the key to this cmdlet is what you put between the -ScriptBlock {Braces}.

See more Microsoft PowerShell tasks:

PowerShell Home   • Shell Application   • New-Object   • PowerShell Add Printer   • PowerShell -com

PowerShell Logon Script  • Map Network Drive  • PowerShell Create Shortcut  • Free CSV Import Tool

Invoke-Expression   • Invoke-Command   • Invoke-Item   • PowerShell Expression v Command Mode

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.