powershell - 将包含 PowerShell 对象表示法的文本文件转换为 CSV

标签 powershell export-to-csv

我有一个包含 PowerShell 对象表示法的文本文件 (PsonObjects.txt),如下所示:

@{Computer=Dektop123; ServiceA=Running; ServiceB=Running; RunspaceId=1a-1b}
@{Computer=Dektop456; ServiceA=Stopped; ServiceB=Stopped; RunspaceId=2b-2c}
@{Computer=Laptop123; ServiceA=NotFound; ServiceB=Running; RunspaceId=3c-4c}
@{ServiceA=NotFound; Computer=Laptop456; ServiceB=Running; RunspaceId=4d-5d}

我想将此 Pson 文件转换为 Csv 文件,但一直无法成功。

问题是有时一个对象的属性顺序与前一个对象的顺序不同。就像上面例子中的最后一行。因此,简单地将分号 (';') 转换为逗号 (',') 并删除 '@{}' 字符不会生成正确排序的 Csv 文件。

有没有一种简单的方法可以将此 Pson(Powershell 对象表示法)文件转换为 CSV 文件?

我尝试了几种不同的方法,但我一直在我的 CSV 输出文件中获取字符串的长度或哈希表输出(IsReadOnly、IsFixedSize、IsSychronized、keys、Values、SyncRoot、Count)。

非工作代码:

$inputFile = PsonObjects.txt
$CsvFileName = CsvOutput.csv
foreach($line in (Get-Contnet $inputfile)){
  $newline = $line | convertFrom-StringData
  $newline | Export-CSV $CsvFileName -Append 
} 

感谢任何有关此问题的帮助或建议。

最佳答案

ConvertFrom-StringData 输出一个未排序的Hashtable,其中元素可以是任意顺序,所以在这里没有用。

这是一个可能的解决方案,使用 -split 运算符和排序步骤,使用 ordered Hashtable:

$inputFile = 'PsonObjects.txt'
$csvFileName = 'CsvOutput.csv'

# The order of columns in the output CSV
$keyOrder = 'Computer','ServiceA','ServiceB','RunspaceId'

Get-Content $inputfile | ForEach-Object {
    $line = $_.Trim('@{}')   # Remove unwanted characters from current line

    # First parse the current line into an unordered hashtable
    $ht = @{}
    foreach( $field in $line -split '; ' ) {
        $key, $value = $field -split '='
        $ht[ $key ] = $value
    }   

    # Using the order specified by $keyOrder, create an ordered hashtable
    $orderedHt = [ordered] @{}
    foreach( $key in $keyOrder ) {
        $orderedHt[ $key ] = $ht[ $key ]
    }

    [PSCustomObject] $orderedHt     # Convert hashtable to custom object

} | Export-Csv $csvFileName

输出:

"Computer","ServiceA","ServiceB","RunspaceId"
"Dektop123","Running","Running","1a-1b"
"Dektop456","Stopped","Stopped","2b-2c" 
"Laptop123","NotFound","Running","3c-4c"
"Laptop456","NotFound","Running","4d-5d"

关于powershell - 将包含 PowerShell 对象表示法的文本文件转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72883926/

相关文章:

Powershell DSC : Run regular code in DSC

powershell - 新对象不能包含破折号(-),但可以包含 “needs to”

c# - 将图像导出为 CSV

javascript - 使用 Javascript 将 JSON 转换为 CSV 不会给出 key

database - 将 postgres 表导出到 csv 错误

Powershell导入模块找不到模块

arrays - 显示数组中的重复值

powershell - ValidateSet 带空格的值

powershell - 从 powershell 部署 Service Fabric。错误 -> 获取 ServiceFabricClusterManifest : Cluster connection instance is null

r - R 中的 write.csv 将我的日期转换为 10 位整数