PS: Executing string as a command

Link. January 22, 2008. Comments [0]. Posted in: PowerShell

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!



Comments are closed.

About

Tomas Restrepo is a software developer located in Colombia, South America. His interests include .NET, Connected Systems, PowerShell and lately dynamic programming languages. More...

tomasrestrepo @ twitter My Flickr photostream My saved links on delicious My Technorati Profile

email: tomas@winterdom.com
msn: tomasr@passport.com

View my profile on LinkedIn

MVP logo

Syndicate

Ads


Links

Categories

Statistics

Total Posts: 1020
This Year: 90
This Month: 9
This Week: 0
Comments: 791

Blogroll

Post Archive

Other

Copyright © 2002-2008, Tomas Restrepo.

Powered by: newtelligence dasBlog 2.1.8102.813

Sign In