
.csv
我在將 AD 使用者屬性匯出到屬於特定 AD 群組成員的檔案時遇到問題。
這是我的程式碼
$ExportPath= "C:\Users\group_list.csv"
$groupname = "group1"
$users = Get-ADGroupMember -Identity $groupname | ? {$_.objectclass -eq "user"}
foreach ($activeusers in $users) { Get-ADUser -Identity $activeusers | ? {$_.enabled -ne $true} | select Name, SamAccountName, UserPrincipalName, enabled, DistinguishedName | Format-Table} Export-Csv $ExportPath }
答案1
您應該只$Users
在選擇所需屬性的管道中提供變量,然後將其管道傳輸到.csv
檔案。
$ExportPath = "C:\Users\group_list.csv"
$GroupName = "group1"
$Users = Get-ADGroupMember -Identity $GroupName | ? {$_.objectclass -eq "user"}
$Users | ? {$_.enabled -ne $true} | select Name, SamAccountName, UserPrincipalName, enabled, DistinguishedName | Export-Csv $ExportPath
答案2
您發布的內容有語法問題
$ExportPath = 'C:\Users\group_list.csv'
$groupname = 'group1'
$users = Get-ADGroupMember -Identity $groupname |
Where-Object {$_.objectclass -eq 'user'}
foreach ($activeusers in $users)
{
Get-ADUser -Identity $activeusers |
Where-Object {
$_.enabled -ne $true} |
Select-Object Name,
SamAccountName,
UserPrincipalName,
enabled,
DistinguishedName |
Format-Table
} Export-Csv $ExportPath
快速重構您發布的程式碼。
$ExportPath = 'C:\Users\group_list.csv'
$groupname = 'group1'
$users = Get-ADGroupMember -Identity $groupname |
Where-Object {$_.objectclass -eq 'user'}
foreach ($activeuser -in $users)
{
Get-ADUser -Identity $activeuser |
Where-Object {
$PSItem.enabled -ne $true} |
Select-Object Name,
SamAccountName,
UserPrincipalName,
enabled,
DistinguishedName |
Export-Csv $ExportPath -NoTypeInformation -Append
}
“Zoran Jankov”給出的是更直接/更少的程式碼,但請務必添加“-NoTypeInformation”,否則您最終會在輸出中獲得一些您不想要的額外文字。
供參考...
使用 MS 提供的工具為您編寫基線程式碼,並按原樣使用或根據需要進行調整。
- Active Directory 管理中心:入門
- 活動目錄管理中心
- windows“活動目錄管理中心”
- windows“Active Directory 管理中心”“PowerShell 歷史記錄檢視器”
- Active Directory 管理中心簡介
- 使用AD管理中心建立PowerShell命令
- 步驟:在 Windows Server 2012 R2 中使用 PowerShell 歷史記錄檢視器
- 使用 Active Directory 管理中心學習 PowerShell(PowerShell 歷史記錄檢視器)
不應使用 PowerShell 腳本中使用的別名,儘管它們對於互動式/一次性程式碼來說很好,這就是它們的目的。如果您確實在開發工作中使用它們,請務必在發布或共享之前將它們全部擴展。原因如下:
- 如果您在 VSCode 中開啟此程式碼,它會將任何別名視為錯誤,直到您展開它為止。
- 如果您針對它執行 PSScriptAnalyzer,它也會將它們稱為錯誤。
在 PowerShell 腳本中使用別名的最佳實踐
- https://devblogs.microsoft.com/scripting/best-practice-for-using-aliases-in-powershell-scripts
- https://devblogs.microsoft.com/scripting/using-powershell-aliases-best-practices
為什麼要先擔心別名呢?
無論如何,使用別名有什麼大不了的?如果它們使程式碼更容易輸入,那麼在腳本中使用它們有什麼害處?當涉及到腳本時,有兩件事在起作用。首先,不保證存在任何別名,即使是 Windows PowerShell 建立的別名也是如此。