Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Where-Object like multiple string values

I'm using the following in a do-until block to loop until a specified Exchange Online migration status is present:

(Get-Migrationbatch -Identity $MigrationBatchName | Where {$_.Status -like "Completed" -or "CompletedWithErrors" -or "Corrupted" -or "Failed" -or "Stopped"})

However, the above still returns a job with the status of "Syncing" and so continues the script regardless.

I've tried -match, -eq but still the same.

What am I missing?

like image 548
jshizzle Avatar asked Sep 15 '17 11:09

jshizzle


People also ask

How to use Where condition in PowerShell?

The Where-Object clause in PowerShell filters the content according to a specific value of the property of an object. The Where-Object clause can also be used with any cmdlet/function to target a specific property value of an object.

Where-Object using PowerShell?

The Where-Object cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.

Where-Object filter PowerShell?

The PowerShell Where-Object cmdlet's only goal is to filter the output a command returns to only return the information you want to see. In a nutshell, the Where-Object cmdlet is a filter; that's it. It allows you to construct a condition that returns True or False.

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


2 Answers

You have to write it like this:

(Get-Migrationbatch -Identity $MigrationBatchName | Where {($_.Status -like "Completed") -or ($_.Status -like "CompletedWithErrors") -or ($_.Status -like "Corrupted") -or ($_.Status -like "Failed") -or ($_.Status -like "Stopped")})

Here's another way to do it:

$valuesToLookFor = @(
    'Completed',
    'CompletedWithErrors',
    'Corrupted',
    'Failed',
    'Stopped')

(Get-Migrationbatch -Identity $MigrationBatchName |
    Where-Object { $valuesToLookFor -contains $_.Status })
like image 186
JamesQMurphy Avatar answered Oct 23 '22 05:10

JamesQMurphy


It would be simpler using -in operator, given that you are not using wildcards:

(Get-Migrationbatch -Identity $MigrationBatchName | Where Status -in "Completed","CompletedWithErrors","Corrupted","Failed","Stopped")
like image 33
BobCormorano Avatar answered Oct 23 '22 05:10

BobCormorano