powershell 如何将结果导出到同一个EXCEL表中?

2lpgd968  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(222)

我必须提取3个组织单位中属性为空的活动帐户。然而,我希望结果显示在同一个EXCEL文件中。能帮我解决这个问题吗?

$date = Get-Date -Format yyyy-MM-dd
$path = "c:\temp\empty_attributes.xlsx"

$OU1 = "OU=Accounts,DC=com,DC=contoso"
$OU2 = "OU=TestAccounts,DC=com,DC=contoso"
$OU3 = "OU=Users,DC=com,DC=contoso"

Get-ADUser -Filter {-not(employeeNumber -like "*") -and (Enabled -eq "True") }  -SearchBase $OU1 -Properties * | select name, samaccountname, employeeNumber | Export-excel -Path $path -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2

Get-ADUser -Filter {-not(employeeNumber -like "*") -and (Enabled -eq "True") }  -SearchBase $OU2 -Properties * | select name, samaccountname, employeeNumber | Export-excel -Path $path -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2

Get-ADUser -Filter {-not(employeeNumber -like "*") -and (Enabled -eq "True") }  -SearchBase $OU3 -Properties * | select name, samaccountname, employeeNumber | Export-excel -Path $path -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2
7fyelxc5

7fyelxc51#

只需在一个管道中处理它,而不是为每个组织单位拥有多个变量,而是将它们全部存储在一个数组中,然后对其进行循环:

$date = Get-Date -Format yyyy-MM-dd
$path = "c:\temp\empty_attributes.xlsx"

$OUs = @(
    "OU=Accounts,DC=com,DC=contoso"
    "OU=TestAccounts,DC=com,DC=contoso"
    "OU=Users,DC=com,DC=contoso"
)

$params = @{
    LDAPFilter = '(&(!userAccountControl:1.2.840.113556.1.4.803:=2)(!employeeNumber=*))'
    Properties = 'employeeNumber'
}

$OUs | ForEach-Object { Get-ADUser @params -SearchBase $_ } |
    Select-Object name, samaccountname, employeeNumber |
    Export-excel -Path $path -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2

您还需要考虑停止使用-Properties *,只使用您需要查询的特定属性,否则您的查询将非常低效。

相关问题