Reputation: 51
I am trying to get a list of computers from AD excluding some computers which are not in use anymore. Here is my code:
$ServerList = Get-ADComputer -Filter * | Where {
$_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notlike @("*server1*","*Server2*")
} | Select-Object Name
I am trying to put the computers which I was to exclude in an array instead of using
-and $_.DistinguishedName -notlike "*serverIwantToExclude*"
Can you guys give me any idea on how I could amend it ?
Upvotes: 1
Views: 1768
Reputation: 1
another way to exclude them is to add all those computers to a group and exclude it
#Provide DN of the group
$groupname = "CN=groupname,OU=Groups,DC=Domain,DC=COM"
get-adcomputer -filter {(OperatingSystem -like "Windows")} | -properties * | ?{([string]$_.memberof -notmatch $groupname)} | select name, lastlogondate
Upvotes: 0
Reputation: 25041
-notlike
does not support collections on the right-hand side (RHS). A similarly intended approach is to use -notmatch
, which is a regex string:
$ServerList = Get-ADComputer -Filter * |
Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch 'server1|Server2'} |
Select-Object Name
If you want your server names in a list first, you can create a regex string from that.
$serverdown = 'server1','server2'
$regex = $serverdown -join '|'
$ServerList = Get-ADComputer -Filter * |
Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch $regex} |
Select-Object Name
If you do not anchor your regex strings, it looks for the regex match anywhere within the target string (effectively having surrounding wildcards). |
is an alternation (an effective OR
).
There are other operators that support collections like -contains
, -in
, -notin
, and -notcontains
. However, they must match exactly and cannot use wildcards.
Upvotes: 3
Reputation: 2519
you can use the -inotin
operator if you know the full name of the servers you wish to exclude, meaning you can not use a wildcard or regex with the -inotin
operator. If this is the case and you know the names I recommend using the Name
property of the ADComputer
object.
[string[]] $excludedServers = 'server1','server2'
$ServerList = Get-ADComputer -Filter * | Where {
$_.DistinguishedName -like "*Computers*" -and $_.Name -inotin $excludedServers
} | Select-Object Name
Upvotes: 0