Last active
September 12, 2018 13:53
-
-
Save luksi1/628fa2cf1b42f865b75af245737c01ce to your computer and use it in GitHub Desktop.
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
# Custom validator for one element | |
class ValidateElementAttribute : System.Management.Automation.ValidateArgumentsAttribute | |
{ | |
[void] Validate([object]$arguments, [System.Management.Automation.EngineIntrinsics]$engineIntrinsics) | |
{ | |
# Validation happens here | |
if ($arguments -ne "foo") { | |
throw "you should have chosen foo" | |
} | |
} | |
} | |
# Custom validator for multiple elements | |
class ValidateElementsAttribute : System.Management.Automation.ValidateEnumeratedArgumentsAttribute | |
{ | |
[void] ValidateElement([object]$arguments) | |
{ | |
# Check each element here | |
if ($arguments -notmatch "^f") { | |
throw "nope... not f*. maybe try 'foo' or 'flute' or 'fsck'" | |
} | |
} | |
} | |
function Do-Something | |
{ | |
[cmdletbinding()] | |
param( | |
[ValidateElement()] | |
$A, | |
[ValidateElements()] | |
$B | |
) | |
if ($A) { | |
write-host $A | |
} | |
if ($B) { | |
write-host $B | |
} | |
} | |
# Throws an exception | |
Do-Something -A poo | |
# Does not throw exception | |
Do-Something -A foo | |
# Throws exception | |
Do-Something -B @("foo","food","pooo") | |
# Does not throw exception | |
Do-Something -B @("foo","food","flute") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment