Last active
February 8, 2019 20:13
-
-
Save jakobii/e33f764afa087046034100e387ce1cbe to your computer and use it in GitHub Desktop.
Anonymous Powershell Functions
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
# 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