Home > Back-end >  better method for the condition "-or" Powershell
better method for the condition "-or" Powershell

Time:11-11

I have this code that the truth looks very tangled and I would like to make it more beautiful in sight

(Get-AzResource | Where {($_.tags.tag1-eq $null) -or ($_.tags.tag2-eq $null) -or ($_.tags.tag3-eq $null) -or ($_.tags.tag4-eq $null) -or ($_.tags.tag5-eq "") -or ($_.tags.tag6-eq "") -or ($_.tags.tag7-eq "")}

This code fulfills the function of finding resources that do not have certain tags and that are empty, but the problem is that I leave an "-or" can I make it more beautiful in some way?

CodePudding user response:

Use the -contains operator:

Get-AzResource | Where-Object {
  ($_.tags.tag1, $_.tags.tag2, $_.tags.tag3, $_.tags.tag4 -contains $null) -or
  ($_.tags.tag5, $_.tags.tag6, $_.tags.tag7 -contains '')
}

Note: The (...) around the -contains operations aren't strictly necessary, given the relative operator precedence of -contains and -or.

  • Related