Share via


How to check if an asterisk is in a string?

Question

Tuesday, November 29, 2011 9:12 PM

How can I check if an asterisk is in a string?

 

Example:

$string = "fdas*hjkl"

 If ($string -match "*"){Write-Host "Asterisk Found"}

All replies (2)

Tuesday, November 29, 2011 9:13 PM âś…Answered

PS >  "fdas*hjkl".Contains("*")
True
PS >  "fdas*hjkl".IndexOf("*")
4
PS >  "fdas*hjkl" -match "\*"
True
PS >  "fdashjkl" -match "\*"
False

Tuesday, November 29, 2011 9:33 PM

If ($string -match '\'){Write-Host 'Asterisk Found'}

 

-match uses regular expressions so you have to use \ to represent a

simple * character.

 

Note that I recoded with single-quotes.  I try to always use

single-quotes when no PowerShell string expansion is intended.

 On 11/29/2011 3:12 PM, Chadz wrote:

> How can I check if an asterisk is in a string?

> Example:

> $string="fdas*hjkl"

> If($string-match"*"){*Write-Host*"Asterisk Found"}

>