简体   繁体   中英

Powershell- get value from array - Where-Object

I got the job to create a Script which gets from the Department Number (in AD) all Users and their related Computers (Managed By attribute).

I managed to get all Users - and a array of all AD-Computers which have the Managed By attribute set- now I have to find each correct computer (means where the Username (got from AD-Users)) matches one (or more) computers of the Complete AD-Computer extract.

I tried it now with this one:

$test = $user.samaccountname
$computer +=($ManagedBy | Where-Object {$_.ManagedBy -like "*"$test"*"})

Short explanation of the variables:

$ManagedBy contains:

@{ManagedBy=CN=weibo1,OU=Users,OU=Managed,DC=asia,DC=ourComp,DC=com; Name=computer1}
@{ManagedBy=CN=kimyo1,OU=Users,OU=Managed,DC=asia,DC=ourComp,DC=com; Name=computer2} 

$test contains all usernames which are in the wanted department:

putzifa1
fischch1
jonesem1

etc.

I have really no idea and can't find any good solution on the web to do this (I have some ideas like foreach and then all the time an if or something, but I guess the performance would not work) .... $ManagedBy contains about 4000 entries, the other one about 350

Thank you very much in advance!

You're making this way too complicated. The managedBy attribute contains a user's distinguished name, so all you need to do is get a list with the distinguished names of users from a given department, then filter the computer objects for managedBy values contained in that list.

Assuming that the department number is stored in the proper attribute ( department ) something like this should do:

$dept = ...

$users = Get-ADUser -Filter 'department -eq "$dept"' |
         select -Expand DistinguishedName

Get-ADComputer -Filter * -Properties * | ? {
  $users -contains $_.ManagedBy
} | select -Expand Name

Or something like this, if you need both computername and the associated username:

$dept = ...

$users = @{}
Get-ADUser -Filter 'department -eq "$dept"' | % {
  $users[$_.DistinguishedName] = $_.SamAccountName
}

Get-ADComputer -Filter * -Properties * | ? {
  $users.Keys -contains $_.ManagedBy
} | select @{n='Computer';e={$_.Name}}, @{n='User';e={$users[$_.ManagedBy]}}

The statement $user = @{} creates an empty hashtable , which is subsequently filled with distinguishedName/sAMAccountName pairs ( $users[$_.DistinguishedName] = $_.SamAccountName ). The purpose of creating a hashtable instead of a simple list is to allow you to look up account names by the distinguished name stored in a computer's managedBy attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM