Recently I was writing a small script for Powershell and I needed to call an external program from my script. However, I wanted to be able to put keep the directory the executable was located in in a variable; you know, like one usually does in regular batch files.

After searching around using google, I found that you can execute the contents of a string as a command by prefixing it with '&', like this:

&'c:\windows\system32\calc.exe'

This is fine if you've got a simple literal string. However, if you want to use the value of one or more variables in it, you of course need to switch to using double quotes instead, like this:

$JDKHOME = "C:\Program Files\Java\jdk1.5.0_06\bin"
&"$JDKHOME\native2ascii.exe" "$name.temp" $name -encoding utf-8

Turns out you can actually execute the contents of a variable as a command, which I wasn't expecting to work at first:

$MYCMD = 'write-host'
&$MYCMD 'hello world'

Pretty nifty!

Technorati tags:


Tomas Restrepo

Software developer located in Colombia. Sr. PFE at Microsoft.