skip to Main Content

Automating Maven with PowerShell

I found out the hard way that mvn (Maven) on Windows always return a success code of true, which means you cannot use the return code ($?) to check whether the mvn command succeeded or failed. Why they decided to break this seemingly basic program contract is a mystery. A work-around is to scan the mvn output and look for specific strings such as “BUILD SUCCESSFUL”.

Here’s how:

function InvokeAndCheckStdOut($cmd, $successString, $failString) {
    Write-Host "====> InvokeAndCheckStdOut"
    $fullCmd = "$cmd|Tee-Object -variable result" 

    Invoke-Expression $fullCmd
    $found = $false
    $success = $false
    foreach ($line in $result) {
      if ($line -match $failString) {
       $found = $true
       $success = $false
       break
      }
      else {
       if ($line -match $successString) {
        $found = $true
        $success = $true
        #"[InvokeAndCheckStdOut] FOUND MATCH: $line"
        break
       }
       else {
        #"[InvokeAndCheckStdOut] $line"
       }
      }
    }

    if (! $success) {
      PlayWav "${env:windir}\Media\ding.wav"
      throw "Mvn command failed."
    }

    Write-Host "InvokeAndCheckStdOut <===="
}

function InvokeMvn($cmd) {
    InvokeAndCheckStdOut $cmd "BUILD SUCCESSFUL" "BUILD FAILED"
}


InvokeMvn "mvn clean install"

See Also

I occasionally blog about programming (.NET, Node.js, Java, PowerShell, React, Angular, JavaScript, etc), gadgets, etc. Follow me on Twitter for tips on those same topics. You can also find me on GitHub.

See About for more info.

This Post Has One Comment

Leave a Reply

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

Back To Top