【问题标题】:Output to CSV include commas输出到 CSV 包括逗号
【发布时间】:2016-12-05 22:43:38
【问题描述】:

下面的代码旨在列出特定父支持组的所有成员。我想将“成员”数组中的所有值分开,并将这些逗号包含在输出到 CSV 中。我该怎么做?

Set-ExecutionPolicy Bypass -Force

#Report start of script actions.
Write-Output "Discovering Security Group members..."

# Install Remote Server Administration Tools if not already installed.
if (!(Get-Module -ListAvailable -Name ActiveDirectory)) {
    Install-WindowsFeature RSAT-AD-PowerShell
}

# Import the ActiveDirectory module.
Import-Module ActiveDirectory

#Prevent truncated output of objects in the Members array.
$FormatEnumerationLimit = -1

#Define the Export-CSV output location.
$OutputFile = "$home\Desktop\Web_Filtering_Group_memberships_" + (Get-Date -Format "M.d.yyyy-HHmm") + ".csv"

#Prevent truncated output of arrays.
$FormatEnumerationLimit = -1

#Discovering Security Group members.
Get-ADGroup -SearchBase 'OU=Parent Group,OU=Security Groups,DC=domain,DC=com' -Filter * -Properties * |
    Select-Object -Property Name, Description, GroupCategory,
        @{Name='Members';exp={
            Get-ADGroupMember $_.SamAccountName | Select -ExpandProperty SamAccountName
        }} |
    Export-CSV -NoTypeInformation $OutputFile

#Report end of script actions.
Write-Output "Discovery of all Web Filtering Group members is complete. Output saved to: $OutputFile"

【问题讨论】:

    标签: arrays csv powershell


    【解决方案1】:

    只需将成员加入逗号分隔的字符串:

    ... | Select-Object Name,Description,GroupCategory,@{n='Members';e={
      (Get-ADGroupMember $_.SamAccountName | Select -Expand SamAccountName) -join ','
    }} | Export-Csv ...
    

    Export-Csv 将所有导出的字段放在双引号中,因此您将获得如下输出:

    "名称","描述","组类别","成员"
    ...“富,酒吧,巴兹”
    ...,“一些”
    ...,"或,其他"

    字符串值中的嵌套逗号是有效的 CSV。

    【讨论】:

    • 太棒了!正是我需要的。谢谢。
    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多