如何使用 PowerShell 將 AD 使用者屬性匯出到 .csv 檔案?

如何使用 PowerShell 將 AD 使用者屬性匯出到 .csv 檔案?

.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 提供的工具為您編寫基線程式碼,並按原樣使用或根據需要進行調整。

不應使用 PowerShell 腳本中使用的別名,儘管它們對於互動式/一次性程式碼來說很好,這就是它們的目的。如果您確實在開發工作中使用它們,請務必在發布或共享之前將它們全部擴展。原因如下:

  1. 如果您在 VSCode 中開啟此程式碼,它會將任何別名視為錯誤,直到您展開它為止。
  2. 如果您針對它執行 PSScriptAnalyzer,它也會將它們稱為錯誤。

在 PowerShell 腳本中使用別名的最佳實踐

為什麼要先擔心別名呢?

無論如何,使用別名有什麼大不了的?如果它們使程式碼更容易輸入,那麼在腳本中使用它們有什麼害處?當涉及到腳本時,有兩件事在起作用。首先,不保證存在任何別名,即使是 Windows PowerShell 建立的別名也是如此。

使用 PSScriptAnalyzer 檢查您的 PowerShell 程式碼以獲得最佳實踐

相關內容