我正在撰寫一個函式,該函式將從 AD 組中獲取資訊并將其匯出到 csv 檔案中。我正在嘗試獲取用戶的名稱和描述,但輸出 CSV 中的幾個用戶缺少描述。這是我的代碼:
function Get-UserInfo{
param(
[Microsoft.ActiveDirectory.Management.ADGroup]$DomainName
)
Get-ADGroupMember -Identity $DomainName | #get the group of users specified
ForEach-Object { #For each object grabbed
$test = Get-ADUser -Identity $_ -Properties * | Select-Object Description,Name #grab the Name Description from each user
[pscustomobject] @{ #once data is grabbed send to custom object
Name = $test.Name
Description = $test.Description
}
} | Export-Csv -NoTypeInformation C:\Users\admin\Desktop\Test.csv #Export information into CSV
}
令人困惑的是如果我跑
Get-ADUser -Identity "User" -Properties *
在沒有描述的用戶之一的控制臺中,他們的描述會顯示出來。我認為這可能是我的流水線方式有問題,但我不確定。有人有什么建議嗎?
uj5u.com熱心網友回復:
我假設引數$DomainName實際上是指$GroupName.
當您只需要回傳兩個屬性時,不要使用,-Properties *因為在請求所有屬性時,您是在浪費時間和記憶體。
Get-ADGroupMember 可以回傳計算機、組或用戶型別的物件,因為您只需要用戶,所以應該過濾結果。
嘗試
# get all user objects that are member of the group and collect the data in variable $result
$result = Get-ADGroupMember -Identity $GroupName | # get the group of users specified
Where-Object { $_.objectClass -eq 'user' } | # filter users only (skip groups and computer objects
ForEach-Object {
# Get-ADUser by default returns these properties"
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
Get-ADUser -Identity $_.DistinguishedName -Properties Description |
# select and output the wanted properties as object.
# this will be collected in variable $result
Select-Object Name, Description
}
# now you can display on screen
$result | Format-Table -AutoSize
# and export to CSV
$result | Export-Csv -Path 'C:\Users\admin\Desktop\Test.csv' -NoTypeInformation
uj5u.com熱心網友回復:
試試這個,首先,AD Groups可以有用戶物件以外的成員,你需要過濾它們。我還建議您不要Export-Csv在函式內部對路徑 ( ) 進行硬編碼。
function Get-UserInfo{
param(
[parameter(ValueFromPipeline, Mandatory)]
[Microsoft.ActiveDirectory.Management.ADGroup]
$DomainName
)
@(Get-ADGroupMember -Identity $DomainName).Where({
$_.ObjectClass -eq 'user' # => Groups can have other object types
}) | Get-ADUser -Properties Description | # => Takes DN from pipeline
Select-Object Description, Name |
Export-Csv -NoTypeInformation C:\Users\admin\Desktop\Test.csv
}
Export-Csv您可以將其洗掉,而不是在函式內部,然后您可以對函式執行以下操作:
Get-ADGroup 'somegroup' | Get-UserInfo | Export-Csv path/to/csv.csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395659.html
