DirectorySearcher获取所有域控制器以获取域列表

时间:2016-02-10 16:33:56

标签: powershell powershell-v3.0

目前我有8个域名。使用以下代码......

$listOfDCs = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers

ForEach ($DC in $listOfDCs)
{
    Write-Host $DC
}

我为一个域获得了32个控制器。知道如何为其他域提取控制器吗?

注意:我希望尽可能避免使用任务cmdlet。

原因是lastlogon属性值对于域中的每个dc都不同。我只想抓住最新的一个。这是我的工作代码,但它没有提取最新的代码......

$SamAccountName = "JohnDoe"
$domainSearchProperties = @('SamAccountName','LastLogon', 'DistinguishedName')
$domainDisplayOutputProperties = @('SamAccountName','LastLogon')
$domainConnector = 'www.myplayground.com'
$domainName = 'MyPlayground'
$outputFile = 'C:\Scripts\Tests\testresults.csv'

Function SearchSingleDomainAndExportContents
{
    Param ([String]$SamAccountName, [String]$LocalOutputFileWithPath, [String[]]$domainSearchProperties, [String[]]$domainDisplayOutputProperties, [String]$domainConnector, [String]$domainName)
    Write-Host "Starting sub-process to search with SamAccountName $SamAccountName in $domainName"
    $searchDomainResultsTable = powershell -command {
        Param ([String]$SamAccountName, [String]$LocalOutputFileWithPath, [String[]]$domainSearchProperties, [String[]]$domainDisplayOutputProperties, [String]$domainConnector, [String]$domainName)
        $domain = "LDAP://$domainConnector"
        $adDomain = New-Object System.DirectoryServices.DirectoryEntry($domain)
        $adSearcher = New-Object System.DirectoryServices.DirectorySearcher($adDomain)
        $adSearcher.Filter = "(&(objectCategory=User)(samAccountType:1.2.840.113556.1.4.803:=805306368)(sAMAccountName=$SamAccountName))"
        $adSearcher.PageSize=1000
        $adSearcher.PropertiesToLoad.AddRange($domainSearchProperties) | out-Null
        $userRecords = $adSearcher.FindAll() | Where-Object {($_.DistinguishedName -notlike "*Retired*")}
        $adSearcher.Dispose() | Out-Null
        [System.GC]::Collect() | Out-Null

        # The AD results are converted to an array of hashtables.
        $userPropertiesTable = @()
        foreach($record in $userRecords) {
            $hashUserProperty = @{}
            foreach($userProperty in $domainSearchProperties){
                if (($userProperty -eq 'objectGUID') -or ($userProperty -eq 'objectSid') -or ($userProperty -eq 'msExchMasterAccountSid')) {
                    if ($record.Properties[$userProperty]) {
                        $hashUserProperty.$userProperty = $record.Properties[$userProperty][0]
                    } else {
                        $hashUserProperty.$userProperty = $null
                    }
                } Else {
                    if ($record.Properties[$userProperty]) {
                        $hashUserProperty.$userProperty = ($record.Properties[$userProperty] -join '; ').trim('; ')
                    } else {
                        $hashUserProperty.$userProperty = $null
                    }
                } #end Else
            } #end ForEach
            $userPropertiesTable += New-Object PSObject -Property $hashUserProperty
        } #end ForEach
        [System.GC]::Collect() | Out-Null

        # Fixes the property values to be a readable format before exporting to csv file
        $listOfBadDateValues = '9223372036854775807', '9223372036854770000', '0'
        $maxDateValue = '12/31/1600 5:00 PM'
        $valuesToFix = @('lastLogonTimestamp', 'AccountExpires', 'LastLogon', 'pwdLastSet', 'objectGUID', 'objectSid', 'msExchMasterAccountSid')
        $valuesToFixCounter = 0
        $valuesToFixFound = @($false, $false, $false, $false, $false, $false, $false)

        ForEach ($valueToFix in $valuesToFix)
        {
            if ($domainDisplayOutputProperties -contains $valueToFix)
            {
                $valuesToFixFound[$valuesToFixCounter] = $true
            }
            $valuesToFixCounter++
        }

        $tableFixedValues = $userPropertiesTable | % { 
            if ($valuesToFixFound[0]) {
                if ($_.lastLogonTimestamp) {
                    $_.lastLogonTimestamp = ([datetime]::FromFileTime($_.lastLogonTimestamp)).ToString('g')
                }
            }; if ($valuesToFixFound[1]) {
                if (($_.AccountExpires) -and ($listOfBadDateValues -contains $_.AccountExpires)) {
                    $_.AccountExpires = ""
                } else {
                    if (([datetime]::FromFileTime($_.AccountExpires)).ToString('g') -eq $maxDateValue) {
                        $_.AccountExpires = ""
                    } Else {
                        $_.AccountExpires = ([datetime]::FromFileTime($_.AccountExpires)).ToString('g')
                    }
                }
            }; if ($valuesToFixFound[2]) {
                if (($_.LastLogon) -and ($listOfBadDateValues -contains $_.LastLogon)) {
                    $_.LastLogon = ""
                } else {
                    if (([datetime]::FromFileTime($_.LastLogon)).ToString('g') -eq $maxDateValue) {
                        $_.LastLogon = ""
                    } Else {
                        $_.LastLogon = ([datetime]::FromFileTime($_.LastLogon)).ToString('g')
                    }
                }
            }; if ($valuesToFixFound[3]) {
                if (($_.pwdLastSet) -and ($listOfBadDateValues -contains $_.pwdLastSet)) {
                    $_.pwdLastSet = ""
                } else {
                    if (([datetime]::FromFileTime($_.pwdLastSet)).ToString('g') -eq $maxDateValue) {
                        $_.pwdLastSet = ""
                    } Else {
                        $_.pwdLastSet = ([datetime]::FromFileTime($_.pwdLastSet)).ToString('g')
                    }
                }
            }; if ($valuesToFixFound[4]) {
                if ($_.objectGUID) {
                    $_.objectGUID = ([guid]$_.objectGUID).Guid
                } Else {
                    $_.objectGUID = ""
                }
            }; if ($valuesToFixFound[5]) {
                if ($_.objectSid) {
                    $_.objectSid  = (New-Object Security.Principal.SecurityIdentifier($_.objectSid, 0)).Value
                } Else {
                    $_.objectSid = ""
                }
            }; if ($valuesToFixFound[6]) {
                if ($_.msExchMasterAccountSid) {
                    $_.msExchMasterAccountSid  = (New-Object Security.Principal.SecurityIdentifier($_.msExchMasterAccountSid, 0)).Value
                } Else {
                    $_.msExchMasterAccountSid = ""
                }
            };$_}
            [System.GC]::Collect() | Out-Null

            $sortedUserPropertiesTable = $tableFixedValues | Select-Object $domainDisplayOutputProperties
            $finalDomainUserPropertiesTable = $sortedUserPropertiesTable | Select-Object -Property @{Name="Domain Name";Expression={$domainName}}, *
            [System.GC]::Collect() | Out-Null

            return $finalDomainUserPropertiesTable
    } -args $SamAccountName, $LocalOutputFileWithPath, $domainSearchProperties, $domainDisplayOutputProperties, $domainConnector, $domainName
    [System.GC]::Collect() | Out-Null
    Write-Host "Search Complete."
    Write-Host ""

    $searchDomainResultsTable | Export-Csv $outputFile -NoTypeInformation -Force
}

这将仅从1 dc中提取数据。这个问题是,还有其他的dc,其中lastlogon包含更晚的日期,那是我之后的日期。所以我需要查询所有的dc,然后只导出该SamAccountName的最新lastlogon日期。

3 个答案:

答案 0 :(得分:1)

如果您的计算机已经是域成员,则在林中查找所有其他域比您想象的要容易。

只需搜索crossRef个对象(这些是域控制器上的数据库分区与林中的逻辑命名上下文(如域)之间的链接,其systemFlag属性值设置为{ {1}}。这些都存储在配置命名上下文中的同一容器中:

0x3

答案 1 :(得分:0)

您可以使用.Net Domain类获取其他域名,就像您为当前域所做的那样。首先,您需要为您定位的域创建上下文,然后您可以获取域信息,包括DC。

$DomainList = 'Domain1.com','Domain2.com','Domain3.com','Domain4.com','Domain5.com','Domain6.com','Domain7.com','Domain8.com'
$AllDCs = $DomainList | ForEach{
    $DomContxt = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext -ArgumentList ('Domain',$_)
    $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomContxt)
    $Domain.DomainControlers
}

答案 2 :(得分:-1)

同样从命令行,您可以向dns服务器询问所有域控制器的IP地址

nslookup.exe domain1

相关问题