我有一個需要獲取 OU 的服務器串列,我已經撰寫了一個腳本來執行此操作。
Get-ADOrganizationalUnit
-Identity $(($adComputer = Get-ADComputer -Identity $env:COMPUTERNAME).DistinguishedName.SubString($adComputer.DistinguishedName.IndexOf("OU=")))
這里的問題是 OU 名稱難以閱讀且不易辨認,因此我發現我需要的是 CanonicalName。然而,問題就在這里。
我想出了下面的片段。
Get-ADOrganizationalUnit -Filter * -properties CanonicalName, DistinguishedName
| select-Object CanonicalName,DistinguishedName
上面的問題是它獲取了 AD 中的所有內容,我需要能夠按服務器名進行過濾,這樣當我在檔案中加載服務器串列時,我可以使用 foreach 回圈來獲取服務器名和服務器名的報告OU,我嘗試使用 -Server 過濾器無濟于事,因為我相信這是針對 AD 服務器的。
在我的研究中,我發現PowerShell 按 OU 過濾。在我的測驗環境中,它已經運行了幾個小時,沒有任何結果。
下面的代碼片段將回傳組,我無法讓服務器名稱過濾器作業。
Get-ADOrganizationalUnit -Properties CanonicalName -Filter *
| Sort-Object CanonicalName
| ForEach-Object { [pscustomobject]@ {
Name = Split-Path $_.CanonicalName -Leaf
CanonicalName = $_.CanonicalName
UserCount = @(Get-AdUser -Filter * -SearchBase $_.DistinguishedName -SearchScope OneLevel).Count
}
}
uj5u.com熱心網友回復:
我會這樣做:
- 首先查詢串列中的所有計算機。在這里,我假設計算機串列來自 CSV,并且計算機位于名為Computers的列中。
- 通過從DistinguishedName中洗掉 Common Name 來獲取計算機的組織單位:
(.... -split '(?=OU=)',2)[-1] - 將計算機物件添加到哈希表中,其中鍵是計算機的 OU。這將使我們只查詢每個 OU 一次。
- 遍歷哈希表鍵(OU 的 DistinguishedName),查詢它們的CanonicalName。
- 為每臺計算機創建一個具有所需屬性的新物件。
- 將結果匯出為 CSV。
# If it's a txt file instead:
# $computers = Get-Content path/to/computers.txt
$csv = Import-Csv path/to/csv.csv
$map = @{}
# If it's a txt file, instead:
# foreach($computer in $computers)
foreach($computer in $csv.Computers)
{
try
{
$adComputer = Get-ADComputer $computer
$ou = ($adComputer.DistinguishedName -split '(?=OU=)',2)[-1]
if($val = $map[$ou]) {
$map[$ou] = $val $adComputer
continue
}
$map[$ou] = , $adComputer
}
catch
{
Write-Warning $_.Exception.Message
}
}
$result = foreach($ou in $map.Keys)
{
$params = @{
Identity = $ou
Properties = 'canonicalName'
}
try
{
$canonical = Get-ADOrganizationalUnit @params
foreach($computer in $map[$ou])
{
[pscustomobject]@{
'Computer Name' = $computer.Name
'OU DistinguishedName' = $ou
'OU CanonicalName' = $canonical.CanonicalName
}
}
}
catch
{
Write-Warning $_.Exception.Message
}
}
$result | Export-Csv .... -NoTypeInformation
uj5u.com熱心網友回復:
像這樣的東西會起作用嗎?DistinguishedName過濾計算機名稱或通配符模式,然后使用計算機的和CanonicalName屬性獲取 OU 名稱和 OU 規范名稱:
$filter = "Name -eq 'SERVER01'" # exact name
# OR
$filter = "Name -like 'SERVER*'" # anything that starts with SERVER
Get-ADComputer -Filter $filter -Properties canonicalname |
select name,
@{ name = 'OU' ; expression = { [void]($_.DistinguishedName -match 'OU=. $'); $Matches[0] } },
@{ name = 'OU Canonical' ; expression = { $_.CanonicalName -replace "/$($_.Name)" } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414552.html
標籤:
