Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created January 26, 2017 06:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jaykul/e0c08be051bed56d62474ae12b9b1b8a to your computer and use it in GitHub Desktop.
Save Jaykul/e0c08be051bed56d62474ae12b9b1b8a to your computer and use it in GitHub Desktop.
Invoke-Step with dependencies
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