1+ <#
2+ . SYNOPSIS
3+ Validates the Platform
4+ . DESCRIPTION
5+ Validates the Platform.
6+
7+ When used within Parameters, this adds a ```[ValidateScript({})]``` to ensure that the platform is correct.
8+
9+ When used on a ```[Management.Automation.Language.VariableExpressionAst]``` will apply a
10+ ```[ValidateScript({})]``` to that variable, which will prevent assignemnt to the variable if not on the platform.
11+ . EXAMPLE
12+ {
13+ param(
14+ [ValidatePlatform("Windows")]
15+ [switch]
16+ $UseWMI
17+ )
18+ } | .>PipeScript
19+ #>
20+ [CmdletBinding (DefaultParameterSetName = ' Parameter' )]
21+ param (
22+ # The name of one or more platforms. These will be interpreted as wildcards.
23+ [Parameter (Mandatory , Position = 0 )]
24+ [string []]
25+ $Platform ,
26+
27+ [Parameter (ValueFromPipeline , ParameterSetName = ' VariableExpressionAST' )]
28+ [Management.Automation.Language.VariableExpressionAST ]
29+ $VariableAST
30+ )
31+
32+ $Platform = @ ($Platform -replace ' Windows' , ' Win*' )
33+
34+ $checkPlatform = @"
35+ `$ platformList = '$ ( $Platform -join " ','" ) '
36+ "@ + {
37+ $platformOK = ($platFormList -like ' Win*' -and $ (
38+ $winPlat = @ ($platFormList -like ' Win*' )[0 ]
39+ (-not $psVersionTable.Platform ) -or $psVersionTable.Platform -like $winPlat
40+ )) -or $ (
41+ foreach ($platform in $platformList ) {
42+ if ($psVersionTable.Platform -like $platform ) {
43+ $true ;break
44+ }
45+ }
46+ )
47+ }
48+
49+ if ($PSCmdlet.ParameterSetName -eq ' Parameter' ) {
50+
51+ [ScriptBlock ]::Create(@"
52+ [ValidateScript({
53+ `$ ok = `$ false
54+ $checkPlatform
55+ `$ ok = `$ platformOK
56+ if (-not `$ ok) {
57+ throw "Incorrect Platform: '`$ (`$ psVersionTable.Platform)'. Must be like '$ ( $Platform -join " ','" ) '."
58+ }
59+ })]
60+ $ (
61+ if ($psCmdlet.ParameterSetName -eq ' Parameter' ) {
62+ ' param()'
63+ } else {
64+ ' $' + $VariableAST.variablePath.ToString ()
65+ }
66+ )
67+ "@ )
68+
69+ }
0 commit comments