Powershell: where {_.Name is not in $ object}

I am creating a script that lists all inactive computer accounts. I would like to exclude several systems from the results.

I have a text file containing all the systems that need to be excluded (one system name per line). All elements are stored in the object with the property name "name". So $ excluded will contain:

name ---- system1 system2 

To list all inactive systems, I use the Search-ADAccount cmdlet:

 $InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true} 

Of course, I can loop all the results 1 on 1, but is there an easy way to exclude systems directly from the results? I have a feeling that this is possible with select-object or where-object, but I cannot figure out how to compare the results with objects.

+4
source share
3 answers

You were basically right to use this in your title: "where {_.Name is not in $ object}"

The syntax is a little different. Connect it to the next

 Where { !($_.Name -in $excluded) } 

OR

 Where { $_.Name -notin $excluded } 

Both seem to give the same results in the console. Happy coding!

Note. Tested on PSv2 and v3.

I came across this when I was looking for an answer, and decided that I would update these parameters for others who are facing this.

+11
source

Import the exclude file (like csv) and use the -notcontains statement:

 $names = Import-csv exclude.txt | Foreach-Object {$_.Name} $InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $names -notcontains $_.Name} 
+3
source

I think you can use -notcontains ( TechNet article ):

 $InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $excluded -notcontains $_.name } 
0
source

Source: https://habr.com/ru/post/1413692/


All Articles