Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicholasLeader/5621a854c19b5a400b67d6c2bb42381f to your computer and use it in GitHub Desktop.
Save NicholasLeader/5621a854c19b5a400b67d6c2bb42381f to your computer and use it in GitHub Desktop.
PowerShell Function Example with input validation
<#
Nicholas Leader
05/16/2016
Simple function example
In this example I'm showing how input to the function can be validated
After running this script a 'Test-name' function will be available, which accepts an argument or parameter
Reference: http://mikefrobbins.com/2015/03/31/powershell-advanced-functions-can-we-build-them-better-with-parameter-validation-yes-we-can/
#>
# declaring the function name
function Test-name {
# binding to a cmdlet for calling function after script is run
[CmdletBinding()]
# setting up the parameter or argument to the function
param (
[ValidateScript({
# filting the input - if the user's value contains 'Monkey' or 'test' in the string, then the function will return
If ($_ -like '*Monkey*'-or $_ -like '*test*') {
$True
}
# if 'monkey' or 'test' are not in the string supplied by the user then an error is thrown
else {
Throw "$_ is either not a valid filename or it is not recommended."
}
})]
# Setting the function object to a string
[string]$FileName
)
# writing the output of the function (assuming the value is bool of true) to the console
Write-host $FileName "is acceptable!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment