使用Powershell获取嵌套OU

时间:2011-06-20 06:57:01

标签: windows arrays powershell

我试图编写一个powershell脚本来获取嵌套OU中服务器的OU信息,而不使用QAD cmdlet,一个堆栈成员帮助我编写了如下代码

$computerName = "DC1"
$found = $FALSE
$domain = [ADSI]("LDAP://dc=contoso,dc=com")

$ous = ($domain.psbase.children |
        Where-Object {$_.psBase.schemaClassName -eq "OrganizationalUnit"} |
        Select-Object -expand Name)        

foreach ($child in $ous){
    $ou = [ADSI]("LDAP://ou=$child,dc=contoso,dc=com")
    $computers = ($ou.psbase.children |
                  Where-Object {$_.psBase.schemaClassName -eq "Computer"} |
                  Select-Object -expand Name)

    foreach ($client in $computers){
        if ($client -eq $computerName) {
            Write-Host "Found $computerName in" $ou.psBase.name
            $found = $TRUE
        }
    }
}

if (-not $found) {Write-Host "$computerName not found."}

我想要一些帮助来修改计算机在嵌套OU中的存在。

谢谢, Vinith

2 个答案:

答案 0 :(得分:2)

您可以使用adsisearcher加速器:

$searcher = [adsisearcher]'(&(ObjectCategory=computer)(Name=DC1))'
$searcher.FindOne()

答案 1 :(得分:2)

#  Reference -- http://powergui.org/thread.jspa?threadID=17534
#  List and count user objects per OU 

Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
cd\
cls

$File = "C:\Scripts\CountComputersInOu.csv"
#To specify parent OU "your.domain.com/computer"
$StartOU = "your.domain.com/"
$strFilter = ‘(objectClass=Computer)’

foreach ($targetou in Get-QADObject -SearchRoot $StartOU -Type organizationalUnit)
{

$Parent = [ADSI]"LDAP://$targetou"
#"These are the users in $($Parent.PSBase.Parent.Name): " | Out-File $File -append

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = 'LDAP://'+$targetou+''
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "onelevel"

$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()


"There are $($colResults.count) active computers in $($Parent.PSBase.Parent.Name)\$($targetou.name)
" | Out-File $File -append
}