One of the interesting things about having a blog is seeing what people are searching for when they navigate to an entry. On at least a dozen occasions I've seen searches where people were obviously trying to invoke NAnt from PowerShell. Because I've talked about both NAnt and PowerShell without speaking to this subject, they have been disappointed in what they've found in my blogs. Indeed, when I've performed my own searches, I've noticed there isn't a lot of useful info on doing this subject. Especially at detecting an error in the NAnt script.
This isn't the most comprehensive script but it does the basics:
function
Invoke-NAnt ($NantFile,$target,[hashtable]$Properties)
{
$sb = New-Object "System.Text.StringBuilder"
if ($properties -ne $null)
{
foreach ($key in $Properties.Keys)
{
[void] $sb.Append( '"' + "-D:$key=$($Properties.$key)" + '" ' )
}
}
nant "-f:$NantFile" $target $sb.ToString()
if (-not $?)
{
Throw "Nant Failed"
}
}
Example Usage:
Invoke-NAnt
Test.build "TestTarget" @{Test1="Value1";Test2="Value2"}
Test.Build contains:
<
project>
<target name="TestTarget">
<echo message="Test1=${Test1}"/>
<echo message="Test2=${Test2}"/>
<fail message="This is a failure"/>
</target>
</project>
Output looks like:
NAnt 0.85 (Build 0.85.2478.0; release; 10/14/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net
Buildfile: file:///C:/Projects/PSNant/Test.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: TestTarget
TestTarget:
[echo] Test1=Value1
[echo] Test2=Value2
BUILD FAILED
C:\Projects\PSNant\Test.build(6,6):
This is a failure
Total time: 0 seconds.
Nant Failed
At C:\Projects\PSNant\InvokeNant.PS1:19 char:10
+ Throw <<<< "Nant Failed"
This particular script is designed to fail with the 'fail task'. This is because I was having trouble detecting errors.
if (-not $?)
{
Throw "Nant Failed"
}
The $? variable is set to $true if the previous instruction succeeded. As of yet, I'm not getting the actual failure message. If someone can help with that, I'd appreciate it.
Other usage comments:
The $properties parameter takes a hash table that gets marshaled into -D:<propname>=<propvalue> line arguments. I find the syntax of @{Test1="Value1";Test2="Value2"} to be more natural for PowerShell.
This function will return an array of text lines which are the output from NAnt. If you don't want them to pipe out you'll need to assign it to a variable or [void] it.
$NantOutput
= Invoke-NAnt Test.build "TestTarget" @{Test1="Value1";Test2="Value2"}
Finally: Obviously this needs to be dressed out a little more for supporting some useful parameters to NAnt like Logger and Default Framework.