-like oddity

Recently saw a question asking why this code worked

PS>  $a = ‘aa’
PS>  $b = ‘a’
PS>  $a -like “*$b*”
PS>  Remove-Variable -Name b
PS>  $a -like “*$b*”

Set 2 variables and compare using wildcards. The comparison comes back as  True as you’d expect.

Remove $b and try the comparison again. Still comes back as true.

The reason is based on the definition of the wildcard *

By removing $b you’re really testing

PS>  $a -like “**”

The definition of the * wildcard is that it:

Matches zero or more characters

So, just having a wildcard will always match

PS>  $a -like ‘*’

Just a little something to be aware of when using wildcards and variables. If the variable is null – effective result if not present – you’ll always get a  match.

This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s