1+ <#
2+ . SYNOPSIS
3+ Validates Property Names
4+ . DESCRIPTION
5+ Validates that an object has one or more property names.
6+ . Example
7+ {
8+ param(
9+ [ValidatePropertyName(PropertyName='a','b')]
10+ $InputObject
11+ )
12+ } | .>PipeScript
13+ . EXAMPLE
14+ [PSCustomObject]@{a='a';b='b'} |
15+ .> {
16+ param(
17+ [ValidatePropertyName(PropertyName='a','b')]
18+ [vfp]
19+ $InputObject
20+ )
21+
22+ $InputObject
23+ }
24+ . EXAMPLE
25+ @{a='a'} |
26+ .> {
27+ param(
28+ [ValidatePropertyName(PropertyName='a','b')]
29+ [vfp]
30+ $InputObject
31+ )
32+
33+ $InputObject
34+ }
35+ #>
36+ [CmdletBinding (DefaultParameterSetName = ' Parameter' )]
37+ [Alias (' ValidatePropertyNames' )]
38+ param (
39+ # The property names being validated.
40+ [Parameter (Mandatory , Position = 0 )]
41+ [string []]
42+ $PropertyName ,
43+
44+ # A variable expression.
45+ # If this is provided, will apply a ```[ValidateScript({})]``` attribute to the variable, constraining future values.
46+ [Parameter (ValueFromPipeline , ParameterSetName = ' VariableExpressionAST' )]
47+ [Management.Automation.Language.VariableExpressionAST ]
48+ $VariableAST
49+ )
50+
51+ process {
52+ $checkPropertyNames =
53+ {
54+ $foundProperties = @ (
55+ foreach ($propName in $PropertyNames ) {
56+ if ($inObject -is [Collections.IDictionary ]) {
57+ $inObject.Contains ($propName )
58+ } elseif ($inObject.psobject ) {
59+ $null -ne $inObject.psobject.properties [$propName ]
60+ } else {
61+ $false
62+ }
63+ }
64+ )
65+ $missingProperties =
66+ @ (
67+ for ($propertyIndex = 0 ; $propertyIndex -lt $propertyNames.Length ; $propertyIndex ++ ) {
68+ if (-not $foundProperties [$propertyIndex ]) {
69+ $PropertyNames [$propertyIndex ]
70+ }
71+ })
72+ }
73+
74+
75+ [ScriptBlock ]::Create(@"
76+ [ValidateScript({
77+ `$ propertyNames = '$ ( $PropertyName -join " ','" ) '
78+ `$ inObject = `$ _
79+ $checkPropertyNames
80+ if (`$ MissingProperties) {
81+ throw "Missing Properties: `$ (`$ missingProperties -join ',')"
82+ }
83+ return `$ true
84+ })]
85+ $ (
86+ if ($psCmdlet.ParameterSetName -eq ' Parameter' ) {
87+ ' param()'
88+ } else {
89+ ' $' + $VariableAST.variablePath.ToString ()
90+ }
91+ )
92+ "@ )
93+
94+ }
0 commit comments