Search for special characters in a string in PowerShell

18,084

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

Share:
18,084
0nir
Author by

0nir

Data Ninja..

Updated on July 29, 2022

Comments

  • 0nir
    0nir over 1 year

    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.