Skip to content

Instantly share code, notes, and snippets.

@JCapriotti
Last active August 31, 2017 13:37
Show Gist options
  • Save JCapriotti/45639e06ba777ee974b1 to your computer and use it in GitHub Desktop.
Save JCapriotti/45639e06ba777ee974b1 to your computer and use it in GitHub Desktop.
Octopus Step Testing

The example step includes one required parameter and one that is not required and has a default.

Call with No Parameters

PS C:\temp> Invoke-OctopusStep @{} .\step.ps1
Missing parameter value RequiredParameter
At C:\temp\step.ps1:12 char:13
+             throw "Missing parameter value $Name"
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (Missing paramet...quiredParameter:String) [], RuntimeException
+ FullyQualifiedErrorId : Missing parameter value RequiredParameter

Call with required parameter but no default

PS C:\temp> Invoke-OctopusStep @{RequiredParameter="apple"} .\step.ps1
Script Title...
RequiredParameter: apple
DefaultedParameter: default value

Call with both the required and defaulted parameter

PS C:\temp> Invoke-OctopusStep @{RequiredParameter="apple"; DefaultedParameter="orange"} .\step.ps1
Script Title...
RequiredParameter: apple
DefaultedParameter: orange
$ErrorActionPreference = "Stop"
function Get-Parameter($Name, $Default, [switch]$Required) {
$result = $null
if ($OctopusParameters -ne $null) {
$result = $OctopusParameters[$Name]
}
if ($result -eq $null) {
if ($Required) {
throw "Missing parameter value $Name"
} else {
$result = $Default
}
}
return $result
}
$requiredParameter = Get-Parameter "RequiredParameter" -Required
$defaultedParameter = Get-Parameter "DefaultedParameter" "default value"
Write-Host "Script Title..."
Write-Host "RequiredParameter: $requiredParameter"
Write-Host "DefaultedParameter: $defaultedParameter"
# Main body of the script goes here!
function Invoke-OctopusStep {
param (
[Parameter(Mandatory=$true)]
[hashtable]$parameters,
[Parameter(Mandatory=$true)]
[string]$script
)
$OctopusParameters = @{}
foreach ($item in $parameters.GetEnumerator()) {
$OctopusParameters[$item.Name] = $item.Value;
}
& $script
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment