Downloads:

755

Downloads of v 5.5.5:

27

Last Update:

17 Oct 2019

Package Maintainer(s):

Software Author(s):

  • Roman Kuzmin

Tags:

admin powershell module build test automation psake invoke-build invoke.build

InvokeBuild (PowerShell Module)

5.5.5 | Updated: 17 Oct 2019

Downloads:

755

Downloads of v 5.5.5:

27

Maintainer(s):

Software Author(s):

  • Roman Kuzmin

InvokeBuild (PowerShell Module) 5.5.5

All Checks are Passing

2 Passing Test


Validation Testing Passed


Verification Testing Passed

Details

To install InvokeBuild (PowerShell Module), run the following command from the command line or from PowerShell:

>

To upgrade InvokeBuild (PowerShell Module), run the following command from the command line or from PowerShell:

>

To uninstall InvokeBuild (PowerShell Module), run the following command from the command line or from PowerShell:

>

NOTE: This applies to both open source and commercial editions of Chocolatey.

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://chocolatey.org/api/v2. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Enter your internal repository url

(this should look similar to https://chocolatey.org/api/v2)

4. Choose your deployment method:


choco upgrade invokebuild -y --source="'STEP 3 URL'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade invokebuild -y --source="'STEP 3 URL'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Ensure invokebuild installed
  win_chocolatey:
    name: invokebuild
    state: present
    version: 5.5.5
    source: STEP 3 URL

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'invokebuild' do
  action    :install
  version  '5.5.5'
  source   'STEP 3 URL'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


Chocolatey::Ensure-Package
(
    Name: invokebuild,
    Version: 5.5.5,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller invokebuild
{
   Name     = 'invokebuild'
   Ensure   = 'Present'
   Version  = '5.5.5'
   Source   = 'STEP 3 URL'
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'invokebuild':
  provider => 'chocolatey',
  ensure   => '5.5.5',
  source   => 'STEP 3 URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


salt '*' chocolatey.install invokebuild version="5.5.5" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package was approved as a trusted package on 17 Oct 2019.

Description

Invoke-Build is a build and test automation tool which invokes tasks defined in PowerShell v2.0+ scripts. It is similar to psake but arguably easier to use and more powerful. It is complete, bug free, well covered by tests.

In addition to basic task processing the engine supports

  • Incremental tasks with effectively processed inputs and outputs.
  • Persistent builds which can be resumed after interruptions.
  • Parallel builds in separate workspaces with common stats.
  • Batch invocation of tests composed as tasks.
  • Ability to define new classes of tasks.

Invoke-Build v3.0.1+ is cross-platform with PowerShell v6.

Invoke-Build can be effectively used in VSCode and ISE.

Several PowerShell Team projects use Invoke-Build.

NOTE: This is an automatically updated package. If you find it is out of date by more than a week, please contact the maintainer(s) and let them know the package is no longer updating correctly.


tools\.skipAutoUninstaller
 
tools\chocolateyBeforeModify.ps1
$ErrorActionPreference = 'Stop'

$moduleName = $env:ChocolateyPackageName      # this could be different from package name
Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue
tools\chocolateyInstall.ps1
$ErrorActionPreference = 'Stop'

$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$moduleName = 'InvokeBuild'  # this may be different from the package name and different case

# module may already be installed outside of Chocolatey
Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue

$sourcePath = Join-Path -Path $toolsDir -ChildPath "$modulename\*"
$destPath   = Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules\$moduleName"

if ($PSVersionTable.PSVersion.Major -ge 5)
{
    $manifestFile = Join-Path -Path $toolsDir -ChildPath "$moduleName\$moduleName.psd1"
    $manifest     = Test-ModuleManifest -Path $manifestFile -WarningAction Ignore -ErrorAction Stop
    $destPath     = Join-Path -Path $destPath -ChildPath $manifest.Version.ToString()
}

Write-Verbose "Creating destination directory '$destPath' for module."
New-Item -Path $destPath -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null

Write-Verbose "Moving '$moduleName' files from '$sourcePath' to '$destPath'."
Move-Item -Path $sourcePath -Destination $destPath -Force

if ($PSVersionTable.PSVersion.Major -lt 4)
{
    $modulePaths = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine') -split ';'
    if ($modulePaths -notcontains $destPath)
    {
        Write-Verbose "Adding '$destPath' to PSModulePath."
        $newModulePath = @($destPath, $modulePaths) -join ';'

        [Environment]::SetEnvironmentVariable('PSModulePath', $newModulePath, 'Machine')
        $env:PSModulePath = $newModulePath
    }
}
tools\chocolateyUninstall.ps1
$ErrorActionPreference = 'Stop'

$moduleName = $env:ChocolateyPackageName
$sourcePath = Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules\$moduleName"

Write-Verbose "Removing all version of '$moduleName' from '$sourcePath'."
Remove-Item -Path $sourcePath -Recurse -Force -ErrorAction SilentlyContinue

if ($PSVersionTable.PSVersion.Major -lt 4) {
    $modulePaths = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine') -split ';'

    Write-Verbose "Removing '$sourcePath' from PSModulePath."
    $newModulePath = $modulePaths | Where-Object { $_ -ne $sourcePath }

    [Environment]::SetEnvironmentVariable('PSModulePath', $newModulePath, 'Machine')
    $env:PSModulePath = $newModulePath
}
tools\InvokeBuild\about_InvokeBuild.help.txt
TOPIC
    about_InvokeBuild

SHORT DESCRIPTION
    Build and test automation in PowerShell

LONG DESCRIPTION
    The module provides the following commands:

        Invoke-Build
            The alias of Invoke-Build.ps1
            It invokes build scripts, this is the build engine.

        Build-Checkpoint
            The alias of Build-Checkpoint.ps1
            It invokes persistent builds using the engine.

        Build-Parallel
            The alias of Build-Parallel.ps1
            It invokes parallel builds using the engine.

    Import the installed module:

        Import-Module InvokeBuild

    Or import from the specified location:

        Import-Module <path>\InvokeBuild.psd1

    Get help for the engine:

        help <path>\Invoke-Build.ps1 -full

    Get help for build commands:

        . <path>\Invoke-Build.ps1
        help task -full
        help exec -full
        ...

    The package contains the build engine with a few helpers, all you need
    for running build scripts. There are various related tools, see README.
tools\InvokeBuild\Build-Checkpoint.ps1
<#
Copyright (c) Roman Kuzmin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
#>

#.ExternalHelp InvokeBuild-Help.xml
param(
	[Parameter(Position=0, Mandatory=1)][string]$Checkpoint,
	[Parameter(Position=1)][hashtable]$Build,
	[switch]$Preserve,
	[switch]$Resume
)

try {
$ErrorActionPreference = 'Stop'

$Checkpoint = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Checkpoint)

$Build = if ($Build) {@{} + $Build} else {@{}}
if ($Build['WhatIf']) {throw 'WhatIf is not supported.'}

${*checkpoint} = @{
	Checkpoint = $Checkpoint
	Preserve = $Preserve
	Result = $Build['Result']
	Data = $null
}
$Build.Remove('Result')

if ($Resume) {
	if (![System.IO.File]::Exists($Checkpoint)) {throw "Missing checkpoint '$Checkpoint'."}
	${*checkpoint}.Data = try {Import-Clixml $Checkpoint} catch {throw 'Invalid checkpoint file?'}

	foreach($_ in @($Build.Keys)) {
		if ($_ -ne 'Safe' -and $_ -ne 'Summary') {
			$Build.Remove($_)
		}
	}
	$Build.Task = ${*checkpoint}.Data.Task
	$Build.File = ${*checkpoint}.Data.File
	$Build = $Build + ${*checkpoint}.Data.Prm1
}

${*checkpoint}.XBuild = {
	if (${*checkpoint}.Data) {
		foreach($_ in ${*checkpoint}.Data.Done) {
			${*}.All[$_].Elapsed = [TimeSpan]::Zero
		}
		foreach($_ in ${*checkpoint}.Data.Prm2.GetEnumerator()) {
			Set-Variable $_.Key $_.Value -Scope Script
		}
		if ($_ = ${*}.Data['Checkpoint.Import']) {
			. *Run $_ ${*checkpoint}.Data.User
		}
	}
}

${*checkpoint}.XCheck = {
	Export-Clixml ${*checkpoint}.Checkpoint -InputObject @{
		User = *Run ${*}.Data['Checkpoint.Export']
		Task = $BuildTask
		File = $BuildFile
		Prm1 = ${*}.SP
		Prm2 = $(
			$r = @{}
			foreach($_ in ${*}.DP.Keys) {
				$r[$_] = Get-Variable -Name $_ -Scope Script -ValueOnly
			}
			$r
		)
		Done = @(
			foreach($t in ${*}.All.Values) {
				if ($t.Elapsed -and !$t.Error) {
					$t.Name
				}
			}
		)
	}
}

$_ = $Build
Remove-Variable Checkpoint, Build, Preserve, Resume

Set-Alias Invoke-Build (Join-Path (Split-Path $MyInvocation.MyCommand.Path) Invoke-Build.ps1)
Invoke-Build @_ -Result ${*checkpoint}

if (!${*checkpoint}.Value.Error -and !${*checkpoint}.Preserve) {
	[System.IO.File]::Delete(${*checkpoint}.Checkpoint)
}
}
catch {
	if ($_.InvocationInfo.ScriptName -notmatch '\b(Invoke-Build|Build-Checkpoint)\.ps1$') {throw}
	$PSCmdlet.ThrowTerminatingError($_)
}
finally {
	if ($r = ${*checkpoint}.Result) {
		if ($r -is [string]) {
			New-Variable $r ${*checkpoint}.Value -Scope 1 -Force
		}
		else {
			$r.Value = ${*checkpoint}.Value
		}
	}
}
tools\InvokeBuild\Build-Parallel.ps1
<#
Copyright (c) Roman Kuzmin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
#>

#.ExternalHelp InvokeBuild-Help.xml
param(
	[Parameter(Position=0)][hashtable[]]$Build,
	$Result,
	[int]$Timeout=[int]::MaxValue,
	[int]$MaximumBuilds=[Environment]::ProcessorCount,
	[switch]$FailHard
)

# info, result
$info = [PSCustomObject]@{
	Tasks = [System.Collections.Generic.List[object]]@()
	Errors = [System.Collections.Generic.List[object]]@()
	Warnings = [System.Collections.Generic.List[object]]@()
	Started = [DateTime]::Now
	Elapsed = $null
}
if ($Result) {
	if ($Result -is [string]) {
		New-Variable $Result $info -Scope 1 -Force
	}
	else {
		$Result.Value = $info
	}
}

# no builds
if (!$Build) {return}

# get and source the engine
$ib = Join-Path (Split-Path $MyInvocation.MyCommand.Path) Invoke-Build.ps1
try {. $ib} catch {$PSCmdlet.ThrowTerminatingError($_)}
$ErrorActionPreference = 'Stop'

### make works, check scripts
$works = @()
for ($1 = 0; $1 -lt $Build.Count) {
	$b = @{} + $Build[$1]
	$Build[$1++] = $b

	if ($file = $b['File']) {
		if (![System.IO.File]::Exists(($file = *Path $file))) {*Die "Missing script '$file'." 13}
	}
	elseif (!($file = Get-BuildFile (*Path))) {
		*Die "Missing default script in build $1." 5
	}

	$b.Result = @{}
	$b.File = $file
	$b.Safe = $true

	$work = @{}
	$works += $work
	$work.Build = $b
	$work.Done = $false
	$work.Error1 = $null
	$work.Error2 = $null
	$work.Title = "($1/$($Build.Count)) $file"
}

### prepare logs and make shells
foreach($work in $works) {
	$b = $work.Build
	if ($log = $b['Log']) {
		$work.Temp = $false
		$b.Remove('Log')
		[System.IO.File]::Delete(($log = *Path $log))
	}
	else {
		$work.Temp = $true
		$log = [System.IO.Path]::GetTempFileName()
	}
	$work.Log = $log
	$work.PS = [PowerShell]::Create().AddCommand($ib).AddParameters($b).AddCommand('Out-File').AddParameter('FilePath', $log).AddParameter('Encoding', 'UTF8')
}

function Write-Log($work) {
	$file = $work.Log
	if ($work.Temp) {
		try {
			$read = [System.IO.File]::OpenText($file)
			while($null -ne ($_ = $read.ReadLine())) {$_}
			$read.Close()
		}
		catch {
			Write-Warning $_
		}
		[System.IO.File]::Delete($file)
	}
	else {
		"Log: $file"
	}
}

### main
if ($MaximumBuilds -lt 1) {*Die "MaximumBuilds should be a positive number." 5}
$MaximumBuilds = [math]::Min($MaximumBuilds, $Build.Count)
$stage = [System.Collections.Generic.List[object]]@()
$iWork = 0
$abort = ''
$failures = @()
$stopwatch = [Diagnostics.Stopwatch]::StartNew()
try {
	for() {
		### stage next work(s), BeginInvoke
		while($stage.Count -lt $MaximumBuilds -and $iWork -lt $works.Count) {
			$work = $works[$iWork++]
			$stage.Add($work)

			Write-Build Cyan "Start $($work.Title)"
			$work.Job = $work.PS.BeginInvoke()
		}
		if (!$stage) {break}

		### wait for any staged
		$waits = New-Object System.Collections.Generic.List[System.Threading.WaitHandle]
		foreach($work in $stage) {$waits.Add($work.Job.AsyncWaitHandle)}
		$time = $Timeout - $stopwatch.ElapsedMilliseconds
		$index = [System.Threading.WaitHandle]::WaitAny($waits.ToArray(), $time, $true)
		if ($index -eq [System.Threading.WaitHandle]::WaitTimeout) {
			$abort = 'Build timed out.'
			break
		}

		### unstage done, EndInvoke
		$work = $stage[$index]
		$stage.RemoveAt($index)
		$work.Done = $true
		try {
			$work.PS.EndInvoke($work.Job)
			$work.Error2 = $work.Build.Result.Value.Error
		}
		catch {
			$work.Error1 = "Invalid build arguments or script. Error: $_"
		}

		### abort?
		if (($work.Error1 -or $work.Error2) -and $FailHard) {
			$abort = "Aborted by $($work.Title)"
			break
		}
	}

	### finish works
	foreach($work in $works) {
		Write-Build Cyan "Build $($work.Title):"

		### get error and dispose
		$runtime = $false
		$_ = try {
			if ($work.Done) {
				if ($work.Error1) {
					$work.Error1
				}
				else {
					$runtime = $true
					$r = $work.Build.Result.Value
					$info.Tasks.AddRange($r.Tasks)
					$info.Errors.AddRange($r.Errors)
					$info.Warnings.AddRange($r.Warnings)
					$r.Error
				}
			}
			else {
				$work.PS.Stop()
				$abort
			}
		}
		catch {
			$_
		}
		finally {
			$work.PS.Dispose()
		}

		### log
		Write-Log $work

		### result
		if ($_) {
			Write-Build Cyan "Build $($work.Title) FAILED."
			$_ = if ($_ -is [System.Management.Automation.ErrorRecord] -and $runtime) {*Msg $_ $_} else {"$_"}
			Write-Build Red "ERROR: $_"
			$failures += @{
				File = $work.Title
				Error = $_
			}
		}
		else {
			Write-Build Cyan "Build $($work.Title) succeeded."
		}
	}

	### fail?
	if ($failures) {
		*Die ($(
			"Failed builds:"
			foreach($_ in $failures) {
				"Build: $($_.File)"
				"ERROR: $($_.Error)"
			}
		) -join [Environment]::NewLine)
	}
}
finally {
	$errors = $info.Errors.Count
	$warnings = $info.Warnings.Count
	$info.Elapsed = [DateTime]::Now - $info.Started

	if (($up = $PSCmdlet.SessionState.PSVariable.Get('*')) -and ($up = if ($up.Description -eq 'IB') {$up.Value})) {
		$up.Tasks.AddRange($info.Tasks)
		$up.Errors.AddRange($info.Errors)
		$up.Warnings.AddRange($info.Warnings)
	}

	$color, $text = if ($failures) {12, 'Builds FAILED'}
	elseif ($errors) {14, 'Builds completed with errors'}
	elseif ($warnings) {14, 'Builds succeeded with warnings'}
	else {10, 'Builds succeeded'}

	Write-Build $color @"
Tasks: $($info.Tasks.Count) tasks, $errors errors, $warnings warnings
$text. $($Build.Count) builds, $($failures.Count) failed $($info.Elapsed)
"@
}
tools\InvokeBuild\ib.cmd

:: ib.cmd - Invoke-Build helper for cmd.exe
:: It must be in the same directory as Invoke-Build.ps1

@echo off

if "%1"=="?" goto list
if "%1"=="/?" goto help

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0Invoke-Build.ps1' %*"
exit /B %errorlevel%

:list
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0Invoke-Build.ps1' %* | Format-Table -AutoSize"
exit /B 0

:help
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "help -Full '%~dp0Invoke-Build.ps1'"
exit /B 0
tools\InvokeBuild\Invoke-Build.ps1
<#
Copyright (c) Roman Kuzmin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
#>

#.ExternalHelp InvokeBuild-Help.xml
param(
	[Parameter(Position=0)][string[]]$Task,
	[Parameter(Position=1)]$File,
	$Result,
	[switch]$Safe,
	[switch]$Summary,
	[switch]$WhatIf
)

dynamicparam {

function *Path($P) {
	$PSCmdlet.GetUnresolvedProviderPathFromPSPath($P)
}

function *Die($M, $C=0) {
	$PSCmdlet.ThrowTerminatingError((New-Object System.Management.Automation.ErrorRecord ([Exception]"$M"), $null, $C, $null))
}

function Get-BuildFile($Path) {
	do {
		if (($f = [System.IO.Directory]::GetFiles($Path, '*.build.ps1')).Length -eq 1) {return $f}
		if ($_ = $f -match '[\\/]\.build\.ps1$') {return $_}
		if ($f.Length -ge 2) {throw "Ambiguous default script in '$Path'."}
		if ([System.IO.File]::Exists(($_ = $env:InvokeBuildGetFile)) -and ($_ = & $_ $Path)) {return $_}
	} while($Path = Split-Path $Path)
}

if ($MyInvocation.InvocationName -eq '.') {return}
trap {*Die $_ 5}

New-Variable * -Description IB ([PSCustomObject]@{
	All = [System.Collections.Specialized.OrderedDictionary]([System.StringComparer]::OrdinalIgnoreCase)
	Tasks = [System.Collections.Generic.List[object]]@()
	Errors = [System.Collections.Generic.List[object]]@()
	Warnings = [System.Collections.Generic.List[object]]@()
	Redefined = @()
	Doubles = @()
	Started = [DateTime]::Now
	Elapsed = $null
	Error = 'Invalid arguments.'
	Task = $null
	File = $BuildFile = $PSBoundParameters['File']
	Safe = $PSBoundParameters['Safe']
	Summary = $PSBoundParameters['Summary']
	CD = *Path
	DP = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
	SP = @{}
	P = $(if ($_ = $PSCmdlet.SessionState.PSVariable.Get('*')) {if ($_.Description -eq 'IB') {$_.Value}})
	A = 1
	B = 0
	Q = 0
	H = @{}
	EnterBuild = $null
	ExitBuild = $null
	EnterTask = $null
	ExitTask = $null
	EnterJob = $null
	ExitJob = $null
	Header = {Write-Build 11 "Task $($args[0])"}
	Footer = {Write-Build 11 "Done $($args[0]) $($Task.Elapsed)"}
	Data = @{}
	XBuild = $null
	XCheck = $null
})
if ($_ = $PSBoundParameters['Result']) {
	if ($_ -is [string]) {
		New-Variable $_ ${*} -Scope 1 -Force
	}
	elseif ($_ -is [hashtable]) {
		${*}.XBuild = $_['XBuild']
		${*}.XCheck = $_['XCheck']
		$_.Value = ${*}
	}
	else {throw 'Invalid parameter Result.'}
}
$BuildTask = $PSBoundParameters['Task']
if ($BuildFile -is [scriptblock]) {
	$BuildFile = $BuildFile.File
	return
}
if ($BuildTask -eq '**') {
	if (![System.IO.Directory]::Exists(($_ = *Path $BuildFile))) {throw "Missing directory '$_'."}
	$BuildFile = @(Get-ChildItem -LiteralPath $_ -Filter *.test.ps1 -Recurse)
	return
}

if ($BuildFile) {
	if (![System.IO.File]::Exists(($BuildFile = *Path $BuildFile))) {throw "Missing script '$BuildFile'."}
}
elseif (!($BuildFile = Get-BuildFile ${*}.CD)) {
	throw 'Missing default script.'
}
${*}.File = $BuildFile

if (!($_ = (Get-Command $BuildFile -ErrorAction 1).Parameters)) {
	& $BuildFile
	throw 'Invalid script.'
}
if ($_.Count) {&{
	$c = 'Verbose', 'Debug', 'ErrorAction', 'WarningAction', 'ErrorVariable', 'WarningVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable', 'InformationAction', 'InformationVariable'
	$r = 'Task', 'File', 'Result', 'Safe', 'Summary', 'WhatIf'
	foreach($p in $_.Values) {
		if ($c -notcontains ($_ = $p.Name)) {
			if ($r -contains $_) {throw "Script uses reserved parameter '$_'."}
			${*}.DP.Add($_, (New-Object System.Management.Automation.RuntimeDefinedParameter $_, $p.ParameterType, $p.Attributes))
		}
	}
	${*}.DP
}}

} end {

#.ExternalHelp InvokeBuild-Help.xml
function Add-BuildTask(
	[Parameter(Position=0, Mandatory=1)][string]$Name,
	[Parameter(Position=1)]$Jobs,
	[string[]]$After,
	[string[]]$Before,
	$If=-9,
	$Inputs,
	$Outputs,
	$Data,
	$Done,
	$Source=$MyInvocation,
	[switch]$Partial
)
{
	trap {*Die "Task '$Name': $_" 5}
	if ($Jobs -is [hashtable]) {
		if ($PSBoundParameters.Count -ne 2) {throw 'Invalid parameters.'}
		Add-BuildTask $Name @Jobs -Source:$Source
		return
	}
	if ($Name[0] -eq '?') {throw 'Invalid task name.'}
	if ($_ = ${*}.All[$Name]) {${*}.Redefined += $_}
	${*}.All[$Name] = [PSCustomObject]@{
		Name = $Name
		Error = $null
		Started = $null
		Elapsed = $null
		Jobs = $1 = [System.Collections.Generic.List[object]]@()
		After = $After
		Before = $Before
		If = $If
		Inputs = $Inputs
		Outputs = $Outputs
		Data = $Data
		Done = $Done
		Partial = $Partial
		InvocationInfo = $Source
	}
	if (!$Jobs) {return}
	$1.AddRange(@($Jobs))
	$2 = @()
	foreach($j in $1) {
		$r, $null = *Job $j
		if ($2 -contains $r) {${*}.Doubles += ,($Name, $r)}
		$2 += $r
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Assert-Build([Parameter()]$Condition, [string]$Message) {
	if (!$Condition) {
		*Die "Assertion failed.$(if ($Message) {" $Message"})" 7
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Assert-BuildEquals([Parameter()]$A, $B) {
	if (![Object]::Equals($A, $B)) {
		*Die @"
Objects are not equal:
A:$(if ($null -ne $A) {" $A [$($A.GetType())]"})
B:$(if ($null -ne $B) {" $B [$($B.GetType())]"})
"@ 7
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Get-BuildError([Parameter(Mandatory=1)][string]$Task) {
	if (!($_ = ${*}.All[$Task])) {
		*Die "Missing task '$Task'." 5
	}
	$_.Error
}

#.ExternalHelp InvokeBuild-Help.xml
function Get-BuildProperty([Parameter(Mandatory=1)][string]$Name, $Value) {
	${*n} = $Name
	${*v} = $Value
	Remove-Variable Name, Value
	if (($null -ne ($_ = $PSCmdlet.GetVariableValue(${*n})) -and '' -ne $_) -or ($_ = [Environment]::GetEnvironmentVariable(${*n}))) {return $_}
	if ($null -eq ${*v}) {*Die "Missing property '${*n}'." 13}
	${*v}
}

#.ExternalHelp InvokeBuild-Help.xml
function Get-BuildSynopsis([Parameter(Mandatory=1)]$Task, $Hash=${*}.H) {
	$f = ($I = $Task.InvocationInfo).ScriptName
	if (!($d = $Hash[$f])) {
		$Hash[$f] = $d = @{T = Get-Content -LiteralPath $f; C = @{}}
		foreach($_ in [System.Management.Automation.PSParser]::Tokenize($d.T, [ref]$null)) {
			if ($_.Type -eq 15) {$d.C[$_.EndLine] = $_.Content}
		}
	}
	for($n = $I.ScriptLineNumber; --$n -ge 1) {
		if ($c = $d.C[$n]) {if ($c -match '(?m)^\s*#*\s*Synopsis\s*:(.*)') {return $Matches[1].Trim()}}
		elseif ($d.T[$n - 1].Trim()) {break}
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Invoke-BuildExec([Parameter(Mandatory=1)][scriptblock]$Command, [int[]]$ExitCode=0) {
	${private:*c} = $Command
	${private:*x} = $ExitCode
	Remove-Variable Command, ExitCode
	& ${*c}
	if (${*x} -notcontains $global:LastExitCode) {
		*Die "Command {${*c}} exited with code $global:LastExitCode." 8
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Remove-BuildItem([Parameter(Mandatory=1)][string[]]$Path) {
	if ($Path -match '^[.*/\\]*$') {*Die 'Not allowed paths.' 5}
	$v = $PSBoundParameters['Verbose']
	try {
		foreach($_ in $Path) {
			if (Get-Item $_ -Force -ErrorAction 0) {
				if ($v) {Write-Verbose "remove: removing $_" -Verbose}
				Remove-Item $_ -Force -Recurse
			}
			elseif ($v) {Write-Verbose "remove: skipping $_" -Verbose}
		}
	}
	catch {
		*Die $_
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Test-BuildAsset([Parameter(Position=0)][string[]]$Variable, [string[]]$Environment, [string[]]$Property) {
	Remove-Variable Variable, Environment, Property
	if ($_ = $PSBoundParameters['Variable']) {foreach($_ in $_) {
		if ($null -eq ($$ = $PSCmdlet.GetVariableValue($_)) -or '' -eq $$) {*Die "Missing variable '$_'." 13}
	}}
	if ($_ = $PSBoundParameters['Environment']) {foreach($_ in $_) {
		if (!([Environment]::GetEnvironmentVariable($_))) {*Die "Missing environment variable '$_'." 13}
	}}
	if ($_ = $PSBoundParameters['Property']) {foreach($_ in $_) {
		if ('' -eq (Get-BuildProperty $_ '')) {*Die "Missing property '$_'." 13}
	}}
}

#.ExternalHelp InvokeBuild-Help.xml
function Use-BuildAlias([Parameter(Mandatory=1)][string]$Path, [string[]]$Name) {
	trap {*Die $_ 5}
	$d = switch -regex ($Path) {
		'^\*|^\d+\.' {Split-Path (Resolve-MSBuild $_)}
		^Framework {"$env:windir\Microsoft.NET\$_"}
		default {*Path $_}
	}
	if (![System.IO.Directory]::Exists($d)) {throw "Cannot resolve '$Path'."}
	foreach($_ in $Name) {
		Set-Alias $_ (Join-Path $d $_) -Scope 1
	}
}

#.ExternalHelp InvokeBuild-Help.xml
function Set-BuildFooter([Parameter()][scriptblock]$Script) {${*}.Footer = $Script}

#.ExternalHelp InvokeBuild-Help.xml
function Set-BuildHeader([Parameter()][scriptblock]$Script) {${*}.Header = $Script}

#.ExternalHelp InvokeBuild-Help.xml
function Write-Build([ConsoleColor]$Color, [string]$Text) {
	$i = $Host.UI.RawUI
	$_ = $i.ForegroundColor
	try {
		$i.ForegroundColor = $Color
		$Text
	}
	finally {
		$i.ForegroundColor = $_
	}
}
if ($env:APPVEYOR) {
	function Write-Build([ConsoleColor]$Color, [string]$Text) {Write-Host $Text -ForegroundColor $Color}
}
else {
	try {$null = Write-Build 0} catch {function Write-Build($Color, [string]$Text) {$Text}}
}

function *My {
	$_.InvocationInfo.ScriptName -eq $MyInvocation.ScriptName
}

function *SL($P=$BuildRoot) {
	Set-Location -LiteralPath $P -ErrorAction 1
}

function *Fin([Parameter()]$M, $C=0) {
	*Die $M $C
}

function *Run($_) {
	if ($_) {
		*SL
		. $_ @args
	}
}

function *At($I) {
	$I.InvocationInfo.PositionMessage.Trim()
}

function *Msg($M, $I) {
@"
$M
$(*At $I)
"@
}

function *Job($J) {
	if ($J -is [string]) {if ($J[0] -eq '?') {$J.Substring(1), 1} else {$J}}
	elseif ($J -is [scriptblock]) {$J}
	else {*Fin 'Invalid job.' 5}
}

function *Unsafe($N, $J) {
	if ($J -contains $N) {return 1}
	foreach($_ in $J) {
		$r, $null = *Job $_
		if ($r -ne $N -and ($t = ${*}.All[$r]) -and $t.If -and (*Unsafe $N $t.Jobs)) {
			return 1
		}
	}
}

function *Amend($X, $J, $B) {
	$n = $X.Name
	foreach($_ in $J) {
		$r, $s = *Job $_
		if (!($t = ${*}.All[$r])) {*Fin (*Msg "Task '$n': Missing task '$r'." $X) 5}
		$j = $t.Jobs
		$i = $j.Count
		if ($B) {
			for($k = -1; ++$k -lt $i -and $j[$k] -is [string]) {}
			$i = $k
		}
		$j.Insert($i, $(if ($s) {"?$n"} else {$n}))
	}
}

function *Check($J, $T, [email protected]()) {
	foreach($_ in $J) { if ($_ -is [string]) {
		$_, $null = *Job $_
		if (!($r = ${*}.All[$_])) {
			$_ = "Missing task '$_'."
			*Fin $(if ($T) {*Msg "Task '$($T.Name)': $_" $T} else {$_}) 5
		}
		if ($P -contains $r) {
			*Fin (*Msg "Task '$($T.Name)': Cyclic reference to '$_'." $T) 5
		}
		*Check $r.Jobs $r ($P + $r)
	}}
}

filter *Help {
	$r = 1 | Select-Object Name, Jobs, Synopsis
	$r.Name = $_.Name
	$r.Jobs = foreach($j in $_.Jobs) {if ($j -is [string]) {$j} else {'{}'}}
	$r.Synopsis = Get-BuildSynopsis $_
	$r
}

function *Root($A) {
	*Check $A.Keys
	$h = @{}
	foreach($_ in $A.Values) {foreach($_ in $_.Jobs) {
		if ($_ -is [string]) {
			$_, $null = *Job $_
			$h[$_] = 1
		}
	}}
	foreach($_ in $A.Keys) {if (!$h[$_]) {$_}}
}

function *Err($T) {
	${*}.Errors.Add([PSCustomObject]@{Error = $_; File = $BuildFile; Task = $T})
	Write-Build 12 "ERROR: $(if (*My) {$_} else {*Msg $_ $_})"
	if ($T) {$T.Error = $_}
}

function *IO {
	if ((${private:*i} = $Task.Inputs) -is [scriptblock]) {
		*SL
		${*i} = @(& ${*i})
	}
	*SL
	${private:*p} = [System.Collections.Generic.List[object]]@()
	${*i} = foreach($_ in ${*i}) {
		if ($_ -isnot [System.IO.FileInfo]) {$_ = [System.IO.FileInfo](*Path $_)}
		if (!$_.Exists) {*Fin "Missing input '$_'." 13}
		${*p}.Add($_.FullName)
		$_
	}
	if (!${*p}) {return 2, 'Skipping empty input.'}

	${private:*o} = $Task.Outputs
	if ($Task.Partial) {
		${*o} = @(
			if (${*o} -is [scriptblock]) {
				${*p} | & ${*o}
				*SL
			}
			else {
				${*o}
			}
		)
		if (${*p}.Count -ne ${*o}.Count) {*Fin "Different Inputs/Outputs counts: $(${*p}.Count)/$(${*o}.Count)." 6}

		$k = -1
		$Task.Inputs = $i = [System.Collections.Generic.List[object]]@()
		$Task.Outputs = $o = [System.Collections.Generic.List[object]]@()
		foreach($_ in ${*i}) {
			$f = *Path ($p = ${*o}[++$k])
			if (![System.IO.File]::Exists($f) -or $_.LastWriteTime -gt [System.IO.File]::GetLastWriteTime($f)) {
				$i.Add(${*p}[$k])
				$o.Add($p)
			}
		}
		if ($i) {return $null, "Out-of-date outputs: $($o.Count)/$(${*p}.Count)."}
	}
	else {
		if (${*o} -is [scriptblock]) {
			$Task.Outputs = ${*o} = ${*p} | & ${*o}
			*SL
		}
		if (!${*o}) {*Fin 'Outputs must not be empty.' 5}

		$Task.Inputs = ${*p}
		$m = (${*i} | .{process{$_.LastWriteTime.Ticks}} | Measure-Object -Maximum).Maximum
		foreach($_ in ${*o}) {
			$p = *Path $_
			if (![System.IO.File]::Exists($p)) {return $null, "Missing output '$_'."}
			if ($m -gt [System.IO.File]::GetLastWriteTime($p).Ticks) {return $null, "Out-of-date output '$_'."}
		}
	}
	2, 'Skipping up-to-date output.'
}

function *Task {
	${private:*p} = "$($args[1])/$($args[0])"
	${private:*n}, ${private:*s} = *Job $args[0]
	New-Variable Task (${*}.Task = ${*}.All[${*n}]) -Option Constant

	if ($Task.Elapsed) {
		Write-Build 8 "Done ${*p}"
		return
	}

	$Task.Started = [DateTime]::Now
	if ((${private:*x} = $Task.If) -is [scriptblock]) {
		*SL
		try {
			${*x} = & ${*x}
		}
		catch {
			*Err $Task
			${*}.Tasks.Add($Task)
			Write-Build 14 (*At $Task)
			$Task.Elapsed = [TimeSpan]::Zero
			throw
		}
	}
	if (!${*x}) {
		Write-Build 8 "Task ${*p} skipped."
		return
	}

	${private:*i} = , [int]($null -ne $Task.Inputs)
	try {
		. *Run ${*}.EnterTask
		foreach(${private:*j} in $Task.Jobs) {
			if (${*j} -is [string]) {
				try {
					*Task ${*j} ${*p}
				}
				finally {
					${*}.Task = $Task
				}
				continue
			}
			& ${*}.Header ${*p}

			if (1 -eq ${*i}[0]) {
				try {
					${*i} = *IO
				}
				catch {
					*Err $Task
					throw
				}
				Write-Build 8 ${*i}[1]
			}
			if (${*i}[0]) {
				continue
			}

			try {
				. *Run ${*}.EnterJob
				*SL
				if (0 -eq ${*i}[0]) {
					& ${*j}
				}
				else {
					$Inputs = $Task.Inputs
					$Outputs = $Task.Outputs
					if ($Task.Partial) {
						${*x} = 0
						$Inputs | .{process{
							$2 = $Outputs[${*x}++]
							$_
						}} | & ${*j}
					}
					else {
						$Inputs | & ${*j}
					}
				}
			}
			catch {
				*Err $Task
				throw
			}
			finally {
				. *Run ${*}.ExitJob
			}
		}
	}
	catch {
		$Task.Error = $_
		if (!${*s} -or (*Unsafe ${*n} $BuildTask)) {throw}
	}
	finally {
		$Task.Elapsed = [DateTime]::Now - $Task.Started
		${*}.Tasks.Add($Task)
		if ($Task.Error) {
			Write-Build 14 (*At $Task)
		}
		else {
			if (${*}.XCheck) {& ${*}.XCheck}
			& ${*}.Footer ${*p}
		}
		*Run $Task.Done
		. *Run ${*}.ExitTask
	}
}

Set-Alias assert Assert-Build
Set-Alias equals Assert-BuildEquals
Set-Alias error Get-BuildError
Set-Alias exec Invoke-BuildExec
Set-Alias property Get-BuildProperty
Set-Alias remove Remove-BuildItem
Set-Alias requires Test-BuildAsset
Set-Alias task Add-BuildTask
Set-Alias use Use-BuildAlias
Set-Alias Invoke-Build ($_ = $MyInvocation.MyCommand.Path)
$_ = Split-Path $_
Set-Alias Show-TaskHelp (Join-Path $_ Show-TaskHelp.ps1)
Set-Alias Build-Parallel (Join-Path $_ Build-Parallel.ps1)
Set-Alias Resolve-MSBuild (Join-Path $_ Resolve-MSBuild.ps1)

if ($MyInvocation.InvocationName -eq '.') {
	Remove-Variable Task, File, Result, Safe, Summary, WhatIf
	return
}

function Write-Warning([Parameter()]$Message) {
	$PSCmdlet.WriteWarning($Message)
	${*}.Warnings.Add([PSCustomObject]@{Message = $Message; File = $BuildFile; Task = ${*}.Task})
}

$ErrorActionPreference = 'Stop'
foreach($_ in $PSBoundParameters.Keys) {
	if (${*}.DP.ContainsKey($_)) {
		${*}.SP[$_] = $PSBoundParameters[$_]
	}
}
if (${*}.Q = $BuildTask -eq '?' -or $BuildTask -eq '??') {
	$WhatIf = $true
}
Remove-Variable Task, File, Result, Safe, Summary

${*}.Error = $null
try {
	if ($BuildTask -eq '**') {
		${*}.A = 0
		foreach($_ in $BuildFile) {
			Invoke-Build * $_.FullName -Safe:${*}.Safe
		}
		${*}.B = 1
		exit
	}

	function Enter-Build([Parameter()][scriptblock]$Script) {${*}.EnterBuild = $Script}
	function Exit-Build([Parameter()][scriptblock]$Script) {${*}.ExitBuild = $Script}
	function Enter-BuildTask([Parameter()][scriptblock]$Script) {${*}.EnterTask = $Script}
	function Exit-BuildTask([Parameter()][scriptblock]$Script) {${*}.ExitTask = $Script}
	function Enter-BuildJob([Parameter()][scriptblock]$Script) {${*}.EnterJob = $Script}
	function Exit-BuildJob([Parameter()][scriptblock]$Script) {${*}.ExitJob = $Script}
	function Set-BuildData([Parameter()]$Key, $Value) {${*}.Data[$Key] = $Value}

	*SL ($BuildRoot = if ($BuildFile) {Split-Path $BuildFile} else {${*}.CD})
	$_ = ${*}.SP
	${private:**} = @(. ${*}.File @_)
	foreach($_ in ${**}) {
		Write-Warning "Unexpected output: $_."
		if ($_ -is [scriptblock]) {*Fin "Dangling scriptblock at $($_.File):$($_.StartPosition.StartLine)" 6}
	}
	if (!(${**} = ${*}.All).Count) {*Fin "No tasks in '$BuildFile'." 6}

	foreach($_ in ${**}.Values) {
		if ($_.Before) {*Amend $_ $_.Before 1}
	}
	foreach($_ in ${**}.Values) {
		if ($_.After) {*Amend $_ $_.After}
	}

	if (${*}.Q) {
		*Check ${**}.Keys
		if ($BuildTask -eq '?') {
			${**}.Values | *Help
		}
		else {
			${**}
		}
		exit
	}

	if ($BuildTask -eq '*') {
		$BuildTask = *Root ${**}
	}
	else {
		if (!$BuildTask -or '.' -eq $BuildTask) {
			$BuildTask = if (${**}['.']) {'.'} else {${**}.Item(0).Name}
		}
		*Check $BuildTask
	}
	if ($WhatIf) {
		Show-TaskHelp
		exit
	}

	New-Variable BuildRoot (*Path $BuildRoot) -Option Constant -Force
	if (![System.IO.Directory]::Exists($BuildRoot)) {*Fin "Missing build root '$BuildRoot'." 13}

	Write-Build 11 "Build $($BuildTask -join ', ') $BuildFile"
	foreach($_ in ${*}.Redefined) {
		Write-Build 8 "Redefined task '$($_.Name)'."
	}
	foreach($_ in ${*}.Doubles) {
		if (${*}.All[$_[1]].If -isnot [scriptblock]) {
			Write-Warning "Task '$($_[0])' always skips '$($_[1])'."
		}
	}

	${*}.A = 0
	try {
		. *Run ${*}.EnterBuild
		if (${*}.XBuild) {. ${*}.XBuild}
		if (${*}.XCheck) {& ${*}.XCheck}
		foreach($_ in $BuildTask) {
			*Task $_ ''
		}
	}
	finally {
		${*}.Task = $null
		. *Run ${*}.ExitBuild
	}
	${*}.B = 1
	exit
}
catch {
	${*}.B = 2
	${*}.Error = $_
	if (!${*}.Errors) {*Err}
	if ($_.FullyQualifiedErrorId -eq 'PositionalParameterNotFound,Add-BuildTask') {
		Write-Warning 'Check task parameters: Name and comma separated Jobs.'
	}
	if (${*}.Safe) {
		exit
	}
	elseif (*My) {
		$PSCmdlet.ThrowTerminatingError($_)
	}
	throw
}
finally {
	*SL ${*}.CD
	if (${*}.B -and !${*}.Q) {
		$t = ${*}.Tasks
		$e = ${*}.Errors
		if (${*}.Summary) {
			Write-Build 11 'Build summary:'
			foreach($_ in $t) {
				'{0,-16} {1} - {2}:{3}' -f $_.Elapsed, $_.Name, $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber
				if ($_ = $_.Error) {
					Write-Build 12 "ERROR: $(if (*My) {$_} else {*Msg $_ $_})"
				}
			}
		}
		if ($w = ${*}.Warnings) {
			foreach($_ in $w) {
				"WARNING: $($_.Message)$(if ($_.Task) {" Task: $($_.Task.Name)."}) File: $($_.File)."
			}
		}
		if ($_ = ${*}.P) {
			$_.Tasks.AddRange($t)
			$_.Errors.AddRange($e)
			$_.Warnings.AddRange($w)
		}
		$c, $m = if (${*}.A) {12, "Build ABORTED $BuildFile"}
		elseif (${*}.B -eq 2) {12, 'Build FAILED'}
		elseif ($e) {14, 'Build completed with errors'}
		elseif ($w) {14, 'Build succeeded with warnings'}
		else {10, 'Build succeeded'}
		Write-Build $c "$m. $($t.Count) tasks, $($e.Count) errors, $($w.Count) warnings $((${*}.Elapsed = [DateTime]::Now - ${*}.Started))"
	}
}
}
tools\InvokeBuild\InvokeBuild-Help.xml
<?xml version="1.0" encoding="utf-8"?>
<helpItems xmlns="http://msh" schema="maml">
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Invoke-Build.ps1</command:name>
<maml:description>
<maml:para>Invoke-Build - Build Automation in PowerShell</maml:para>
</maml:description>
</command:details>
<maml:description>
<maml:para>The command invokes so called tasks defined in a PowerShell script.
Let&apos;s call this process build and a script with tasks build script.

A build script defines parameters, variables, and one or more tasks.
Any code is invoked with the current location set to $BuildRoot,
the script directory. $ErrorActionPreference is set to &apos;Stop&apos;.

SCRIPT PARAMETERS

Build scripts define parameters as usual using the param() block.
On calling, specify them for Invoke-Build as if they are its own.

Known issue #4. Specify script switches after Task and File.

The following parameter names are reserved for the engine:
Task, File, Result, Safe, Summary, WhatIf

COMMANDS AND HELP

The following commands are available for build scripts:

    task      (Add-BuildTask)
    exec      (Invoke-BuildExec)
    assert    (Assert-Build)
    equals    (Assert-BuildEquals)
    remove    (Remove-BuildItem)
    property  (Get-BuildProperty)
    requires  (Test-BuildAsset)
    use       (Use-BuildAlias)
    error     (Get-BuildError)

    Get-BuildSynopsis
    Resolve-MSBuild
    Set-BuildFooter
    Set-BuildHeader
    Write-Build
    Write-Warning [1]

[1] Write-Warning is redefined internally in order to count warnings in
a build script and nested scripts. Warnings in modules are not counted.

To get commands help, dot-source Invoke-Build and then call help:

    PS&gt; . Invoke-Build
    PS&gt; help task -full

SPECIAL ALIASES

    Invoke-Build
    Build-Parallel

These aliases are for the scripts Invoke-Build.ps1 and Build-Parallel.ps1.
Use them for calling nested builds, i.e. omit script extensions and paths.

PUBLIC VARIABLES

    $WhatIf    - WhatIf mode, Invoke-Build parameter
    $BuildRoot - build script location, by default
    $BuildFile - build script path
    $BuildTask - initial tasks
    $Task      - current task

$BuildRoot may be changed by scripts on loading in order to set a custom
build root directory. Other variables should not be changed.

$Task is available for script blocks defined by task parameters If, Inputs,
Outputs, and Jobs and by blocks Enter|Exit-BuildTask, Enter|Exit-BuildJob,
Set-BuildHeader, Set-BuildFooter.

    $Task properties:

    - Name - [string], task name
    - Jobs - [object[]], task jobs
    - Started - [DateTime], task start time

    And in Exit-BuildTask:

    - Error - task error or null
    - Elapsed - [TimeSpan], task duration

BUILD BLOCKS

Scripts may define special script blocks. They are invoked:

    Enter-Build {} - before the first task
    Exit-Build {} - after the last task

    Enter-BuildTask {} - before each task
    Exit-BuildTask {} - after each task

    Enter-BuildJob {} - before each task action
    Exit-BuildJob {} - after each task action

    Set-BuildHeader {param($Path)} - to write task headers
    Set-BuildFooter {param($Path)} - to write task footers

Blocks are not called on WhatIf.
Nested builds do not inherit parent blocks.
If Enter-X is called then Exit-X is also called, even on failures.

Enter-Build and Exit-Build are invoked in the script scope. Enter-Build is
suitable for initialization and it can output text unlike the build script.

Enter-BuildTask, Exit-BuildTask, Enter-BuildJob, and Exit-BuildJob are
invoked in the same scope, the parent of task action blocks.

PRIVATE STUFF

Function and variable names starting with &apos;*&apos; are reserved for the engine.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Invoke-Build.ps1</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Task</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>File</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Result</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Safe</maml:name>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Summary</maml:name>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>WhatIf</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Task</maml:name>
<maml:description>
<maml:para>One or more tasks to be invoked. If it is not specified, null, empty,
or equal to &apos;.&apos; then the task &apos;.&apos; is invoked if it exists, otherwise
the first added task is invoked.

Names with wildcard characters are reserved for special cases.

SAFE REFERENCES

If a task &apos;X&apos; is referenced as &apos;?X&apos; then it is allowed to fail without
breaking the build, i.e. other tasks specified after X will be invoked.

SPECIAL TASKS

? - Tells to list tasks with brief information and check for errors.
Task synopses are defined in preceding comments as # Synopsis: ...

?? - Tells to collect and get all tasks as an ordered dictionary.
It can be used by external tools for analysis, completion, etc.

Tasks ? and ?? set $WhatIf to true. Properly designed build scripts
should not perform anything significant if $WhatIf is set to true.

* - Tells to invoke all tasks, for example when tasks are tests.

** - Invokes * for all files *.test.ps1 found recursively in the
current directory or a directory specified by the parameter File.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>File</maml:name>
<maml:description>
<maml:para>A build script which adds tasks by the command &apos;task&apos; (Add-BuildTask).

If it is not specified then Invoke-Build looks for *.build.ps1 files in
the current location. A single file is used as the script. If there are
more files then .build.ps1 is used if it exists, otherwise build fails.

If the build file is not found then a script defined by the environment
variable InvokeBuildGetFile is called with the path as an argument. For
this location it may return the full path of a special build script.

If the file is still not found then parent directories are searched.

INLINE SCRIPT

&apos;File&apos; is a script block which is normally used in order to assemble a
build on the fly without creating and using an extra build script file.

$BuildFile is the calling script (or null, e.g. in jobs).
The default $BuildRoot is its directory (or the current location).

Script parameters, parallel, and persistent builds are not supported.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Result</maml:name>
<maml:description>
<maml:para>Tells to make the build result. Normally it is the name of a variable
created in the calling scope. Or it is a hashtable which entry Value
contains the result.

Result properties:

    All - all available tasks
    Error - a terminating build error
    Tasks - invoked tasks including nested
    Errors - error objects including nested
    Warnings - warning objects including nested
    Redefined - list of original redefined tasks

Tasks is a list of objects:

    Name - task name
    Jobs - task jobs
    Error - task error
    Started - start time
    Elapsed - task duration
    InvocationInfo - task location (.ScriptName, .ScriptLineNumber)

Errors is a list of objects:

    Error - original error
    File - current $BuildFile
    Task - current $Task or null for other errors

Warnings is a list of objects:

    Message - warning message
    File - current $BuildFile
    Task - current $Task or null for other warnings

Do not change these data and do not use not documented members.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Safe</maml:name>
<maml:description>
<maml:para>Tells to catch a build failure, store an error as the property Error of
Result and return quietly. A caller should use Result and check Error.

Some exceptions are possible even in the safe mode. They show serious
errors, not build failures. For example, a build script is missing.

When Safe is used together with the special task ** (invoke *.test.ps1)
then task failures stop current test scripts, not the whole testing.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Summary</maml:name>
<maml:description>
<maml:para>Tells to show summary information after the build. It includes task
durations, names, locations, and error messages.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>WhatIf</maml:name>
<maml:description>
<maml:para>Tells to show tasks and jobs to be invoked and some analysis of used
parameters and environment variables. See Show-TaskHelp for details.

If a script does anything but adding tasks then it should check for
$WhatIf and skip the real actions in order to support WhatIf calls.
Alternatively, use the Enter-Build block for pre-build actions.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Text</maml:name>
</dev:type>
<maml:description>
<maml:para>Build log which includes task records and engine messages, warnings,
errors, and output from build script tasks and special blocks.

The script itself should not output anything. Unexpected script output
causes warnings, in the future it may be treated as an error.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code>## How to call Invoke-Build in order to deal with build failures.
## Use one of the below techniques or you may miss some failures.

## (1/2) If you do not want to catch errors and just want the calling
## script to stop on build failures then

$ErrorActionPreference = &apos;Stop&apos;
Invoke-Build ...

## (2/2) If you want to catch build errors and proceed further depending
## on them then use try/catch, $ErrorActionPreference does not matter:

try {
    Invoke-Build ...
    # Build completed
}
catch {
    # Build FAILED, $_ is the error
}</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 2 --------------------------</maml:title>
<dev:code># Invoke tasks Build and Test from the default script with parameters.
# The script defines parameters Output and WarningLevel by param().

Invoke-Build Build, Test -Output log.txt -WarningLevel 4</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 3 --------------------------</maml:title>
<dev:code># Show tasks in the default script and the specified script

Invoke-Build ?
Invoke-Build ? Project.build.ps1

# Custom formatting is possible, too

Invoke-Build ? | Format-Table -AutoSize
Invoke-Build ? | Format-List Name, Synopsis</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 4 --------------------------</maml:title>
<dev:code># Get task names without invoking for listing, TabExpansion, etc.

$all = Invoke-Build ??
$all.Keys</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 5 --------------------------</maml:title>
<dev:code># Invoke all in Test1.test.ps1 and all in Tests\...\*.test.ps1

Invoke-Build * Test1.test.ps1
Invoke-Build ** Tests</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 6 --------------------------</maml:title>
<dev:code># How to use build results, e.g. for summary

try {
    # Invoke build and get the variable Result
    Invoke-Build -Result Result
}
finally {
    # Show build error
    &quot;Build error: $(if ($Result.Error) {$Result.Error} else {&apos;None&apos;})&quot;

    # Show task summary
    $Result.Tasks | Format-Table Elapsed, Name, Error -AutoSize
}</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Wiki</maml:linkText>
<maml:uri>https://github.com/nightroman/Invoke-Build/wiki</maml:uri>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Project</maml:linkText>
<maml:uri>https://github.com/nightroman/Invoke-Build</maml:uri>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Build-Checkpoint</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Build-Parallel</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>For other commands, at first invoke:</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>PS&gt; . Invoke-Build</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>task      (Add-BuildTask)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>exec      (Invoke-BuildExec)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>assert    (Assert-Build)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>equals    (Assert-BuildEquals)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>remove    (Remove-BuildItem)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>property  (Get-BuildProperty)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>requires  (Test-BuildAsset)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>use       (Use-BuildAlias)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>error     (Get-BuildError)</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Get-BuildSynopsis</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Resolve-MSBuild</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Set-BuildFooter</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Set-BuildHeader</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Write-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Add-BuildTask</command:name>
<maml:description>
<maml:para>(task) Defines and adds a task.</maml:para>
</maml:description>
<command:verb>Add</command:verb>
<command:noun>BuildTask</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;task&apos;. It is normally used in the build script scope
but it can be called from another script or function. Build scripts should
have at least one task.

This command is all that build scripts really need. Tasks are main build
blocks. Other build commands are helpers, scripts do not have to use them.

In addition to task parameters, you may use task help comments, synopses,
preceding task definitions:

    # Synopsis: ...
    task ...

Synopses are used in task help information returned by the command

    Invoke-Build ?

To get a task synopsis during a build, use Get-BuildSynopsis.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Add-BuildTask</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Name</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Jobs</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>After</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Before</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Data</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Done</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>If</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Inputs</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Outputs</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Source</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Partial</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Name</maml:name>
<maml:description>
<maml:para>The task name. Wildcard characters are deprecated and &quot;?&quot; must not be
the first character. Duplicated names are allowed, each added task
overrides previously added with the same name.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Jobs</maml:name>
<maml:description>
<maml:para>Specifies one or more task jobs or a hashtable with actual parameters.
Jobs are other task references and own actions, script blocks. Any
number of jobs is allowed. Jobs are invoked in the specified order.

Valid jobs are:

    [string] - an existing task name, normal reference
    [string] &quot;?Name&quot; - safe reference to a task allowed to fail
    [scriptblock] - action, a script block invoked for this task

Special value:

    [hashtable] which contains the actual task parameters in addition
    to the task name. This task definition is more convenient with
    complex parameters, often typical for incremental tasks.

    Example:
        task Name @{
            Inputs = {...}
            Outputs = {...}
            Partial = $true
            Jobs = {
                process {...}
            }
        }</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>After</maml:name>
<maml:description>
<maml:para>Tells to add this task to the end of jobs of the specified tasks.

Altered tasks are defined as normal references (TaskName) or safe
references (?TaskName). In the latter case this inserted task may
fail without stopping a build.

Parameters After and Before are used in order to alter task jobs
in special cases when direct changes in task source code are not
suitable. Use Jobs in order to define relations in usual cases.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Before</maml:name>
<maml:description>
<maml:para>Tells to insert this task to jobs of the specified tasks.
It is inserted before the first action or added to the end.

See After for details.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Data</maml:name>
<maml:description>
<maml:para>Any object attached to the task. It is not used by the engine.
When the task is invoked this object is available as $Task.Data.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Done</maml:name>
<maml:description>
<maml:para>Specifies the command or a script block which is invoked after the
task. Custom handlers should check for $Task.Error if it matters.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>If</maml:name>
<maml:description>
<maml:para>Specifies the optional condition to be evaluated. If the condition
evaluates to false then the task is not invoked. The condition is
defined in one of two ways depending on the requirements.

Using standard Boolean notation (parenthesis) the condition is checked
once when the task is defined. A use case for this notation might be
evaluating a script parameter or another sort of global condition.

    Example:
        task Task1 -If ($Param1 -eq ...) {...}
        task Task2 -If ($PSVersionTable.PSVersion.Major -ge 5) {...}

Using script block notation (curly braces) the condition is evaluated
on task invocation. If a task is referenced by several tasks then the
condition is evaluated each time until it gets true and the task is
invoked. The script block notation is normally used for a condition
that may be defined or changed during the build or just expensive.

    Example:
        task SomeTask -If {...} {...}</maml:para>
</maml:description>
<dev:defaultValue>$true</dev:defaultValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Inputs</maml:name>
<maml:description>
<maml:para>Specifies the input items, tells to process the task as incremental,
and requires the parameter Outputs with the optional switch Partial.

Inputs are file items or paths or a script block which gets them.

Outputs are file paths or a script block which gets them.
A script block is invoked with input paths piped to it.

Automatic variables for incremental task actions:

    $Inputs - full input paths, array of strings
    $Outputs - result of the evaluated Outputs

With the switch Partial the task is processed as partial incremental.
There must be one-to-one correspondence between Inputs and Outputs.

Partial task actions often contain &quot;process {}&quot; blocks.
Two more automatic variables are available for them:

    $_ - full path of an input item
    $2 - corresponding output path

See also wiki topics about incremental tasks:
https://github.com/nightroman/Invoke-Build/wiki</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Outputs</maml:name>
<maml:description>
<maml:para>Specifies the output paths of the incremental task, either directly on
task creation or as a script block invoked with the task. It is used
together with Inputs. See Inputs for details.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Partial</maml:name>
<maml:description>
<maml:para>Tells to process the incremental task as partial incremental.
It is used with Inputs and Outputs. See Inputs for details.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Source</maml:name>
<maml:description>
<maml:para>Specifies the task source. It is used by wrapper functions in order to
provide the actual source for location messages and synopsis comments.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Dummy task with no jobs
task Task1

# Alias of another task
task Task2 Task1

# Combination of tasks
task Task3 Task1, Task2

# Simple action task
task Task4 {
    # action
}

# Typical complex task: referenced task(s) and one own action
task Task5 Task1, Task2, {
    # action after referenced tasks
}

# Possible complex task: actions and tasks in any required order
task Task6 {
    # action before Task1
},
Task1, {
    # action after Task1 and before Task2
},
Task2</dev:code>
<dev:remarks>
<maml:para>This example shows various possible combinations of task jobs.</maml:para>
<maml:para></maml:para>
</dev:remarks>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 2 --------------------------</maml:title>
<dev:code># Synopsis: Complex task with parameters as a hashtable.
task TestAndAnalyse @{
    If = !$SkipAnalyse
    Inputs = {
        Get-ChildItem . -Recurse -Include *.ps1, *.psm1
    }
    Outputs = {
        &apos;Analyser.log&apos;
    }
    Jobs = &apos;Test&apos;, {
        Invoke-ScriptAnalyzer . &gt; Analyser.log
    }
}

# Synopsis: Simple task with usual parameters.
task Test -If (!$SkipTest) {
    Invoke-Pester
}</dev:code>
<dev:remarks>
<maml:para>Tasks with complex parameters are often difficult to compose in a readable
way. In such cases use a hashtable in order to specify task parameters in
addition to the task name. Keys and values correspond to parameter names
and values.</maml:para>
</dev:remarks>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Get-BuildError</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Get-BuildSynopsis</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:uri>https://github.com/nightroman/Invoke-Build/wiki</maml:uri>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Get-BuildError</command:name>
<maml:description>
<maml:para>(error) Gets the specified task error.</maml:para>
</maml:description>
<command:verb>Get</command:verb>
<command:noun>BuildError</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;error&apos;. It is used for a task with a safe reference
&apos;?TaskName&apos; in order to get and analyse its potential error.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Get-BuildError</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Task</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Task</maml:name>
<maml:description>
<maml:para>Name of the task which error is requested.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Error</maml:name>
</dev:type>
<maml:description>
<maml:para>An error or null if the task has not failed.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Add-BuildTask</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Assert-Build</command:name>
<maml:description>
<maml:para>(assert) Checks for a condition.</maml:para>
</maml:description>
<command:verb>Assert</command:verb>
<command:noun>Build</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;assert&apos;. This command checks for a condition and
if it is not true throws an error with the default or specified message.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Assert-Build</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Condition</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Message</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Condition</maml:name>
<maml:description>
<maml:para>The condition.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Message</maml:name>
<maml:description>
<maml:para>An optional message describing the assertion condition.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Assert-BuildEquals</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Assert-BuildEquals</command:name>
<maml:description>
<maml:para>(equals) Verifies that two specified objects are equal.</maml:para>
</maml:description>
<command:verb>Assert</command:verb>
<command:noun>BuildEquals</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;equals&apos;. This command verifies that two specified
objects are equal using [Object]::Equals(). If objects are not equal the
command fails with a message showing object values and types.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Assert-BuildEquals</maml:name>
<command:parameter required="false" position="0" >
<maml:name>A</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>B</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>A</maml:name>
<maml:description>
<maml:para>The first object.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>B</maml:name>
<maml:description>
<maml:para>The second object.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Assert-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Get-BuildProperty</command:name>
<maml:description>
<maml:para>(property) Gets the session or environment variable or the default.</maml:para>
</maml:description>
<command:verb>Get</command:verb>
<command:noun>BuildProperty</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;property&apos;. The command returns:

    - session variable value if it is not $null or &apos;&apos;
    - environment variable if it is not $null or &apos;&apos;
    - default value if it is not $null
    - error</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Get-BuildProperty</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Name</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Value</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Name</maml:name>
<maml:description>
<maml:para>Specifies the session or environment variable name.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Value</maml:name>
<maml:description>
<maml:para>Specifies the default value. If it is omitted or null then the variable
must exist with a not empty value. Otherwise an error is thrown.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Object</maml:name>
</dev:type>
<maml:description>
<maml:para>Requested property value.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Inherit an existing value or throw an error

$OutputPath = property OutputPath</dev:code>
</command:example>
<command:example>
<maml:title>-------------------------- EXAMPLE 2 --------------------------</maml:title>
<dev:code># Get an existing value or use the default

$WarningLevel = property WarningLevel 4</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Test-BuildAsset</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Get-BuildSynopsis</command:name>
<maml:description>
<maml:para>Gets the task synopsis.</maml:para>
</maml:description>
<command:verb>Get</command:verb>
<command:noun>BuildSynopsis</command:noun>
</command:details>
<maml:description>
<maml:para>Gets the specified task synopsis if it is available. Task synopses are
defined in preceding comments as # Synopsis: ... In build scripts this
function may be used in Set-BuildHeader for printing task synopses.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Get-BuildSynopsis</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Task</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Hash</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Task</maml:name>
<maml:description>
<maml:para>The task object. During the build, the current task is available as the
automatic variable $Task.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Hash</maml:name>
<maml:description>
<maml:para>A hashtable for caching. Build scripts do not have to specify it, the
internal cache is used by default. It is designed for external tools.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>String</maml:name>
</dev:type>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Headers: print task paths as usual and synopses in addition
Set-BuildHeader {
    param($Path)
    Write-Build Cyan &quot;Task $Path : $(Get-BuildSynopsis $Task)&quot;
}

# Synopsis: This task prints its own synopsis.
task Task1 {
    &apos;My synopsis : &apos; + (Get-BuildSynopsis $Task)
}</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Set-BuildFooter</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Set-BuildHeader</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Invoke-BuildExec</command:name>
<maml:description>
<maml:para>(exec) Invokes an application and checks $LastExitCode.</maml:para>
</maml:description>
<command:verb>Invoke</command:verb>
<command:noun>BuildExec</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;exec&apos;. It invokes the specified script block which
is supposed to call an executable. Then $LastExitCode is checked. If it
does not fit to the specified values (0 by default) an error is thrown.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Invoke-BuildExec</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Command</maml:name>
<command:parameterValue required="true">ScriptBlock</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>ExitCode</maml:name>
<command:parameterValue required="true">Int32[]</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Command</maml:name>
<maml:description>
<maml:para>Command that invokes an executable which exit code is checked. It must
invoke an application directly (.exe) or not (.cmd, .bat), otherwise
$LastExitCode is not set and may contain the code of another command.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>ExitCode</maml:name>
<maml:description>
<maml:para>Valid exit codes (e.g. 0..3 for robocopy).</maml:para>
</maml:description>
<dev:defaultValue>@(0)</dev:defaultValue>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Objects</maml:name>
</dev:type>
<maml:description>
<maml:para>Output of the specified command.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Call robocopy (0..3 are valid exit codes)

exec { robocopy Source Target /mir } (0..3)</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Use-BuildAlias</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Remove-BuildItem</command:name>
<maml:description>
<maml:para>(remove) Removes specified items.</maml:para>
</maml:description>
<command:verb>Remove</command:verb>
<command:noun>BuildItem</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;remove&apos;. This command removes existing items,
ignores missing items, and fails if it cannot remove existing items.

Use the switch Verbose in order to output messages about removing
existing and skipping missing items or patterns specified by Path.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Remove-BuildItem</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Path</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" globbing="true" >
<maml:name>Path</maml:name>
<maml:description>
<maml:para>Specifies the items to be removed. Wildcards are allowed.
The parameter is mostly the same as Path of Remove-Item.
For sanity, paths with only ., *, \, / are not allowed.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Remove some temporary items

remove bin, obj, *.test.log</dev:code>
</command:example>
</command:examples>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Set-BuildFooter</command:name>
<maml:description>
<maml:para>Tells how to write task footers.</maml:para>
</maml:description>
<command:verb>Set</command:verb>
<command:noun>BuildFooter</command:noun>
</command:details>
<maml:description>
<maml:para>This build block is used in order to change the default task footer format.
Use the automatic variable $Task in order to get the current task data.
Use Write-Build in order to write with colors.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Set-BuildFooter</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Script</maml:name>
<command:parameterValue required="true">ScriptBlock</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Script</maml:name>
<maml:description>
<maml:para>The script like {param($Path) ...} which is used in order to write task
footers. The parameter Path includes the parent and current task names.

In order to omit task footers, set an empty block:

    Set-BuildFooter {}</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Use the usual footer format but change the color
Set-BuildFooter {
    param($Path)
    Write-Build DarkGray &quot;Done $Path $($Task.Elapsed)&quot;
}

# Synopsis: Data for footers in addition to $Path and $Task.Elapsed
task Task1 {
    &apos;Task name     : &apos; + $Task.Name
    &apos;Start time    : &apos; + $Task.Started
    &apos;Location path : &apos; + $Task.InvocationInfo.ScriptName
    &apos;Location line : &apos; + $Task.InvocationInfo.ScriptLineNumber
}</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Get-BuildSynopsis</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Set-BuildHeader</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Write-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Set-BuildHeader</command:name>
<maml:description>
<maml:para>Tells how to write task headers.</maml:para>
</maml:description>
<command:verb>Set</command:verb>
<command:noun>BuildHeader</command:noun>
</command:details>
<maml:description>
<maml:para>This build block is used in order to change the default task header format.
Use the automatic variable $Task in order to get the current task data.
Use Write-Build in order to write with colors.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Set-BuildHeader</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Script</maml:name>
<command:parameterValue required="true">ScriptBlock</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Script</maml:name>
<maml:description>
<maml:para>The script like {param($Path) ...} which is used in order to write task
headers. The parameter Path includes the parent and current task names.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Headers: write task paths as usual and synopses in addition
Set-BuildHeader {
    param($Path)
    Write-Build Cyan &quot;Task $Path --- $(Get-BuildSynopsis $Task)&quot;
}

# Synopsis: Data for headers in addition to $Path and Get-BuildSynopsis
task Task1 {
    &apos;Task name     : &apos; + $Task.Name
    &apos;Start time    : &apos; + $Task.Started
    &apos;Location path : &apos; + $Task.InvocationInfo.ScriptName
    &apos;Location line : &apos; + $Task.InvocationInfo.ScriptLineNumber
}</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Get-BuildSynopsis</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Set-BuildFooter</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Write-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Test-BuildAsset</command:name>
<maml:description>
<maml:para>(requires) Checks for required build assets.</maml:para>
</maml:description>
<command:verb>Test</command:verb>
<command:noun>BuildAsset</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;requires&apos;. This command tests the required build
assets. It fails if something is missing or invalid. It is used either
in script code (common assets) or in tasks (individual assets).</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Test-BuildAsset</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Variable</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Environment</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Property</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Variable</maml:name>
<maml:description>
<maml:para>Specifies session variable names and tells to fail if a variable is
missing or its value is null or an empty string.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Environment</maml:name>
<maml:description>
<maml:para>Specifies environment variable names and tells to fail if a variable is
not defined or its value is an empty string.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Property</maml:name>
<maml:description>
<maml:para>Specifies session or environment variable names and tells to fail if a
variable is missing or its value is null or an empty string. It makes
sense to use `property` later with tested names without defaults.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Get-BuildProperty</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Use-BuildAlias</command:name>
<maml:description>
<maml:para>(use) Sets framework or directory tool aliases.</maml:para>
</maml:description>
<command:verb>Use</command:verb>
<command:noun>BuildAlias</command:noun>
</command:details>
<maml:description>
<maml:para>Scripts use its alias &apos;use&apos;. Invoke-Build does not change the system path
in order to make framework tools available by names. This is not suitable
for using mixed framework tools (in different tasks, scripts, parallel
builds). Instead, this function is used for setting tool aliases in the
scope where it is called.

This command may be used in the script scope to make aliases for all tasks.
But it can be called from tasks in order to use more task specific tools.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Use-BuildAlias</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Path</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Name</maml:name>
<command:parameterValue required="true">String[]</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Path</maml:name>
<maml:description>
<maml:para>Specifies the tools directory.

If it is * or it starts with digits followed by a dot then the MSBuild
path is resolved using the package script Resolve-MSBuild.ps1. Build
scripts may invoke it directly by the provided alias Resolve-MSBuild.
The optional suffix x86 tells to use 32-bit MSBuild.

If it is like Framework* then it is assumed to be a path relative to
Microsoft.NET in the Windows directory.

Otherwise it is a full or relative literal path of any directory.

Examples: *, 4.0, Framework\v4.0.30319, .\Tools</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Name</maml:name>
<maml:description>
<maml:para>Specifies the tool names. They become aliases in the current scope.
If it is a build script then the aliases are created for all tasks.
If it is a task then the aliases are available just for this task.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Use .NET 4.0 tools MSBuild, csc, ngen. Then call MSBuild.

use 4.0 MSBuild, csc, ngen
exec { MSBuild Some.csproj /t:Build /p:Configuration=Release }</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Invoke-BuildExec</maml:linkText>
</maml:navigationLink>
<maml:navigationLink>
<maml:linkText>Resolve-MSBuild</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Write-Build</command:name>
<maml:description>
<maml:para>Writes text using colors if they are supported.</maml:para>
</maml:description>
<command:verb>Write</command:verb>
<command:noun>Build</command:noun>
</command:details>
<maml:description>
<maml:para>This function is used in order to output colored text in a console or other
hosts with colors. Unlike Write-Host it is suitable for redirected output,
e.g. to a file. If a host does not have colors then just text is written.

Write-Build is designed for use in tasks and build blocks. Do not use it in
functions and scripts with returned results. Write-Host may be used in some
cases instead, with known limitations.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Write-Build</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Color</maml:name>
<command:parameterValue required="true">ConsoleColor</command:parameterValue>
</command:parameter>
<command:parameter required="true" position="1" >
<maml:name>Text</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Color</maml:name>
<maml:description>
<maml:para>[System.ConsoleColor] value or its string representation.</maml:para>
<maml:para>Values : Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="true" position="1" >
<maml:name>Text</maml:name>
<maml:description>
<maml:para>Text written using colors if they are supported.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>String</maml:name>
</dev:type>
</command:returnValue>
</command:returnValues>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Build-Parallel.ps1</command:name>
<maml:description>
<maml:para>Invokes parallel builds by Invoke-Build</maml:para>
</maml:description>
</command:details>
<maml:description>
<maml:para>This script invokes build scripts simultaneously using Invoke-Build.ps1
which has to be in the same directory. Number of simultaneous builds is
limited by the number of processors by default.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Build-Parallel.ps1</maml:name>
<command:parameter required="false" position="0" >
<maml:name>Build</maml:name>
<command:parameterValue required="true">Hashtable[]</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>MaximumBuilds</maml:name>
<command:parameterValue required="true">Int32</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Result</maml:name>
<command:parameterValue required="true">Object</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Timeout</maml:name>
<command:parameterValue required="true">Int32</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>FailHard</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="false" position="0" >
<maml:name>Build</maml:name>
<maml:description>
<maml:para>Build parameters defined as hashtables with these keys/data:

    Task, File, ... - Invoke-Build.ps1 and script parameters
    Log - Tells to write build output to the specified file

Any number of builds is allowed, including 0 and 1. The maximum number
of parallel builds is the number of processors by default. It can be
changed by the parameter MaximumBuilds.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>FailHard</maml:name>
<maml:description>
<maml:para>Tells to abort all builds if any build fails.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>MaximumBuilds</maml:name>
<maml:description>
<maml:para>Maximum number of builds invoked at the same time.</maml:para>
</maml:description>
<dev:defaultValue>Number of processors.</dev:defaultValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Result</maml:name>
<maml:description>
<maml:para>Tells to output build results using a variable. It is either a name of
variable to be created for results or any object with the property
Value to be assigned ([ref], [hashtable]).

Result properties:

    Tasks - tasks (*)
    Errors - errors (*)
    Warnings - warnings (*)
    Started - start time
    Elapsed - build duration

(*) see: help Invoke-Build -Parameter Result</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Timeout</maml:name>
<maml:description>
<maml:para>Maximum overall build time in milliseconds.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Text</maml:name>
</dev:type>
<maml:description>
<maml:para>Output of invoked builds and other log messages.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code>Build-Parallel @(
    @{File=&apos;Project1.build.ps1&apos;}
    @{File=&apos;Project2.build.ps1&apos;; Task=&apos;MakeHelp&apos;}
    @{File=&apos;Project2.build.ps1&apos;; Task=&apos;Build&apos;, &apos;Test&apos;}
    @{File=&apos;Project3.build.ps1&apos;; Log=&apos;C:\TEMP\Project3.log&apos;}
    @{File=&apos;Project4.build.ps1&apos;; Configuration=&apos;Release&apos;}
)</dev:code>
<dev:remarks>
<maml:para>Five parallel builds are invoked with various combinations of parameters.
Note that it is fine to invoke the same build script more than once if
build flows specified by different tasks do not conflict.</maml:para>
</dev:remarks>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Invoke-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
<command:details>
<command:name>Build-Checkpoint.ps1</command:name>
<maml:description>
<maml:para>Invokes persistent builds with checkpoints.</maml:para>
</maml:description>
</command:details>
<maml:description>
<maml:para>This command invokes the build specified by the hashtable Build so that it
writes checkpoints to the file specified by Checkpoint. If the build fails
then it may be resumed later, use the switch Resume in addition to the
original Checkpoint parameter. The build is resumed at the failed task.

Not every build may be persistent, right away or at all:

    - Think carefully of what the persistent build state is.
    - Some data are not suitable for persistence in clixml files.
    - Changes in stopped build scripts may cause incorrect resuming.
    - Checkpoint files must not be used with different engine versions.

CUSTOM EXPORT AND IMPORT

By default, the command saves and restores build tasks, script path, and
all parameters declared by the build script, not just specified by Build.
Tip: consider to declare some script variables as artificial parameters
in order to make them persistent.

If this is not enough for saving and restoring the build state then use
custom export and import blocks. The export block is called on writing
checkpoints, i.e. on each task. The import block is called on resuming
once, before the task to be resumed.

The export block is defined as

    Set-BuildData Checkpoint.Export {
        $script:var1
        $script:var2
    }

The import block is defined as

    Set-BuildData Checkpoint.Import {
        param($data)
        $var1, $var2 = $data
    }

Note that the import block is called in the script scope. In the example,
variables $var1, $var2 are the script variables, you may but do not have
to use the prefix `$script:`. The parameter $data is the data written by
Checkpoint.Export, exported to clixml and then imported from clixml.</maml:para>
</maml:description>
<command:syntax>
<command:syntaxItem>
<maml:name>Build-Checkpoint.ps1</maml:name>
<command:parameter required="true" position="0" >
<maml:name>Checkpoint</maml:name>
<command:parameterValue required="true">String</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Build</maml:name>
<command:parameterValue required="true">Hashtable</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Preserve</maml:name>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Resume</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
<command:parameters>
<command:parameter required="true" position="0" >
<maml:name>Checkpoint</maml:name>
<maml:description>
<maml:para>Specifies the checkpoint file (clixml). The checkpoint file is removed
after successful builds unless the switch Preserve is specified.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="1" >
<maml:name>Build</maml:name>
<maml:description>
<maml:para>Specifies the build and script parameters. WhatIf is not supported.
On Resume tasks, script path, and script parameters are ignored.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Preserve</maml:name>
<maml:description>
<maml:para>Tells to preserve the checkpoint file on successful builds.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named" >
<maml:name>Resume</maml:name>
<maml:description>
<maml:para>Tells to resume the build from the existing checkpoint file.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:returnValues>
<command:returnValue>
<dev:type>
<maml:name>Text</maml:name>
</dev:type>
<maml:description>
<maml:para>Output of the invoked build.</maml:para>
</maml:description>
</command:returnValue>
</command:returnValues>
<command:examples>
<command:example>
<maml:title>-------------------------- EXAMPLE 1 --------------------------</maml:title>
<dev:code># Invoke a persistent sequence of steps defined as tasks.
Build-Checkpoint temp.clixml @{Task = &apos;*&apos;; File = &apos;Steps.build.ps1&apos;}

# Given the above failed, resume at the failed step.
Build-Checkpoint temp.clixml -Resume</dev:code>
</command:example>
</command:examples>
<maml:relatedLinks>
<maml:navigationLink>
<maml:linkText>Invoke-Build</maml:linkText>
</maml:navigationLink>
</maml:relatedLinks>
</command:command>
</helpItems>
tools\InvokeBuild\InvokeBuild.psd1
@{
	ModuleVersion = '5.5.5'
	ModuleToProcess = 'InvokeBuild.psm1'
	GUID = 'a0319025-5f1f-47f0-ae8d-9c7e151a5aae'
	Author = 'Roman Kuzmin'
	CompanyName = 'Roman Kuzmin'
	Copyright = '(c) Roman Kuzmin'
	Description = 'Build and test automation in PowerShell'
	PowerShellVersion = '2.0'
	AliasesToExport = 'Invoke-Build', 'Build-Checkpoint', 'Build-Parallel'
	PrivateData = @{
		PSData = @{
			Tags = 'Build', 'Test', 'Automation'
			ProjectUri = 'https://github.com/nightroman/Invoke-Build'
			LicenseUri = 'http://www.apache.org/licenses/LICENSE-2.0'
			IconUri = 'https://raw.githubusercontent.com/nightroman/Invoke-Build/master/ib.png'
			ReleaseNotes = 'https://github.com/nightroman/Invoke-Build/blob/master/Release-Notes.md'
		}
	}
}
tools\InvokeBuild\InvokeBuild.psm1

Set-Alias -Name Build-Checkpoint -Value (Join-Path $PSScriptRoot Build-Checkpoint.ps1)
Set-Alias -Name Build-Parallel -Value (Join-Path $PSScriptRoot Build-Parallel.ps1)
Set-Alias -Name Invoke-Build -Value (Join-Path $PSScriptRoot Invoke-Build.ps1)
Export-ModuleMember -Alias Build-Checkpoint, Build-Parallel, Invoke-Build
tools\InvokeBuild\LICENSE.txt
Invoke-Build - Build Automation in PowerShell
Copyright (c) 2011-2019 Roman Kuzmin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
tools\InvokeBuild\PSGetModuleInfo.xml
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>Microsoft.PowerShell.Commands.PSRepositoryItemInfo</T>
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="Name">InvokeBuild</S>
      <S N="Version">5.5.5</S>
      <S N="Type">Module</S>
      <S N="Description">Build and test automation in PowerShell</S>
      <S N="Author">Roman Kuzmin</S>
      <S N="CompanyName">nightroman</S>
      <S N="Copyright">(c) Roman Kuzmin</S>
      <DT N="PublishedDate">2019-10-16T18:26:37+00:00</DT>
      <Nil N="InstalledDate" />
      <Nil N="UpdatedDate" />
      <URI N="LicenseUri">http://www.apache.org/licenses/LICENSE-2.0</URI>
      <URI N="ProjectUri">https://github.com/nightroman/Invoke-Build</URI>
      <URI N="IconUri">https://raw.githubusercontent.com/nightroman/Invoke-Build/master/ib.png</URI>
      <Obj N="Tags" RefId="1">
        <TN RefId="1">
          <T>System.Object[]</T>
          <T>System.Array</T>
          <T>System.Object</T>
        </TN>
        <LST>
          <S>Build</S>
          <S>Test</S>
          <S>Automation</S>
          <S>PSModule</S>
        </LST>
      </Obj>
      <Obj N="Includes" RefId="2">
        <TN RefId="2">
          <T>System.Collections.Hashtable</T>
          <T>System.Object</T>
        </TN>
        <DCT>
          <En>
            <S N="Key">Function</S>
            <Obj N="Value" RefId="3">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">RoleCapability</S>
            <Obj N="Value" RefId="4">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Command</S>
            <Obj N="Value" RefId="5">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">DscResource</S>
            <Obj N="Value" RefId="6">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Workflow</S>
            <Obj N="Value" RefId="7">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Cmdlet</S>
            <Obj N="Value" RefId="8">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
        </DCT>
      </Obj>
      <Nil N="PowerShellGetFormatVersion" />
      <S N="ReleaseNotes">https://github.com/nightroman/Invoke-Build/blob/master/Release-Notes.md</S>
      <Obj N="Dependencies" RefId="9">
        <TNRef RefId="1" />
        <LST />
      </Obj>
      <S N="RepositorySourceLocation">https://www.powershellgallery.com/api/v2</S>
      <S N="Repository">PSGallery</S>
      <S N="PackageManagementProvider">NuGet</S>
      <Obj N="AdditionalMetadata" RefId="10">
        <TN RefId="3">
          <T>System.Management.Automation.PSCustomObject</T>
          <T>System.Object</T>
        </TN>
        <MS>
          <S N="copyright">(c) Roman Kuzmin</S>
          <S N="description">Build and test automation in PowerShell</S>
          <S N="requireLicenseAcceptance">False</S>
          <S N="releaseNotes">https://github.com/nightroman/Invoke-Build/blob/master/Release-Notes.md</S>
          <S N="isLatestVersion">True</S>
          <S N="isAbsoluteLatestVersion">True</S>
          <S N="versionDownloadCount">94</S>
          <S N="downloadCount">218664</S>
          <S N="packageSize">39315</S>
          <S N="published">10/16/2019 6:26:37 PM +00:00</S>
          <S N="created">10/16/2019 6:26:37 PM +00:00</S>
          <S N="lastUpdated">10/17/2019 12:03:02 AM +00:00</S>
          <S N="tags">Build Test Automation PSModule</S>
          <S N="developmentDependency">False</S>
          <S N="updated">2019-10-17T00:03:02Z</S>
          <S N="NormalizedVersion">5.5.5</S>
          <S N="Authors">Roman Kuzmin</S>
          <S N="IsPrerelease">false</S>
          <S N="ItemType">Module</S>
          <S N="FileList">InvokeBuild.nuspec|about_InvokeBuild.help.txt|Build-Checkpoint.ps1|Build-Parallel.ps1|ib.cmd|Invoke-Build.ps1|InvokeBuild-Help.xml|InvokeBuild.psd1|InvokeBuild.psm1|LICENSE.txt|README.htm|Release-Notes.htm|Resolve-MSBuild.ps1|Show-TaskHelp.ps1</S>
          <S N="GUID">a0319025-5f1f-47f0-ae8d-9c7e151a5aae</S>
          <S N="PowerShellVersion">2.0</S>
          <S N="CompanyName">Roman Kuzmin</S>
        </MS>
      </Obj>
      <S N="InstalledLocation">C:\Users\appveyor\AppData\Local\Temp\1\c7ba21bc-361c-4757-a69d-4594ec672ec6\InvokeBuild\5.5.5</S>
    </MS>
  </Obj>
</Objs>
tools\InvokeBuild\README.htm
 
tools\InvokeBuild\Release-Notes.htm
 
tools\InvokeBuild\Resolve-MSBuild.ps1
<#PSScriptInfo
.VERSION 1.5.0
.AUTHOR Roman Kuzmin
.COPYRIGHT (c) Roman Kuzmin
.TAGS Invoke-Build, MSBuild
.GUID 53c01926-4fc5-4cbd-aa46-32e415b2373b
.LICENSEURI http://www.apache.org/licenses/LICENSE-2.0
.PROJECTURI https://github.com/nightroman/Invoke-Build
#>

<#
.Synopsis
	Finds the specified or latest MSBuild.

.Description
	The script finds the path to the specified or latest version of MSBuild.
	It is designed for MSBuild 16.0, 15.0, 14.0, 12.0, 4.0, 3.5, 2.0.

	For MSBuild 15+ the command uses the module VSSetup, see PSGallery.
	If VSSetup is not installed then the default locations are used.
	VSSetup is required for not default installations.

	MSBuild 15+ resolution: the latest major version (or absolute if -Latest),
	then Enterprise, Professional, Community, BuildTools, other products.

	For MSBuild 2.0-14.0 the information is taken from the registry.

.Parameter Version
		Specifies the required MSBuild major version. If it is omitted, empty,
		or *, then the command finds and returns the latest installed version
		path. The optional suffix x86 tells to use 32-bit MSBuild.
		Known versions: 16.0, 15.0, 14.0, 12.0, 4.0, 3.5, 2.0
.Parameter MinimumVersion
		Specifies the required minimum MSBuild version. If the resolved MSBuild
		version is less than the minimum version then an error is thrown.
.Parameter Latest
		Tells to select the latest minor version if there are 2+ products with
		the same major version. Note that major versions have higher precedence
		than products regardless of -Latest.

.Outputs
	The full path to MSBuild.exe

.Example
	Resolve-MSBuild 16.0x86
	Gets the location of 32-bit MSBuild of Visual Studio 2019.

.Example
	Resolve-MSBuild x86 15.0 -Latest
	Gets the location of the latest 32-bit MSBuild, and asserts that its
	version is at least 15.0.

.Example
	Resolve-MSBuild -MinimumVersion 16.3.1 -Latest
	Gets the location of the latest MSBuild, and asserts that its version is at
	least 16.3.1.

.Link
	https://www.powershellgallery.com/packages/VSSetup
#>

[OutputType([string])]
[CmdletBinding()]
param(
	[string]$Version,
	[Version]$MinimumVersion,
	[switch]$Latest
)

function Get-MSBuild15Path {
	[CmdletBinding()] param(
		[string]$Version,
		[string]$Bitness
	)

	if ([System.IntPtr]::Size -eq 4 -or $Bitness -eq 'x86') {
		"MSBuild\$Version\Bin\MSBuild.exe"
	}
	else {
		"MSBuild\$Version\Bin\amd64\MSBuild.exe"
	}
}

function Get-MSBuild15VSSetup {
	[CmdletBinding()] param(
		[string]$Version,
		[string]$Bitness,
		[switch]$Latest,
		[switch]$Prerelease
	)

	if (!(Get-Module VSSetup)) {
		if (!(Get-Module VSSetup -ListAvailable)) {return}
		Import-Module VSSetup
	}

	$items = @(
		$v = switch($Version) {
			'16.0' {'[16.0,17.0)'}
			'15.0' {'[15.0,16.0)'}
			default {'[15.0,)'}
		}
		Get-VSSetupInstance -Prerelease:$Prerelease |
		Select-VSSetupInstance -Version $v -Require Microsoft.Component.MSBuild -Product *
	)
	if (!$items) {
		if (!$Prerelease) {
			Get-MSBuild15VSSetup $Version $Bitness -Latest:$Latest -Prerelease
		}
		return
	}

	if ($items.Count -ge 2) {
		$byVersion = if ($Latest) {{$_.InstallationVersion}} else {{$_.InstallationVersion.Major}}
		$byProduct = {
			switch ($_.Product.Id) {
				Microsoft.VisualStudio.Product.Enterprise {4}
				Microsoft.VisualStudio.Product.Professional {3}
				Microsoft.VisualStudio.Product.Community {2}
				Microsoft.VisualStudio.Product.BuildTools {1}
				default {0}
			}
		}
		$items = $items | Sort-Object $byVersion, $byProduct
	}

	$item = $items[-1]
	if ($item.InstallationVersion.Major -eq 15) {
		$Version = '15.0'
	}
	else {
		$Version = 'Current'
	}
	Join-Path $item.InstallationPath (Get-MSBuild15Path $Version $Bitness)
}

function Get-MSBuild15Guess {
	[CmdletBinding()] param(
		[string]$Version,
		[string]$Bitness,
		[switch]$Latest,
		[switch]$Prerelease
	)

	if (!($root = ${env:ProgramFiles(x86)})) {$root = $env:ProgramFiles}

	$folders = $(
		if ($Prerelease) {'Preview'}
		elseif ($Version -eq '*') {'2019', '2017'}
		elseif ($Version -eq '16.0') {'2019'}
		else {'2017'}
	)
	$items = @(
		foreach($folder in $folders) {
			Get-Item -ErrorAction 0 @(
				"$root\Microsoft Visual Studio\$folder\*\$(Get-MSBuild15Path Current $Bitness)"
				"$root\Microsoft Visual Studio\$folder\*\$(Get-MSBuild15Path $Version $Bitness)"
			)
		}
	)
	if (!$items) {
		if (!$Prerelease) {
			Get-MSBuild15Guess $Version $Bitness -Latest:$Latest -Prerelease
		}
		return
	}

	if ($items.Count -ge 2) {
		$byVersion = if ($Latest) {{[Version]$_.VersionInfo.FileVersion}} else {{([Version]$_.VersionInfo.FileVersion).Major}}
		$byProduct = {
			switch -Wildcard ($_.FullName) {
				*\Enterprise\* {4}
				*\Professional\* {3}
				*\Community\* {2}
				*\BuildTools\* {1}
				default {0}
			}
		}
		$items = $items | Sort-Object $byVersion, $byProduct
	}

	$items[-1].FullName
}

function Get-MSBuild15 {
	[CmdletBinding()] param(
		[string]$Version,
		[string]$Bitness,
		[switch]$Latest
	)

	if ($path = Get-MSBuild15VSSetup $Version $Bitness -Latest:$Latest) {
		$path
	}
	else {
		Get-MSBuild15Guess $Version $Bitness -Latest:$Latest
	}
}

function Get-MSBuildOldVersion {
	[CmdletBinding()] param(
		[string]$Version,
		[string]$Bitness
	)

	if ([System.IntPtr]::Size -eq 8 -and $Bitness -eq 'x86') {
		$key = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\MSBuild\ToolsVersions\$Version"
	}
	else {
		$key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$Version"
	}
	$rp = [Microsoft.Win32.Registry]::GetValue($key, 'MSBuildToolsPath', '')
	if ($rp) {
		Join-Path $rp MSBuild.exe
	}
}

function Get-MSBuildOldLatest {
	[CmdletBinding()] param(
		[string]$Bitness
	)

	$rp = @(Get-ChildItem HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions | Sort-Object {[Version]$_.PSChildName})
	if ($rp) {
		Get-MSBuildOldVersion $rp[-1].PSChildName $Bitness
	}
}

function Get-MSBuildAny {
	[CmdletBinding()] param(
		[string]$Bitness,
		[switch]$Latest
	)

	if ($path = Get-MSBuild15 * $Bitness -Latest:$Latest) {
		$path
	}
	else {
		Get-MSBuildOldLatest $Bitness
	}
}

$ErrorActionPreference = 1
try {
	if ($Version -match '^(.*?)x86\s*$') {
		$Version = $matches[1]
		$Bitness = 'x86'
	}
	else {
		$Bitness = ''
	}
	$Version = $Version.Trim()

	$v16 = [Version]'16.0'
	$v15 = [Version]'15.0'
	$vMax = [Version]'9999.0'
	if (!$Version) {$Version = '*'}
	$vRequired = if ($Version -eq '*') {$vMax} else {[Version]$Version}

	$path = ''
	if ($vRequired -eq $v16 -or $vRequired -eq $v15) {
		$path = Get-MSBuild15 $Version $Bitness -Latest:$Latest
	}
	elseif ($vRequired -lt $v15) {
		$path = Get-MSBuildOldVersion $Version $Bitness
	}
	elseif ($vRequired -eq $vMax) {
		$path = Get-MSBuildAny $Bitness -Latest:$Latest
	}

	if (!$path) {
		throw 'The specified version is not found.'
	}

	if ($MinimumVersion) {
		$vResolved = [Version](& $path -version -nologo)
		if ($vResolved -lt $MinimumVersion) {
			throw "MSBuild resolved version $vResolved is less than required minimum $MinimumVersion."
		}
	}

	$path
}
catch {
	Write-Error "Cannot resolve MSBuild $Version : $_"
}
tools\InvokeBuild\Show-TaskHelp.ps1

<#
.Synopsis
	Shows Invoke-Build task help information.
	Copyright (c) Roman Kuzmin

.Description
	The command shows the specified tasks help information as task names with
	synopses, jobs with their locations, script parameters and environment. By
	default, it analyses the code in order to extract variables in addition to
	optionally documented in comments.

	Synopsis is defined in task comments as # Synopsis: ...
	Parameters are defined as # Parameters: name1, name2, ...
	Environment variables are defined as # Environment: name1, name2, ...

	Parameters names match build parameters and separated by spaces or commas.
	Parameter descriptions are taken from the build script comment based help.

	Help info members (for custom formatters):

		Task: [object[]] Tasks to do.
			Name: [string] Task name.
			Synopsis: [string] Task synopsis, may be null.
		Jobs: [object[]] Jobs to do.
			Name: [string] Task name.
			Location: [string] Task location as "<file>:<line>".
		Parameters: [object[]] Tasks parameters, may be empty.
			Name: [string] Parameter name.
			Type: [string] Parameter type.
			Description: [string] Parameter help, may be null or empty.
		Environment: [string[]] Tasks environment variables, may be empty.

.Parameter Task
		Build task name(s). The default is the usual default task.
.Parameter File
		Build script path. The default is the usual default script.
.Parameter NoCode
		Tells to skip code analysis for parameters and environment.
		It is used as true for PowerShell v2.
.Parameter Format
		Specifies the custom task help formatter.

.Link
	https://github.com/nightroman/Invoke-Build
#>

param(
	[Parameter(Position=0)][string[]]$Task,
	[Parameter(Position=1)]$File,
	$Format = 'Format-TaskHelp',
	[switch]$NoCode
)

trap {$PSCmdlet.ThrowTerminatingError($_)}
$ErrorActionPreference = 1

if ([System.IO.Path]::GetFileName($MyInvocation.ScriptName) -eq 'Invoke-Build.ps1') {
	$all = ${*}.All
	Remove-Variable Task
}
else {
	$BuildTask = $Task
	$BuildFile = $File
	. Invoke-Build

	### resolve file
	if ($BuildFile) {
		$BuildFile = *Path $BuildFile
		if (![System.IO.File]::Exists($BuildFile)) {*Fin "Missing file '$BuildFile'." 5}
	}
	else {
		$BuildFile = Get-BuildFile (*Path)
		if (!$BuildFile) {*Fin 'Missing default script.' 5}
	}

	### resolve task
	$all = Invoke-Build ?? $BuildFile
	if (!$BuildTask -or '.' -eq $BuildTask) {
		$BuildTask = if ($all['.']) {'.'} else {$all.Item(0).Name}
	}
}

### get script parameter help
$Help = @(&{
	Set-StrictMode -Off
	if ($r = Get-Help $BuildFile) {if ($r = $r.parameters) {if ($r = $r.parameter) {$r}}}
})

### get script parameters
$CommonParameters = 'Verbose', 'Debug', 'ErrorAction', 'WarningAction', 'ErrorVariable', 'WarningVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable', 'InformationAction', 'InformationVariable'
$Parameters = (Get-Command $BuildFile).Parameters
foreach($name in @($Parameters.Keys)) {
	if ($CommonParameters -contains $name) {
		$null = $Parameters.Remove($name)
	}
}

# amend options
$NoCode = $NoCode -or $PSVersionTable.PSVersion.Major -le 2

# globals
$Hash = @{}
$BuildJobs = @()
$MapParameter = @{}
$MapEnvironment = @{}
$VariableExpressionAst = {$args[0] -is [System.Management.Automation.Language.VariableExpressionAst]}

# collect jobs to do in $BuildJobs
function Add-TaskJob($Jobs, $Task) {
	foreach($job in $Jobs) {
		$job, $null = *Job $job
		if ($job -is [string]) {
			$task2 = $all[$job]
			Add-TaskJob $task2.Jobs $task2
		}
		else {
			if ($BuildJobs -notcontains $Task.Name) {
				$script:BuildJobs += $Task.Name
			}
		}
	}

	if ($Task -and $Task.If -is [scriptblock]) {
		if ($BuildJobs -notcontains $Task.Name) {
			$script:BuildJobs += $Task.Name
		}
	}
}

# get parameters and environment from comments
function Get-TaskComment($Task) {
	$f = ($I = $Task.InvocationInfo).ScriptName
	if (!($d = $Hash[$f])) {
		$Hash[$f] = $d = @{T = Get-Content -LiteralPath $f; C = @{}}
		foreach($_ in [System.Management.Automation.PSParser]::Tokenize($d.T, [ref]$null)) {
			if ($_.Type -eq 15) {$d.C[$_.EndLine] = $_.Content}
		}
	}
	$r = @{Parameters = @(); Environment = @()}
	for($n = $I.ScriptLineNumber; --$n -ge 1) {
		if ($c = $d.C[$n]) {
			if ($c -match '(?m)^\s*#*\s*Parameters\s*:(.*)') {$r.Parameters = $Matches[1].Trim() -split '[\s,]+'}
			elseif ($c -match '(?m)^\s*#*\s*Environment\s*:(.*)') {$r.Environment = $Matches[1].Trim() -split '[\s,]+'}
		}
		elseif ($d.T[$n - 1].Trim()) {
			break
		}
	}
	$r
}

function Add-VariablePath($Path) {
	$index = $Path.IndexOf(':')
	if ($index -ge 0) {
		$prefix = $Path.Substring(0, $index)
		$name = $Path.Substring($index + 1)
	}
	else {
		$prefix = ''
		$name = $Path
	}
	if (!$prefix -or $prefix -eq 'script') {
		if ($Parameters.ContainsKey($name)) {
			$MapParameter[$name] = 1
		}
	}
	elseif ($prefix -eq 'env') {
		$MapEnvironment[$name] = 1
	}
}

function Add-BlockVariable($Block) {
	$variables = $job.Ast.FindAll($VariableExpressionAst, $true)
	foreach($variable in $variables) {
		$parent = $variable.Parent
		if ($parent -isnot [System.Management.Automation.Language.AssignmentStatementAst] -or $parent.Left -ne $variable) {
			Add-VariablePath $variable.VariablePath.UserPath
		}
	}
}

function Add-TaskVariable($Jobs) {
	foreach($job in $Jobs) {
		$task = $all[$job]
		$info = Get-TaskComment $task

		foreach($name in $info.Environment) {
			$MapEnvironment[$name] = 1
		}
		foreach($name in $info.Parameters) {
			if ($Parameters.ContainsKey($name)) {
				$MapParameter[$name] = 1
			}
			else {
				Write-Warning "Task '$($task.Name)': unknown parameter '$name'."
			}
		}

		if (!$NoCode) {
			$job = $Task.If
			if ($job -is [scriptblock]) {
				Add-BlockVariable $job
			}
			foreach($job in $task.Jobs) {
				if ($job -is [scriptblock]) {
					Add-BlockVariable $job
				}
			}
		}
	}
}

function Format-TaskHelp($TaskHelp) {
	Write-Build White Task:
	foreach($r in $TaskHelp.Task) {
		if ($r.Synopsis) {
			Write-Build Gray ('    {0} - {1}' -f $r.Name, $r.Synopsis)
		}
		else {
			Write-Build Gray ('    {0}' -f $r.Name)
		}
	}

	Write-Build White Jobs:
	foreach($r in $TaskHelp.Jobs) {
		Write-Build Gray ('    {0} - {1}' -f $r.Name, $r.Location)
	}

	if ($TaskHelp.Parameters) {
		Write-Build White Parameters:
		foreach($param in $TaskHelp.Parameters) {
			Write-Build Gray ('    [{0}] {1}' -f $param.Type, $param.Name)
			if ($param.Description) {
				Write-Build Gray ('        {0}' -f $param.Description)
			}
		}
	}

	if ($TaskHelp.Environment) {
		Write-Build White Environment:
		Write-Build Gray ('    {0}' -f ($TaskHelp.Environment -join ', '))
	}
}

### .Task
$TaskHelp = 1 | Select-Object Task, Jobs, Synopsis, Location, Parameters, Environment
$TaskHelp.Task = @(
	foreach($job in $BuildTask) {
		$job, $null = *Job $job
		$task = $all[$job]
		if (!$task) {*Fin "Missing task '$job' in '$BuildFile'." 5}
		$r = 1 | Select-Object Name, Synopsis
		$r.Name = $task.Name
		$r.Synopsis = Get-BuildSynopsis $task $Hash
		$r
	}
)

### .Jobs
Add-TaskJob $BuildTask
$TaskHelp.Jobs = @(
	foreach($name in $BuildJobs) {
		$task = $all[$name]
		$r = 1 | Select-Object Name, Location
		$r.Name = $task.Name
		$r.Location = '{0}:{1}' -f $task.InvocationInfo.ScriptName, $task.InvocationInfo.ScriptLineNumber
		$r
	}
)

### .Parameters and .Environment
Add-TaskVariable $BuildJobs
$TaskHelp.Environment = @($MapEnvironment.Keys | Sort-Object)

# make parameter objects with help
$TaskHelp.Parameters = @()
foreach($name in $MapParameter.Keys) {
	$param = $Parameters[$name]
	$r = 1 | Select-Object Name, Type, Description
	$r.Name = $name

	$type = $param.ParameterType.Name
	if ($type -eq 'SwitchParameter') {
		$r.Type = 'switch'
	}
	else {
		$r.Type = $type
	}

	$r.Description = foreach($_ in $Help) {
		if ($_.name -eq $name -and $_.PSObject.Properties['description']) {
			($_.description | Out-String).Trim()
			break
		}
	}
	$TaskHelp.Parameters += $r
}
$TaskHelp.Parameters = @($TaskHelp.Parameters | Sort-Object {$_.Type -eq 'switch'}, Name)

# finish
& $Format $TaskHelp
tools\LICENSE.txt
From: https://raw.githubusercontent.com/nightroman/Invoke-Build/master/LICENSE.txt

LICENSE

Invoke-Build - Build Automation in PowerShell
Copyright (c) 2011-2018 Roman Kuzmin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
tools\VERIFICATION.txt
VERIFICATION
Verification is intended to assist the Chocolatey moderators and community in verifying that this package's contents are trustworthy.

To verify the files using the project source:

1. Please go to the project source location (https://github.com/PowerShell/InvokeBuild) and download the source files;
2. Build the source to create the binary files to verify;
3. Use Get-FileHash -Path <FILE TO VERIFY> to get the file hash value from both the built file (from step 1 above) and the file from the package and compare them;

Alternatively you can download the module from the PowerShell Gallery ...

    Save-Module -Name InvokeBuild -Path <PATH TO DOWNLOAD TO>

... and compare the files from the package against those in the installed module. Again use Get-FileHash -Path <FILE TO VERIFY> to retrieve those hash values.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Version Downloads Last Updated Status
InvokeBuild (PowerShell Module) 5.5.4 18 Wednesday, October 16, 2019 Approved
InvokeBuild (PowerShell Module) 5.5.3 55 Thursday, August 29, 2019 Approved
InvokeBuild (PowerShell Module) 5.5.2 85 Wednesday, June 12, 2019 Approved
InvokeBuild (PowerShell Module) 5.5.1 60 Tuesday, April 9, 2019 Approved
InvokeBuild (PowerShell Module) 5.5.0 48 Wednesday, April 3, 2019 Approved
InvokeBuild (PowerShell Module) 5.4.6 48 Wednesday, March 27, 2019 Approved
InvokeBuild (PowerShell Module) 5.4.5 49 Tuesday, March 5, 2019 Approved
InvokeBuild (PowerShell Module) 5.4.4 53 Monday, February 25, 2019 Approved
InvokeBuild (PowerShell Module) 5.4.3 63 Thursday, February 14, 2019 Approved

This package has no dependencies.

Discussion for the InvokeBuild (PowerShell Module) Package

Ground Rules:

  • This discussion is only about InvokeBuild (PowerShell Module) and the InvokeBuild (PowerShell Module) package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or InvokeBuild (PowerShell Module), or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus