0nir
0nir

Reputation: 1355

Search for special characters in a string in PowerShell

I have the below code wherein I am trying to search for special characters and the length of the string. Should the condition fail, an error note should be written to the host. I am using PowerShell 2.0. The code checks for the string length, but it is not able to check for any special character.

$chk = $user_logon.Output_Value
if($chk.length -gt 64 -or $chk -notmatch '[^a-zA-Z0-9]')
{
  Write-Host "Error - The Value ""$chk"" is greater than 64 bits or it contains a special character" -BackgroundColor "White" -ForegroundColor "Red";
}

I also tried -

if($chk.length -gt 64 -or $chk -notmatch "^[a-zA-Z0-9\s]+$")

which has worked. But I would like to have the condition which checks for all the special characters barring an underscore "_" which can be a part of $chk.

Upvotes: 2

Views: 24127

Answers (1)

ctn
ctn

Reputation: 2930

You need to replace $chk -notmatch '[^a-zA-Z0-9]' with $chk -match '[^a-zA-Z0-9]'

Upvotes: 4

Related Questions