PowerShell foreach循环以CSV格式导出到新列

时间:2015-04-30 16:46:02

标签: powershell csv export-to-csv

我目前正在处理一个CSV文件,该文件包含经理的员工编号,但不包含他们的SAMAccountName。我想利用Get-ADUser从EmployeeNumber属性中获取经理的SAMAccountName,并将其放在同一个CSV文件中的新列中。

CSV示例:

"Full Name","Username","Manager","Manager User Sys ID"
"User 1","u1","1, Manager","123456"
"User 2","u2","2, Manager","234567"
"User 3","u3","3, Manager","345678"

我想:

"Full Name","Username","Manager","Manager User Sys ID","Manager SamAccountName"
"User 1","u1","1, Manager","123456","m1"
"User 2","u2","2, Manager","234567","m2"
"User 3","u3","3, Manager","345678","m3"

我花了一些时间整理下面的代码。我可以添加一个新列,可以进一步获取SAMAccountName,但它只导出新CSV文件中的一行,如下所示:

"SAMAccountName","managerUsername"
"m1","@{SAMAccountName=m1}"

以下是代码:

$managers = Import-Csv -Path .\test.csv
$usermananger = @()
foreach ($manager in $managers)
{
  $getmanagersam = Get-ADUser -Filter "employeeNumber -eq $($manager."Manager User Sys ID")" -Properties SAMAccountName |
    Select-Object SAMAccountName
  $exportstring = $testmanager |
    Select-Object *,@{Name='managerUsername';Expression={"$getmanagersam"}}
  $exportstring | Export-Csv -Path .\simpletest.csv -NoTypeInformation
}

3 个答案:

答案 0 :(得分:1)

正如@ MathiasR.Jessen在评论中提到的:您需要展开{​​{1}}属性才能获得该值。此外,您每次迭代都会覆盖输出CSV。可以附加到文件,也可以将SamAccountName cmdlet移动到循环外部。前者需要PowerShell v3或更高版本,后者要求您将循环更改为Export-Csv循环(或在子表达式中运行ForEach-Object循环)。

我个人更喜欢使用管道,所以我选择后者:

foreach

答案 1 :(得分:0)

简短的回答是在-Append语句中添加export-csv选项,以阻止每次循环覆盖。

或者将导出移出循环外部,如下所示:

$managers = Import-Csv -Path .\test.csv

$managers|foreach-object{
  $getmanagersam = Get-ADUser -Filter "employeeNumber -eq $($_.'Manager User Sys ID')" | select -ExpandProperty SAMAccountName
  $_|Select *,@{Name='managerUsername';Expression=$getmanagersam}
} | Export-Csv -Path .\simpletest.csv -NoTypeInformation

注意:看起来像@AnsgarWiechers一样打败了我: - )

答案 2 :(得分:0)

我在派对上看起来很晚,但很少阻止我...我不是通过CREATE TABLE CENSUS_MSA_DROPDOWN ( OID number(15), CityName VARCHAR(60) CONSTRAINT census_msa_dropdown_pk PRIMARY KEY, StateCode CHAR(2)); select OID,SUBSTR(Basename,1, INSTR(Basename,',',1)-1), substr(basename,LENGTH(basename)-1,2) from CENSUS_MSA; cmdlet添加属性的忠实粉丝,所以我'我将提供一个替代方案,将CSV管道传输到Select循环(就像其他答案一样),但在其中你使用ForEach-Object Add-Member参数,然后管道它关闭到输出文件。我将在管道后添加一个新行和缩进,以便于阅读。

-PassThru

这应该基本上与其他两个答案完全相同,它只是以不同的方式添加属性,因为多样性是生活的调味品! (我在互联网上看到过,所以一定是真的。)