TAGS :Viewed: 7 - Published at: a few seconds ago

[ More than one exception when using the match operator ]

I have this part of my code:

$exception = "VM"

ForEach($item in $list) {

IF ($item -match $exception) { $invalidlist += $item }
ELSE { $validlist += $item }

}

Which works as intendet when only assigned 1 item to the variable $exception. The Problem is, i need the variable to contain more then one item, like:$exception = "VM","TM","TMP"

How is it possible to search for a match to any item in $exception?

Thanks in advance.

EDIT: The $list is created by using:

$list = Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 548.00:00:00

Answer 1


Regarding your updated comment, your $list is array of AD Objects: Assuming you care of the computer name, You should add the Name property to $item -> $item.name like in the following example:

*If you care to return only the Computer name and not the full object, add the $item.name to the invalid variable as well, e.g. $invalidlist += $item.name

$invalidlist = @()
$validlist = @()
$exception = "VM","TM","TMP"
$list = Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 548.00:00:00   

ForEach($item in $list) {

## if the item in $exception are equal to the $item name you can use the contains operator
## otherwise you can use -match
IF ($exception -contains $item.name) { $invalidlist += $item }
ELSE { $validlist += $item }
}