Invoke-Maven

I’ve slowly been building up a personal module at work that I use in my Jenkins workflows.  One function that I wrote a while ago but didn’t get around to using until yesterday was Invoke-Maven.

<#
    .SYNOPSIS
        Executes Maven.
    
    .DESCRIPTION
        Assumes Maven is correctly setup in the PATH, as well as JAVA_HOME and M2_HOME variables.
    
    .PARAMETER goal
        Specifies the goals to execute, such as "clean", "install", or "deploy".
    
    .PARAMETER pomPath
        Path to the POM file. Path is validated with Test-Path.
    
    .PARAMETER deployPath
        Path for Maven to deploy to. Path is validated with Test-Path.
    
    .PARAMETER logPath
        Path to write maven log file to. If this parameter is used there is no console output.
    
    .PARAMETER X
        Turn Maven debugging on.

    .EXAMPLE
        Invoke-Maven -goal deploy -pomPath "C:\Development\Java\Projects\pom.xml" -deployPath "C:\Development\Builds"
#>
function Invoke-Maven {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('clean', 'install', 'deploy', IgnoreCase = $true)]
        [string]$goal,
        [Parameter(Mandatory = $true)]
        [ValidateScript({ Test-Path $_ })]
        [string]$pomPath,
        [ValidateScript({ Test-Path $_ })]
        [Alias('url', 'deployUrl')]
        [string]$deployPath,
        [string]$logPath,
        [switch]$X
    )
    
    If ($PSBoundParameters.ContainsKey('logPath') -eq $true) {
        If ($goal -match "deploy") {
            $cmd = "mvn -B -f $pomPath $goal ""-Ddeployment.DeployURL=$deployPath"" - l $logPath"
        } else {
            $cmd = "mvn -B -f $pomPath $goal -l $logPath"
        }
        If ($X) {
            $cmd = "$cmd -X"
        }
    } else {
        If ($goal -match "deploy") {
            $cmd = "mvn -B -f $pomPath $goal ""-Ddeployment.DeployURL=$deployPath"""
        } else {
            $cmd = "mvn -B -f $pomPath $goal"
        }
        If ($X) {
            $cmd = "$cmd -X"
        }
    }
    
    Write-Verbose "Invoke-Expression $cmd"
    Invoke-Expression "$cmd"
}

The only real problem with it is that if you use the logPath parameter, Maven doesn’t display anything to the host console.  What I ended up doing in my Jenkins job that uses this function is calling it with Start-Transcript to get both a log file and the console output.

Advertisements
This entry was posted in DevOps and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s