Skip to content

Instantly share code, notes, and snippets.

@jakobii
Last active February 8, 2019 20:13
Show Gist options
  • Save jakobii/e33f764afa087046034100e387ce1cbe to your computer and use it in GitHub Desktop.
Save jakobii/e33f764afa087046034100e387ce1cbe to your computer and use it in GitHub Desktop.
Anonymous Powershell Functions
# Our Custom Logic
$CustomErrorAction = {
param(
$TheError
)
# some custom logic
write-host $TheError -ForegroundColor 'red'
}
# A Contrived Function
Function Use-File {
param(
[string]$Path,
[scriptblock]$OnError # The callback function
)
# test the path
[bool]$FileExists = Test-Path $path -ErrorAction 'stop'
# if the path can't be found, invoke the $OnError scriptblock.
# pass the error to the script block.
if(!$FileExists){
$OnError.invoke("Can not find $Path!")
}
# function continues to do other stuff ......
}
Use-File -Path "C:\missing\file.txt" -OnError $CustomErrorAction
# Can not find C:\missing\file.txt!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment