【问题标题】:PowerShell Import-CSV "filter out blank rows" Export-CSVPowerShell Import-CSV “过滤掉空白行” Export-CSV
【发布时间】:2018-06-03 05:52:28
【问题描述】:

我正在导出所有 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


    【解决方案1】:

    您无需多次导入/导出并在开始时进行过滤:

    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
    

    【讨论】:

    • 谢谢你,这很完美,我真的理解它是如何工作的! (奖金)
    【解决方案2】:

    试试这个:

    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
    

    【讨论】:

    • 这不会出错,但是 CSV 文件是空的。
    • 获取 ADUser -filter * | {![string]::IsNullOrWhiteSpace($_.Department)} 在哪里打印一些东西?
    • 抱歉耽搁了……生活发生了……我跑了 Get-ADUser -filter * |其中 {![string]::IsNullOrWhiteSpace( $_.Department)} 它在某些东西上工作了 20 秒左右,然后返回命令提示符。所以它正在做一些事情,但没有输出。
    • ok 然后添加 -Properties Name,Title,Department,SamAccountName(我已经修改了我的代码)
    猜你喜欢
    • 2017-10-19
    • 2016-01-07
    • 2021-03-11
    • 2022-01-21
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多