PowerShell Import-CSV“过滤掉空行”Export-CSV

问题描述 投票:2回答:2

我正在导出所有AD用户帐户,格式化为按照管理所需的方式排序的CSV文件。他们希望按部门字段排序并删除所有未列出部门代码的帐户。

我拼凑了一个脚本来获取格式化的CSV文件:

Import-Module ActiveDirectory

Get-ADUser -filter * -properties Name, Title, Department, SamAccountName |
    Select-Object GivenName, Surname, Title, Department |
    Export-CSV -Path "\\Server\Share\file.csv" -NoTypeInformation

'Filter only users with DEPARTMENT populated'
$BlankColumns = "Department"

Import-CSV \\JXWFILEPRD01\Les$\file.csv |
    Where-Object {
        $line = $_
        ($BlankColumns | ForEach-Object{
            ![string]::IsNullOrEmpty(($line.$_.Trim('"')))
        }) -notcontains $false
    } | Export-CSV -Path "\\Server\Share\out.csv"

但是,当我导入CSV并删除我们不想要的行时,它会将输出溢出到控制台。我还没弄明白如何以一种有效的方式使用Export-CSV。它要么出错,要么继续转储到控制台然后出错。

powershell csv active-directory
2个回答
2
投票

您可以多次导入/导出并在开始时过滤:

Import-Module -Name ActiveDirectory

Get-ADUser -Filter 'Department -like "*"' -Properties Name,Title,Department,SamAccountName |
    Select-Object -Property GivenName,Surname,Title,Department |
    Sort-Object -Property Department |
    Export-CSV -Path '\\Server\Share\file.csv' -NoTypeInformation

0
投票

试试这个:

Import-Module ActiveDirectory

Get-ADUser -filter * -Properties Name,Title,Department,SamAccountName  | where {![string]::IsNullOrWhiteSpace( $_.Department)} |
    Select GivenName, Surname, Title, Department | 
        Export-CSV "\\Server\Share\file.csv" -NoType
© www.soinside.com 2019 - 2024. All rights reserved.