Anyone know of any good MSBuild tasks that will execute a PowerShell script and pass it different parameters?
I was able to find B# .NET Blog: Invoking PowerShell scripts from MSBuild, but I'm hoping for something that is a little more polished.
If I can't find anything I will of course just go ahead and polish my own using that blog post as a starter.
With a bit of fun, I managed to come up with a fairly clean way of making this work:
Notes:
if your powershell script needs to use < > or & characters, just place the contents in a CDATA wrapper:
if you want return items to the msbuild script you can get them:
See! then you can use those items with another msbuild Task :D
Duplicate Question and Answer I Posted, here for posterity for when it has been vote to closed. The key difference is that this question was constrained to being OOTB and my self-answer stays within that constraint.
Question
Powershell doesn't seem to have an easy way to trigger it with an arbitrary command and then bubble up parse and execution errors in a way that correctly interoperates with callers that are not PowerShell - e.g.,
cmd.exe
, TeamCity etc.My question is simple. What's the best way for me with OOTB MSBuild v4 and PowerShell v3 (open to suggestions-wouldnt rule out a suitably production ready MSBuild Task, but it would need to be a bit stronger than suggesting "it's easy - taking the PowerShell Task Factory sample and tweak it and/or becoming it's maintainer/parent") to run a command (either a small script segment, or (most commonly) an invocation of a
.ps1
script.I'm thinking it should be something normal like:
That sadly doesn't work:-
ThingToDo
fails to parse, it fails silentlyThingToDo
is a script invocation that doesn't exist, it failsERRORLEVEL
based.cmd
result, it gets hairy"
quotes in theThingToDo
, it won't workSo, what is the bullet proof way of running PowerShell from MSBuild supposed to be? Is there something I can PsGet to make everything OK?
Answer
Weeeeelll, you could use something long winded like this until you find a better way:-
And then 'all' you need to do is:
The single redeeming feature of this (other than trapping all error types I could think of), is that it works OOTB with any PowerShell version and any MSBuild version.
I'll get my coat.
You might also want to look at Psake - a PowerShell based build environment.
One could use http://powershellmsbuild.codeplex.com/ for 3.5. It'd be nice if there was a NuGet package for it that one could leverage via NuGet package restore.
4.0 has a Windows Powershell Task Factory which
you can get in the code galleryhas been rolled into MSBuild Extension Pack (one of the top task libraries - 400+ Tasks & recommended in Inside MSBuild) hasPowerShellTaskFactory
(download the help file from the download section of this example release to have a peek).