简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM