Skip to content

Commit 592a51d

Browse files
author
James Brundage
committed
Adding ValidateExtension (#64)
1 parent fd81038 commit 592a51d

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<#
2+
.SYNOPSIS
3+
Validates Extensions
4+
.DESCRIPTION
5+
Validates that a parameter or object has one or more extensions.
6+
7+
This creates a [ValidatePattern] that will ensure the extension matches.
8+
.Example
9+
{
10+
param(
11+
[ValidateExtension(Extension=".cs", ".ps1")]
12+
$FilePath
13+
)
14+
} |.>PipeScript
15+
.Example
16+
.> {
17+
param(
18+
[ValidateExtension(Extension=".cs", ".ps1")]
19+
$FilePath
20+
)
21+
22+
$FilePath
23+
} -Parameter @{FilePath=".ps1"}
24+
.EXAMPLE
25+
.> {
26+
param(
27+
[ValidateExtension(Extension=".cs", ".ps1")]
28+
$FilePath
29+
)
30+
31+
$FilePath
32+
} -Parameter @{FilePath="foo.txt"}
33+
#>
34+
[CmdletBinding(DefaultParameterSetName='Parameter')]
35+
param(
36+
# The extensions being validated.
37+
[Parameter(Mandatory,Position=0)]
38+
[string[]]
39+
$Extension,
40+
41+
# A variable expression.
42+
# If this is provided, will apply a ```[ValidatePattern({})]``` attribute to the variable, constraining future values.
43+
[Parameter(ValueFromPipeline,ParameterSetName='VariableExpressionAST')]
44+
[Management.Automation.Language.VariableExpressionAST]
45+
$VariableAST
46+
)
47+
48+
process {
49+
$validExtensionRegex = "\.(?>$($extension -replace '^\.' -join "|"))$"
50+
[ScriptBlock]::Create(@"
51+
[ValidatePattern('$($validExtensionRegex.Replace("'","''"))')]
52+
$(
53+
if ($psCmdlet.ParameterSetName -eq 'Parameter') {
54+
'param()'
55+
} else {
56+
'$' + $VariableAST.variablePath.ToString()
57+
}
58+
)
59+
"@)
60+
}

0 commit comments

Comments
 (0)