Ezine 204 – Introduction to PowerShell’s Invoke-Expression

Introduction to PowerShell’s Invoke-Expression

Invoke-Expression is a brilliant PowerShell cmdlet, which mimics us typing instructions into a ‘DOS box’.  A typical scenario is where you are expert with cmd.exe, and now you want to execute the same commands, but using PowerShell.  This is a job for the Invoke family of cmdlets, specifically invoke-Expression.

Topics for Invoke-Expression

 ♣

This Week’s Secret – How to Execute Dos Commands in PowerShell

One of my most convincing arguments for persuading people to learn PowerShell is that anything you can type in CMD you can do with PowerShell.  Because PowerShell does so much more than the DOS box, being able to type old DOS commands is a clincher for making the switch to PowerShell.

While PowerShell has aliases for dir (list-ChildItem) and cd (set-Location), there is no direct equivalent for cmd.exe.  However, the invoke-Expression cmdlet allows you to launch an executable and crucially, append command-line instructions.  The result is that invoke-Expression executes the string as if you had typed it in the ‘DOS box’.

This Week’s Choice of Mission for Invoke-Expression

I have two ‘Vehicles’ for you to test drive invoke-Expression, firstly, test-Connection and secondly WOL (Wake-on-Lan).  My first mission involves storing string values in a text file, just as you typed them in cmd.exe.  Then we use PowerShell to call that file, and then run those instructions. 

In my second mission I will explain how PowerShell can perform the real-life task of waking up a computer on the network.  Our biggest problem with this example is realizing that you have to download the underlying WOL program before the PowerShell instructions have any chance of working.

Invoke-Expression Using a String in a PS1 File

The scenario is that you wish to measure the server’s response time with PowerShell’s test-Connection, this is the equivalent of ping in cmd.exe.

Concept 1:  My instructions will ping a website using PowerShell’s test-Connection cmdlet
Concept 2:  These instructions are saved in a text file with a .ps1 file extension.
Concept 3:  Invoke-Expression then ‘calls’ this text file with its string instructions.

Key point:  Save the instructions below into a file, I called mine c:\PingWeb.ps1

# PowerShell test-Connection .ps1 file
Clear-host
$WebPing = test-Connection www.computerperformance.co.uk -count 10
Write-host Average ($WebPing | measure-Object ResponseTime -average).Average

Now let us use Invoke-Expression to execute these instructions.

# PowerShell cmd invoke-Expression from .ps1 file
$Path = "C:\PingWeb.ps1"
Invoke-Expression "$Path"

As with many of my scripts, this example contains extra code which aids learning, and directs you to making changes to suit your circumstances.  However, you could simplify the expression to:
Invoke-Expression "C:\PingWeb.ps1"

See more on PowerShell Measure-Command »

PowerShell Script Using Invoke-Expression to Wake-on-Lan

Vital preliminary step: download wolcmd.  I strongly recommend that you ‘play’ with wolcmd in the DOS box before you use it in a PowerShell script.

# PowerShell Wake-on-Lan command-line instruction
$ExePath = "E:\Downloads\Applications\wolgui\wolcmd.exe"
$CLine = "00248C1F9023 192.168.1.66 255.255.255.0 7"
Invoke-Expression "$ExePath $CLine" | out-Null

Note 1:  You probably want to change the values of $ExePath and of $CLine

Note 2:  Observe the double quotes surrounding both variables.  "$ExePath $CLine"

Note 3:  Experiment with and without | out-Null.  This command merely suppresses any output.

Troubleshooting

If you are following my actual PowerShell Wake-on-Lan example, then download wolcmd here.

If you have changed the values of $ExePath and $CLine, but your script still does not work try a manual walk-through in the cmd dos box.  See if you can get ipconfig to work with the command-line switch /all.

You can research invoke-Expression with these two trusty PowerShell commands:
get-Help invoke-Expression
Also append get-Member
$ExePath = "E:\Downloads\Applications\wolgui\wolcmd.exe"
$CLine = "00248C1F9023 192.168.1.66 255.255.255.0 7"
Invoke-Expression "$ExePath $CLine" | get-Member

Problem with Invoke-Expression �computername …. �command "xyz"

If it’s any consolation, commands like this did not work for me:
invoke-Expression -computername localhost, BigServer -command "get-process powershell*"

Solution: What I did was switch to Invoke-Command thus:

invoke-Command -computername bigserver -scriptblock {get-process powershell}

More Members of the Invoke Family

# PowerShell script to list Invoke family of cmdlets
get-command -verb invoke

Invoke-Command
Invoke-Expression
Invoke-History
Invoke-Item
Invoke-WmiMethod
Invoke-WSManAction

The two most promising cmdlets are Invoke-Command and Invoke-Item.

WMI Monitor DetailsSolarwinds WMI Software

Here is another chance to download this free WMI Monitor.  It enables to you to measure the real-time performance of any modern Microsoft operating system.  Your FREE WMI Monitor will deliver a desktop dashboard that monitors any Windows server and offers built-in templates plus community customizable templates.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, Exchange mailboxes or SharePoint.

WMI Monitor Highlights:

  • Monitor real-time performance metrics on any Windows computer or application.
  • Leverage a large selection of pre-built and community generated application templates.
  • Modify or design your own application templates with the built-in WMI browser.
  • Use the WMI Monitor to familiarise yourself with classes that can be then used for PowerShell scripting.
  • Download Your Free WMI Monitor
  • See more on Solarwinds WMI Monitor

Summary of PowerShell’s Invoke-Expression

Invoke-Expression is a wonderful way of executing a string of DOS instructions, but in PowerShell.  I chose Wake-on-lan (WOL) as a vehicle to give you a grounding in this cmdlet’s syntax.  The ideas is that Invoke-Expression executes the string as if you typed it at the cmd.exe command-line.  I hope that you will be able to modify my examples to suit your task.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

If you like this page then please share it with your friends

 


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.