I'm trying to create a powershell function that validates users names and if a tech inputs the wrong character, I want it to throw an error message as to why it was wrong and restart the script for them to make the choice again.
So far I have this
Running VSCode with Powershell Extension 2022.8.5
function stringTest {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateLength(4,15)]
[ValidatePattern('^[a-zA-Z0-9-_]+$')]
[string] $alphaTest
)
Write-Host $alphaTest
}
$writeHere = Read-Host "UserName: "
stringTest($writeHere)
Output:
UserName: doej
doej
This works fine, but I want to try and add Custom error messages using the ErrorMessage within Validate Pattern. So I would try this
function stringTest {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateLength(4,15)]
[ValidatePattern({$pattern = "^[a-zA-Z0-9-_]+$([Regex]::escape($pattern))\s"
if ($_ -in $pattern ) {return $true}
throw "$_ is not a valid character. Valid characters are: '$($pattern -join ',')'"
})]
[string] $alphaTest
)
Write-Host $alphaTest
}
$writeHere = Read-Host "UserName: "
stringTest($writeHere)
But now my Validate doesn't actually validate anymore? I try the same name or anything different that "should" be valid
Cannot validate argument on parameter 'alphaTest'. The argument "doej" does not match the "$pattern = | "^[a-zA-Z0-9-]+$([Regex]::escape($pattern))\s" if ($ -in $pattern ) {return $true} throw "$_ is not a valid | character. Valid characters are: '$($pattern -join ',')'" " pattern. Supply an argument that matches "$pattern = | "^[a-zA-Z0-9-]+$([Regex]::escape($pattern))\s" if ($ -in $pattern ) {return $true} throw "$_ is not a valid | character. Valid characters are: '$($pattern -join ',')'" " and try the command again.
From the looks of it, it's trying to match the regex pattern exactly instead of working the way before. Any help would be greatly appreciated or pointing me in the write direction for this.
classorValidateScript[ScriptBlock]toValidatePattern, which, of course, expects a (string) pattern. UseValidateScriptinstead. Also, you'd want to use$_ -match $pattern, not-in.