Execute in PowerShell

Security Briefs

Syndication

As part of a disaster recovery script, early on I wanted to ensure that all of the vdirs on a server were using ASP.NET 2.0. That meant that I wanted to run

aspnet_regiis.exe -r

but I didn't want to make any assumptions about what drive or directory Windows was installed in. What I wanted was something like this:

%WINDIR%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -r

In PowerShell, an easy way to get the value of an environment variable is to use the $env namespace like so:

$env:windir

but when I put this all together and tried to run it, PowerShell didn't parse it the way I expected:

$env:windir\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -r
Unexpected token '\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe' in expression or statement.

Putting quotes around it doesn't help. Now PowerShell assumes you want a string.

"$env:windir\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe" -r
You must provide a value expression on the right-hand side of the '-' operator.

What you need to do is make it clear to PowerShell that you want to execute the next string as a command. The way to do this is to use the call operator & (ampersand). Here's what I ended up with:

& $env:windir\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -r

That's more like it. This is the sort of little roadblock that tends to frustrate people trying to use PowerShell for the first time. I hope this helps!


Posted Dec 02 2007, 11:27 AM by keith-brown

Comments

Norman Diamond wrote re: Execute in PowerShell
on 12-02-2007 3:57 PM
Oh, this one is funny. Whoever designed and/or implemented that part of PowerShell's parser could teach something to the Visual C++ department.

In the ISO standards for C and C++, when preprocessing tokens don't convert correctly to ordinary tokens, conforming implementations are required to issue diagnostics. Conforming implementations are allowed to do whatever else they wish, so for example Visual C++ can paste two preprocessing tokens into one ordinary token in order to create a translation unit good enough for further translation, but they're not allowed to forget about diagnostics while doing so.

So here, PowerShell knows how to avoid pasting two tokens together. Or more importantly, they know how to issue an error message. Visual Studio needs to hire them.
EDF wrote re: Execute in PowerShell
on 12-20-2007 6:12 AM
Thank you Keith! You are absolutly right about things like this being frustrating. I realize it's hard for the creators and power users of Powershell (mostly developers) to understand what newbs like me are going through... We want to learn Powershell, but stuff like this can sure slow us up and discourage us. Thanks for the post.
Troy Lea wrote re: Execute in PowerShell
on 01-17-2008 8:49 PM
Just what I was looking for, thanks for the how-to.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?