通过powershell获取ActiveDirectory中不同OU的所有用户

时间:2015-09-07 07:42:01

标签: powershell

我知道如何将Get-ADUser用于一个OU但是如何为多个OU扩展它?

import-module activedirectory
$Path = 'OU=usertest,dc=a,dc=b,dc=com'
$NumberOfUsersinAD =  (Get-ADUser -SearchBase $Path –filter * ).count 
$ADUsers = Get-ADUser -Searchbase $Path -Filter *

1 个答案:

答案 0 :(得分:0)

单个查询只能有一个SearchBase,但如果您愿意,可以发出多个查询:

$Domain      = 'dc=a,dc=b,dc=com'
# Create array of OU paths
$OUsToSearch = @(
  "OU=usertest1,$Domain",
  "OU=usertest2,$Domain",
  "OU=Deeply,OU=Nested,OU=usertest1,$Domain"
)

# Create empty array 
$ADUsers = @()

# Loop through OUs and search for users
foreach($Path in $OUsToSearch){
    $ADUsers += Get-ADUser -SearchBase $Path -Filter *
}

# Count users (no need for a separate query)
$NumberOfADUsers = $ADUsers.Count