问题
Possible Duplicate:
Any good PowerShell MSBuild tasks?
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:
<Exec
IgnoreStandardErrorWarningFormat="true"
Command="PowerShell "$(ThingToDo)"" />
That sadly doesn't work:-
- if
ThingToDo
fails to parse, it fails silently - if
ThingToDo
is a script invocation that doesn't exist, it fails - if you want to propagate an
ERRORLEVEL
based.cmd
result, it gets hairy - if you want to embed
"
quotes in theThingToDo
, it won't work
So, what is the bullet proof way of running PowerShell from MSBuild supposed to be? Is there something I can PsGet to make everything OK?
回答1:
You can use the following example:
<InvokeScript Condition="..."
PowerShellProperties="..."
ScriptFile="[PATH TO PS1 FILE]"
Function="[FUNCTION TO CALL IN PS1]"
Parameters="..."
RequiredOutputParams="...">
<!-- You can catch the output in an Item -->
<Output TaskParameter="OutputResults"
ItemName="Output" />
</InvokeScript>
This can be used in MSBuild.
回答2:
Weeeeelll, you could use something long winded like this until you find a better way:-
<PropertyGroup>
<__PsInvokeCommand>powershell "Invoke-Command</__PsInvokeCommand>
<__BlockBegin>-ScriptBlock { $errorActionPreference='Stop';</__BlockBegin>
<__BlockEnd>; exit $LASTEXITCODE }</__BlockEnd>
<_PsCmdStart>$(__PsInvokeCommand) $(__BlockBegin)</PsCmdStart>
<_PsCmdEnd>$(__BlockEnd)"</PsCmdEnd>
</PropertyGroup>
And then 'all' you need to do is:
<Exec
IgnoreStandardErrorWarningFormat="true"
Command="$(_PsCmdStart)$(ThingToDo)$(_PsCmdEnd)" />
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.
来源:https://stackoverflow.com/questions/11648530/in-msbuild-how-do-i-run-something-powershell-and-have-all-errors-reported