将不相关的列添加到export-csv -append

时间:2016-03-17 15:00:58

标签: loops powershell scripting export-to-csv

我有一个变量if(x <= 2) y = 1; else y = 0; x++; ,它包含Active Directory帐户名,以及每个帐户所属的AD组。变量目前看起来像这样:

Username1
group1
group2
group3
Username2
group1
group2
Username3
group1
group2
group3
…

现在,我想循环遍历$var。如果条目是用户名(所有这些都以adm开头,这很容易),请将其附加到CSV。如果它是一个组($var),请拉取组samaccountname,description和info,然后将其附加到同一个CSV。我将帐户名导出为CSV没有问题,使用循环将组信息单独导出到CSV没有问题。我认为一旦帐户名称在那里,将组信息导出到CSV就会出现问题;它似乎与标题或列名称有关。以下是我正在尝试使用的内容:

-notlike "adm*"

现在,我希望CSV看起来像这样:

Username1
group1name   group1description   group1info
group2name   group2description   group3info

Username2
group1name   group1description   group1info
group2name   group2description   group3info

这是我得到的错误:

Export-Csv : Cannot append CSV content to the following file:
c:\ahoy\supertest.csv. The appended object does not have a property that
corresponds to the following column: adm007. To continue with mismatched
properties, add the -Force parameter, and then retry the command.
At line:6 char:103
+ ... ription,info | Export-Csv c:\ahoy\supertest.csv -append -NoTypeInformation
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (adm007:String) [Export-Csv], InvalidOperationException
    + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell.Commands.ExportCsvCommand

是的,第一个帐户名是adm007。希望你们能帮助我。

1 个答案:

答案 0 :(得分:3)

您的数据格式不是CSV格式,因此我不建议使用*-Csv cmdlet进行处理。只需使用Out-File输出自定义格式的行:

$var | ForEach-Object { 
    if ($_ -like "adm*") {
        $_
    } else {
        $group = Get-ADGroup $_ -Properties samaccountname,description,info
        '{0} {1} {2}' -f $group.samaccountname, $group.description, $group.info
    }
} | Out-File 'C:\ahoy\supertest.txt'
相关问题