Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell -like operator is not commutative

Consider the following:

$var = 'Now is the time'
if ($var -like 'Now*') { 'true' } else { 'false' }

Output: true

Now swap the two operands for the -like operator:

if ('Now*' -like $var) { 'true' } else { 'false' }

Output: false

The -like operator is not commutative. Is this as expected?

I am on Win 7, using PS version 2. Thanks.

like image 379
Sabuncu Avatar asked Dec 05 '25 07:12

Sabuncu


1 Answers

-Like behaves not commutative - this is expected.

Some points:

  1. A summary of the discussion above in the comments: Commutativity would introduce ambiguity: 'Hello.*' -like 'Hello?' - would this return true or false were -like commutative? Therefor wildcard characters are only allowed on the right side. If they appear on the left size, they are considered literals - not wildcards.

If someone else has other valid points: feel free to edit or give a better answer.

like image 141
Davor Josipovic Avatar answered Dec 08 '25 13:12

Davor Josipovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!