Learn about Windows PowerShell
Summary: Learn four ways to use Windows PowerShell to find letters in strings.
I want to find out if a string contains the letter “m.” The string is stored in the variable $a as shown here:
$a=”northern hairy-nosed wombat”
Here are a variety of ways to accomplish this:
I usually don't add alternatives to your PowerTips, but this time I'm missing the most obvious expression:
$a -match 'm' or maybe
$a -like '*m*'
And, if I think back of VBScript, there is an "indexof" string member, that we can use:
$a.IndexOf('m') -ge 0
here some variant:
PS II> [regex]::ismatch($a,"m")
PS II> Select-String -InputObject $a -Pattern m -Quiet -SimpleMatch
PS II> $a -replace 'm' -ne $a
PS II> $a.ToCharArray() -contains 'm'
PS II> 'm' in $a.ToCharArray() #PS3
And today has been brought to you by the letter "M".
@K_Schulte I am glad you add additional suggestions. I am not posting "edicts" here, but am really wanting to get a conversation started. Everyone who does PowerShell for more than a few months ends up doing things their favorite way. I am hoping to show other ways of doing things, so that we can add an additional tool in our box of tricks. Thank you for sharing.
@Walid Toumi Those are great additions. Thank you for sharing.
@JRV we quit doing Sesame Script years ago ... :-)
@Ed. Then you should be able to use the rest of the alphabet.
I thought 'Sesame Script' was more like "Open sesame'" - You know. LIke Ali Baba.