Created
January 26, 2017 06:35
-
-
Save Jaykul/e0c08be051bed56d62474ae12b9b1b8a to your computer and use it in GitHub Desktop.
Invoke-Step with dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DependsOn : System.Attribute { | |
[string[]]$Name | |
DependsOn([string[]]$name) { | |
$this.Name = $name | |
} | |
} | |
function Invoke-Step { | |
<# | |
.Synopsis | |
Runs a command, taking care to run it's dependencies first | |
.Description | |
Invoke-Step supports the [DependsOn("...")] attribute to allow you to write tasks or build steps that take dependencies on other tasks completing first. | |
When you invoke a step, dependencies are run first, recursively. The algorithm for this is depth-first and *very* naive. Don't build cycles! | |
.Example | |
function init { | |
param() | |
Write-Information "INITIALIZING build variables" | |
} | |
function update { | |
[DependsOn("init")]param() | |
Write-Information "UPDATING dependencies" | |
} | |
function build { | |
[DependsOn(("update","init"))]param() | |
Write-Information "BUILDING: $ModuleName from $Path" | |
} | |
Invoke-Step build -InformationAction continue | |
Defines three steps with dependencies, and invokes the "build" step. | |
Results in this output: | |
Invoking Step: init | |
Invoking Step: update | |
Invoking Step: build | |
#> | |
[CmdletBinding()] | |
param( | |
[string]$Step, | |
[string]$Script | |
) | |
begin { | |
# Source Build Scripts, if any | |
if($Script) { . $Script } | |
# Don't reset on nested calls | |
if(((Get-PSCallStack).Command -eq "Invoke-Step").Count -eq 1) { | |
$script:InvokedSteps = @() | |
$script:DependencySteps = @() | |
} | |
} | |
end { | |
$StepCommand = Get-Command $Step | |
$Dependencies = $StepCommand.ScriptBlock.Attributes.Where{ $_.TypeId.Name -eq "DependsOn" }.Name | |
foreach($dependency in $Dependencies) { | |
if($script:InvokedSteps -notcontains $dependency) { | |
Invoke-Step -Step $dependency | |
} | |
} | |
Write-Information -MessageData "Invoking Step: $Step" | |
& $StepCommand | |
$script:InvokedSteps += $Step | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment