Skip to content

Instantly share code, notes, and snippets.

View chriskuech's full-sized avatar

Chris Kuech chriskuech

  • Datum Source, ex MSFT
View GitHub Profile
$ErrorActionPreference = "Stop"
function Assert-True {
[CmdletBinding()] # add ErrorAction support
Param([boolean]$Value)
if (-not $Value) {
throw "Failed assertion"
}
}
$ErrorActionPreference = "Stop"
# an error will thrown and caught, so you wont see it
try {
throw "something bad happened..."
} catch {
Write-Host "It looks like $_, but everything's still fine."
} finally {
Write-Host "I knew I would get here eventually"
}
function div($n, $d) {$n / $d} # a seemingly pure function
div 1 0 # throws 'Attempted to divide by zero' error
# this outer scope contains only immutable variables
$var = & {
# this scope contains mutable temporary variables
$queue = [System.Collections.Generic]::new()
$queue.Enqueue(@{Id = 1})
while ($queue.Count) {
$jobInfo = $queue.Dequeue()
$newJobInfo = Update-RemoteJob $jobInfo # non-deterministic
if ($newJobInfo) {
$queue.Enqueue($newJobInfo)
function Invoke-AfterEach {
Param(
[scriptblock[]]$ScriptBlock,
[scriptblock]$OnTaskComplete
)
$ScriptBlock | % {
Start-Job {
Param($action, $callback)
&$action
&$callback
$job = Start-Job $action
... # do some other stuff
$job | Wait-Job
# invokes the action, then calls the callback upon completion
function Invoke-Then([scriptblock]$action, [scriptblock]$callback) {
Start-Job {
&$using:action
&$using:callback
}
}
$job = Start-Job $action # `$action` will be executed asynchronously
Invoke-NextCommand # will be called before `$action` has completed
$job | Wait-Job -Timeout 60 | Receive-Job
$d = $a | % {&$aToB $_} | % {&$bToC $_} | % {&$cToD $_}
Import-Module functional
$aToD = $aToB, $bToC, $cToD | Merge-ScriptBlock