英文:
Get all AD object name under specific OU
问题
我想修改下面的PowerShell脚本以导出OU成员(用户和计算机),其中输入将如下所示:
$OUlist = @(
domain.com/Site-A/OU1
domain.com/Site-A/OU2
domain.com/Site-B/OU1
domain.com/Site-B/OU2
...
domain.com/Site-Z/OU1
domain.com/Site-Z/OU99
)
$targetOUs = $OUList
$users = $targetOUs | ForEach-Object {
Get-ADUser -Filter * -SearchBase $_.distinguishedName
Get-ADComputer -Filter * -SearchBase $_.distinguishedName
} | Export-CSV "Result.csv" -NTI
Result.CSV 内容:
Name, Type
PC1, Computer
Person1, User
PC2, Computer
Person2, User
英文:
I would like to modify this PowerShell script below to export the OU members (Users and Computers) where the input will be like this:
$OUlist = @(
domain.com/Site-A/OU1
domain.com/Site-A/OU2
domain.com/Site-B/OU1
domain.com/Site-B/OU2
...
domain.com/Site-Z/OU1
domain.com/Site-Z/OU99
)
$targetOUs = $OUList
$users = $targetOUs |ForEach-Object {
Get-ADUser -Filter * -SearchBase $_.distinguishedName
Get-ADComputer -Filter * -SearchBase $_.distinguishedName
} | Export-CSV "Result.csv" -NTI
Result.CSV content:
Name, Type
PC1, Computer
Person1, User
PC2, Computer
Person2, User
答案1
得分: 1
自从你有一个 CanonicalNames 列表,那么你需要查询所有的组织单位 (OUs) 以正确获取 OU 的 DistinguishedName,以便将其用作 -SearchBase
:
$map = Get-ADOrganizationalUnit -Filter * -Properties canonicalName |
Group-Object canonicalName -AsHashTable -AsString
$targetOUs | ForEach-Object {
# 如果这个 `CanonicalName` 属于现有的组织单位
if($map.ContainsKey($_)) {
$queryParams = @{
LDAPFilter = '(objectClass=user)'
SearchBase = $map[$_].DistinguishedName
SearchScope = 'OneLevel' # 仅查找直接的对象
}
foreach($object in Get-ADObject @queryParams) {
[pscustomobject]@{
Name = $object.Name
Type = $object.ObjectClass
SourceOU = $_
}
}
}
} | Export-CSV "Result.csv" -NTI
从技术上讲,计算机对象是用户类的一个子类,因此使用过滤器 (objectClass=user)
会在单个查询中找到计算机和用户。
英文:
Since you have a list of CanonicalNames then you would need to query all OUs to properly get the OU's DistinguishedName to use as -SearchBase
:
$map = Get-ADOrganizationalUnit -Filter * -Properties canonicalName |
Group-Object canonicalName -AsHashTable -AsString
$targetOUs | ForEach-Object {
# if this `CanonicalName` belongs to an existing OU
if($map.ContainsKey($_)) {
$queryParams = @{
LDAPFilter = '(objectClass=user)'
SearchBase = $map[$_].DistinguishedName
SearchScope = 'OneLevel' # looking only for immediate objects
}
foreach($object in Get-ADObject @queryParams) {
[pscustomobject]@{
Name = $object.Name
Type = $object.ObjectClass
SourceOU = $_
}
}
}
} | Export-CSV "Result.csv" -NTI
Technically, computer objects are a subclass of the user class hence using the filter (objectClass=user)
would find both, computers and users in a single query.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论