title: Search for special characters in a string in PowerShell
body: <p>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.</p>
  <pre><code>$chk = $user_logon.Output_Value
  if($chk.length -gt 64 -or $chk -notmatch '[^a-zA-Z0-9]')
  {
    Write-Host &quot;Error - The Value &quot;&quot;$chk&quot;&quot; is greater than 64 bits or it contains a special character&quot; -BackgroundColor &quot;White&quot; -ForegroundColor &quot;Red&quot;;
  }
  </code></pre>
  <p>I also tried -</p>
  <pre><code>if($chk.length -gt 64 -or $chk -notmatch &quot;^[a-zA-Z0-9\s]+$&quot;)
  </code></pre>
  <p>which has worked. But I would like to have the condition which checks for all the special characters barring an underscore &quot;_&quot; which can be a part of $chk.</p>