将csv文件中的记录转换为字符串(如果打开为.txt文件将显示什么)

时间:2016-03-16 00:45:47

标签: powershell powershell-v3.0

我想要的应该是非常简单。

我使用的csv文件:

"SamAccountName","sn","GivenName"
"PBrain","","Brain"
"JSteward","John","Steward"
"JDoe","John","Doe"
"SDoo","Scooby","Doo"

我的代码:

$baseFileCsvContents = Import-Csv $baseFile

$baseFileCsvContents | ForEach-Object {
    $baseSameAccountName = $_.SamAccountName
    [String]$mergedLineInFile = $_ | Out-String

    Write-Host '$mergedLineInFile =' $mergedLineInFile
    Exit
}

输出:

SamAccountName                                  sn                                             GivenName
--------------                                  --                                             ---------
PBrain                                                                                         Brain

预期产出:

"PBrain","","Brain"

任何人都可以帮助我吗?请?

1 个答案:

答案 0 :(得分:2)

这比将对象管道化为字符串要复杂一些。您必须评估PSObject的每个属性,表示CSV中的一行,然后将值转换为字符串。

$baseFileCsvContents = Import-Csv $BaseFile
$properties = $baseFileCsvContents[0] | get-member -MemberType NoteProperty | Select-Object Name | %{$_.Name.ToString()}
foreach ($item in $baseFileCsvContents) {
    $mergedLineArray = $properties | %{'"' + $item.$($_) + '"'} 
    $mergedLineInFile = $mergedLineArray -join ','
    Write-Host '$mergedLineInFile =' $mergedLineInFile
}