Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
The definitive way to use PowerShell from an msbuild script
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="">
<!-- #1 Place this line at the top of any msbuild script (ie, csproj, etc) -->
<PropertyGroup><PowerShell># 2>nul || type %~df0|find /v "setlocal"|find /v "errorlevel"|powershell.exe -noninteractive -&amp; exit %errorlevel% || #</PowerShell></PropertyGroup>
<!-- #2 in any target you want to run a script -->
<Target Name="default" >
<PropertyGroup> <!-- #3 prefix your powershell script with the $(PowerShell) variable, then code as normal! -->
# powershell script can do whatever you need.
dir ".\*.cs" -recurse |% {
write-host Examining file named: $_.FullName
# do other stuff here...
$answer = 2+5
write-host Answer is $answer !
<!-- #4 and execute the script like this -->
<Exec Command="$(myscript)" EchoOff="true" />
- You can still use the standard Exec Task features! (see:
- if your powershell script needs to use < > or & characters, just place the contents in a CDATA wrapper:
<script2><![CDATA[ $(PowerShell)
# your powershell code goes here!
write-host "<<Hi mom!>>"
- if you want return items to the msbuild script you can get them:
# your powershell code goes here!
(dir "*.cs" -recurse).FullName
<Exec Command="$(script3)" EchoOff="true" ConsoleToMSBuild="true">
<Output TaskParameter="ConsoleOutput" PropertyName="items" />
<Touch Files="$(items)" /> <- see! then you can use those items with another msbuild Task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment