validate the string in powershell

how to validate the string in powershell script ?

i need to check the string ,  does  it contains any characters like  "!@#$%^&*()=+/\|{}[]'";:<>,?

how to do this ?
VarshiniAsked:
Who is Participating?
 
netballiCommented:
here is an small example $a is the string input which contains the special character
spliting the string into individual character and comparing it to all special character ( i havent used all special character but you can improvise)

#"!@#$%^&*()=+/\|{}[]'";:<>,?
$a = "netball@i"
$b = @($a -split"(\w{1})")
foreach($d in $b)
{
   if($d -like "`"" -Or $d -like "`!" -Or $d -like "`@" -Or $d -like "`#" -Or $d -like "`$" -Or $d -like "`%" -Or $d -like "`^" -Or $d -like "`&")
   {
      Write-host "$d an invalid character found"
   }

}
0
 
Carlo-GiulianiCommented:
($string  -match "^[a-zA-Z0-9]*$" ) 

Open in new window

will evaluate to to False if the string contains any character NOT specifed

($string   -match '[/,/./</>///?/;/:/''/"/\/|]') 

Open in new window

will evaluate to to True if the string contains any character specified.

Note the use of the regular expression escape character \ before each character, because many special characters has special meanings for regular expressions.   And the doubled single-quote.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.