Technical Notes

My online notepad

  • Social

  • Support

    Donate towards my web hosting bill!

How to run PowerShell script from Ant

Posted by Anton Khitrenovich on January 22, 2014

logo-powershellYesterday I was looking for a good recipe of how to run PowerShell script from Ant build file. Unfortunately, it seems that most of the people are looking for an advise on exactly the opposite – how to run Ant from PowerShell. So, I did some trial and error on my own, and here are the results.

The following Ant snippet executes PowerShell script MyScript.ps1 in the current directory and verifies that it did not fail. The result of the script execution is stored in myscript.out property.

<exec dir="." executable="powershell" timeout="5000" failonerror="true"
        outputproperty="myscript.out" errorproperty="myscript.error">
    <arg line="-ExecutionPolicy bypass" />
    <arg line="-File MyScript.ps1" />
        <equals arg1="${myscript.error}" arg2="" trim="true" />
        <fail message="${myscript.error}" />

The main caveat here is the error checking. Despite the failonerror flag, the exec task will not fail in case of many errors – like compilation issues, missing parameters and other runtime errors. This happens because the task verifies invocation of PowerShell itself and not the script execution, which is handled inside PowerShell. The solution is to capture error stream into dedicated property and verify that nothing was actually written there.

Pay attention that if tag (lines 6-13) requires ant-contrib tasks library available. The same condition may be rewritten in less readable form with pure Ant:

<fail message="${myscript.error}">
            <equals arg1="${myscript.error}" arg2="" trim="true" />

Another note is the bypass of default execution policy on line 3. This is not specific to Ant, but rather to PowerShell in general. There are a lot of discussions on the net about the topic, so I won’t cover it here.

One Response to “How to run PowerShell script from Ant”

  1. Ryan said

    This was very helpful and worked well! Thank-you for posting.

Leave a Comment

Your email address will not be published. Required fields are marked *