Skip to content

Instantly share code, notes, and snippets.

@luksi1
Last active September 12, 2018 13:53
Show Gist options
  • Save luksi1/628fa2cf1b42f865b75af245737c01ce to your computer and use it in GitHub Desktop.
Save luksi1/628fa2cf1b42f865b75af245737c01ce to your computer and use it in GitHub Desktop.
# 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