PowerShell导出到csv。每行只引用1套

时间:2014-04-17 12:44:03

标签: powershell csv exchange-server double-quotes

当我构建CSV导出时,它会在每组参数周围添加引号。但是,我只想要1套报价。

$UserInfo = New-Object System.Object
foreach ($user in $MailBoxList)
{
  $UserInfo | Add-Member -Type NoteProperty -Name LegacyExchangeDN -Value $user.LegacyExchangeDN
  $UserInfo | Add-Member -Type NoteProperty -Name CloudEmailAddress -Value $CloudEmailAddress
  $UserInfo | Add-Member -Type NoteProperty -Name OnPremiseEmailAddress -Value $user.PrimarySMTPAddress.ToString()
  $UserInfo | Add-Member -Type NoteProperty -Name MailboxGUID -Value $user.ExchangeGUID

  $Users += $UserInfo
}

$Users | Export-CSV -Delimiter "," -Path ".\cloud.csv" -NoTypeInformation

此代码会导致导出CSV:

"LegacyExchangeDN","CloudEmailAddress","OnPremiseEmailAddress","MailboxGUID"
"/o=MyUnit/ou=This Admin Group (BRBIDOMF87SRQLT)/cn=Recipients/cn=a0dd27c5djd864108cfa61dj37dj56c6-MyLastName, M","mMyLastName@WhereverImFrom.Bob.com","mMyLastName@AnotherDomain.com","687efe5e-4690-110e-86a5-69fr4cdecf7e"

我想要的只是带有双引号的第一列数据,其余的没有:

"/o=MyUnit/ou=This Admin Group (BRBIDOMF87SRQLT)/cn=Recipients/cn=a0dd27c5djd864108cfa61dj37dj56c6-MyLastName, M",mMyLastName@WhereverImFrom.Bob.com,mMyLastName@AnotherDomain.com,687efe5e-4690-110e-86a5-69fr4cdecf7e

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你可以自己推动自己的" csv文件:

$Outfile = ".\cloud.csv"
'LegacyExchangeDN,CloudEmailAddress,OnPremiseEmailAddress' | Set-Content $Outfile

foreach($user in $MailBoxList)
{
  $Data = @(
             $user.LegacyExchangeDN,
             $CloudEmailAddress,
             $user.PrimarySMTPAddress.ToString()
            )

 '"{0}",{1},{2}' -f $Data | Add-Content $Outfile
}

答案 1 :(得分:0)

这是一个解决方案。它的作用是将对象转换为csv-strings,然后在将csv保存到文件之前修改它们。

foreach($user in $MailBoxList)
{
    $UserInfo = New-Object System.Object
    $UserInfo | Add-Member -Type NoteProperty -Name LegacyExchangeDN -Value $user.LegacyExchangeDN
    $UserInfo | Add-Member -Type NoteProperty -Name CloudEmailAddress -Value $CloudEmailAddress
    $UserInfo | Add-Member -Type NoteProperty -Name OnPremiseEmailAddress -Value 
    $user.PrimarySMTPAddress.ToString()

    $UserInfo | Add-Member -Type NoteProperty -Name MailboxGUID -Value $user.ExchangeGUID

    $Users += $UserInfo

}

#Convert to csv-formatted-strings
$csv = $Users | ConvertTo-Csv -NoTypeInformation -Delimiter ","

#Get header
$out = @($csv[0])

#Remove quotes for all but first column
$out += $csv[1..($csv.Length-1)] | % {

    [regex]::Match($_,'(^"[^"]*",)(.*)') | % { "{0}{1}" -f $_.Groups[1], $_.Groups[2].Value.Replace('"',"") }

}

$out | Set-Content -Path ".\cloud.csv"

另一个没有正则表达式的apporach:

#Remove quotes for all but first column
$out += $csv[1..($csv.Length-1)] | % {

    $values = $_ -split '","'
    $values[0] + '"' + $values[1..($values.Length-1)] -join ','

}