Using Powershell scripts from MSBuild, Scheduled Tasks, etc.

There are a few different ways to use Powershell from the legacy cmd shell. The most common way is to call it like the following.

> powershell write-host "hello world"

As you can see, the powershell.exe is called with Powershell commands as the parameters. I started noticing some odd behavior though. I have the following script, TestScript.ps1. It has code as follows:

param
(
  $str
)

write-host $str

Very simple right. Well guess what happens when I call it from powershell.exe like above?

> powershell .\TestScript.ps1 "hello world"
hello

A little odd. I have a very cordial script but it is a little tongue tied. I didn’t spend a lot of time trying to figure out why this was occurring, I instead used powershell -? to help me find an alternate method, and probably better way to call Powershell scripts from the legacy cmd shell.

> powershell -Command "& { .\TestScript.ps1 'hello world' }"
hello world

This worked like a charm. Note the quotes, as script blocks aren’t interpreted from the cmd shell properly, and will cause odd behavior. And from MSBuild, a little bit of XML escapage and you can easily use Powershell.

  <target name="AfterBuild">
    <exec command="powershell.exe -command "& {.\Register-EmailApiSnapIn.ps1 '$(TargetPath)'}""></exec>
  </target>