更改Export-CSV输出输出格式

时间:2013-08-05 17:59:46

标签: powershell export-to-csv

我正在开发一个PowerShell脚本,它将使用Export-Csv命令将系统管理员列表输出到CSV文件。获取数据的脚本部分是:

Foreach ($Computer in $Computers){
  $Online = Test-Connection -ComputerName $Computer -Quiet
  if ($Online -eq "True"){
    $GroupName = Get-WmiObject win32_group -ComputerName $Computer | ? {$_.SID -eq 'S-1-5-32-544'} | Select-Object name -ExpandProperty name
    $LocalGroup =[ADSI]"WinNT://$Computer/$GroupName"
    $GroupMembers = @($LocalGroup.psbase.Invoke("Members"))
    $Members = $GroupMembers | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
    foreach ($Member in $Members){
      $obj = New-Object System.Object
      $obj | Add-Member -MemberType NoteProperty -Name "Computer" -Value $Computer
      $obj | Add-Member -MemberType NoteProperty -Name "AdminGroupMembers" -Value $Member
      $obj
    }
  }
}

}

Get-Admins | Export-Csv -NoTypeInformation c:\scripts\adm.csv -Encoding UTF8

当前输出格式如下:

"Computer1", "Admin1"
"Computer1", "Admin2"
"Computer1", "Admin3"
"Computer1", "Admin4"
"Computer2", "Admin1"
"Computer2", "Admin2"
"Computer3", "Admin1"

我试图让输出看起来像这样:

"Computer1", "Admin1" , "Admin2" , "Admin3" , "Admin4"
"Computer2", "Admin1" , "Admin2"  
"Computer3", "Admin1" , "Admin2" , "Admin3"

任何想法?

1 个答案:

答案 0 :(得分:1)

您的输出格式不是CSV格式,因此Export-Csv不适合您。试试这个:

Get-Admins | group { $_.Computer } | % {
  '{0},{1}' -f @($_.Group.Computer)[0], ($_.Group.AdminGroupMembers -join ',')
} | Out-File 'output.csv'

对于PowerShell v2,您需要手动展开组属性:

Get-Admins | group { $_.Computer } | % {
  $computer = @($_.Group | select -Expand Computer)[0]
  $admins   = ($_.Group | select -Expand AdminGroupMembers) -join ','
  '{0},{1}' -f $computer, $admins
} | Out-File 'output.csv'