Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to compare multiple array values in PowerShell

Tags:

powershell

Is there a more elegant way to write the following if statement in PowerShell

[ValidateNotNull()]
[ValidateSet('Service', 'Role', 'RoleService', 'Feature', 'Group', 'File', 'Package')]
[Parameter(Mandatory = $true, Position = 1)]
[string[]]
$ProcessingModes

if ($ProcessingModes -contains 'Role' -or $ProcessingModes -contains 'RoleService' -or $ProcessingModes -contains 'Feature')
{
}
like image 843
Jupaol Avatar asked Mar 11 '26 09:03

Jupaol


2 Answers

You can do array intersection quite easily with this:

$keyModes = 'Role', 'RoleService', 'Feature'
if ($keyModes | ? { $ProcessingModes -contains $_ }) { "found at least one" }
like image 50
Michael Sorens Avatar answered Mar 14 '26 07:03

Michael Sorens


Your question is basically, is there an operator in PowerShell which determines whether the intersection between two arrays is non-empty. The answer is no, there is not. Additionally, after reviewing the question Powershell, kind of set intersection built-in?, it looks like the best approach is to use HashSet objects instead of arrays, which do expose IntersectWith and UnionWith methods.

like image 23
jdmichal Avatar answered Mar 14 '26 07:03

jdmichal