Skip to content

Commit 7a5816f

Browse files
author
James Brundage
committed
Adding ValidateTypes (50)
1 parent 03b674b commit 7a5816f

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
<#
2+
.Synopsis
3+
Validates if an object is one or more types.
4+
.Description
5+
Validates if an object is one or more types.
6+
7+
This allows for a single parameter to handle multiple potential types.
8+
.Example
9+
{
10+
param(
11+
[ValidateTypes(TypeName="ScriptBlock","string")]
12+
$In
13+
)
14+
} | .>PipeScript
15+
.Example
16+
{"hello world"} |
17+
Invoke-PipeScript -ScriptBlock {
18+
param(
19+
[vfp()]
20+
[ValidateTypes(TypeName="ScriptBlock","string")]
21+
$In
22+
)
23+
24+
$In
25+
}
26+
.Example
27+
1 |
28+
Invoke-PipeScript -ScriptBlock {
29+
param(
30+
[vfp()]
31+
[ValidateTypes(TypeName="ScriptBlock","string")]
32+
$In
33+
)
34+
35+
$In
36+
}
37+
#>
38+
[CmdletBinding(DefaultParameterSetName='Parameter')]
39+
param(
40+
# The name of one or more types.
41+
# Types can either be a .NET types of .PSTypenames
42+
# TypeNames will be treated first as real types, then as exact matches, then as wildcards, and then as regular expressions.
43+
[Parameter(Mandatory,Position=0)]
44+
[string[]]
45+
$TypeName
46+
)
47+
48+
49+
$checkTypes = @"
50+
`$validTypeList = '$($typeName -join "','")'
51+
"@ + {
52+
$thisType = @(
53+
if ($_.GetType) {
54+
$_.GetType()
55+
}
56+
$_.PSTypenames
57+
)
58+
$IsTypeOk =
59+
$(@(foreach ($validTypeName in $validTypeList) {
60+
$realType = $validTypeName -as [type]
61+
foreach ($Type in $thisType) {
62+
if ($Type -is [type]) {
63+
if ($realType) {
64+
$realType -eq $type -or
65+
$type.IsSubClassOf($realType) -or
66+
($realType.IsInterface -and $type.GetInterface($realType))
67+
} else {
68+
$type.Name -eq $realType -or
69+
$type.Fullname -eq $realType -or
70+
$type.Fullname -like $realType -or $(
71+
($realType -as [regex]) -and
72+
$type.Name -match $realType -or $type.Fullname -match $realType
73+
)
74+
}
75+
} else {
76+
$type -eq $realType -or
77+
$type -like $realType -or (
78+
($realType -as [regex]) -and
79+
$type -match $realType
80+
)
81+
}
82+
}
83+
}) -eq $true) -as [bool]
84+
}
85+
86+
if ($PSCmdlet.ParameterSetName -eq 'Parameter') {
87+
[scriptblock]::Create(@"
88+
[ValidateScript({
89+
$checkTypes
90+
if (-not `$isTypeOk) {
91+
throw "Unexpected type '`$(@(`$thisType)[0])'. Must be '$($typeName -join "','")'."
92+
}
93+
})]
94+
param()
95+
"@)
96+
}

0 commit comments

Comments
 (0)