2016-02-01 57 views
1

PowerShell的表我有一个文件,内容如下所示:如何从文件中读取

File Versions    
---- --------    
aaa {1.0.0.123, 1.0.0.124} 
bbb {1.0.0.123, 1.0.0.124} 

如何在PowerShell中读入表,或类型数组?

我创建了这个脚本文件:

$versions = $dictionary | ForEach-Object{ 
    $properties = @{ 
     File = $dictionary.Key 
     Versions = $dictionary.Value <# an array of strings #> 
    } 
    New-Object PSObject -Property $properties 
} 

$versions | Out-File "filesVersions.txt" 

脚本不再使用。这只是为了展示filesVersions.txt文件中的内容。

我真正想要的是将一个键值对存储在一个文件中,其中键是FileName,值是版本列表。

有时我需要读取文件内容,将所有新行或新版本读到现有行并保存回去。

我想为它使用Format-Table输出。

+2

看起来您已将'Format-Table'输出保存到文件中。你对这个输出有控制吗?解决这个问题然后解析它现在会更容易。或者它实际上是一个CSV文件,您可以使用'Import-CSV“filesVersions.csv”'。或者这是一个大文件,这就是为什么你使用'ReadAllLines'? – Matt

+0

什么是$版本? – Matt

+0

看到我的编辑更多一点解释。不管什么是filesVersions.csv或$ dictionary,因为它不再存在。这只是我的测试数据,我将它保存到一个文件中,然后我想将其读回。 – Liero

回答

1

我想为它使用Format-Table输出。对不起,但这不是你应该这样做的方式。你正在增加很多不必要的开销。你正在寻找字符串解析哪个可能是不可靠和乏味的。

PowerShell的权力来自对象。在这种情况下使用Export-CSV将是理想的。但是,您需要对该阵列进行双向操作。

$versions = $dictionary | ForEach-Object{ 
    $properties = @{ 
     File = $dictionary.Key 
     Versions = $dictionary.Value -join "|" 
    } 
    New-Object PSObject -Property $properties 
} 

$versions | Export-Csv "filesVersions.csv" -NoTypeInformation 

当您将数据导回到PowerShell中以获取对象时,您需要拆分该字段以获取数组。

Import-Csv "filesVersions.csv" | ForEach-Object{ 
    # Update the property 
    $_.Versions = $_.Versions -split "|" 
    # Send the updated object down the pipe 
    $_ 
} 

或使用计算性能

Import-Csv "filesVersions.csv" | Select-Object File,@{Name="Versions";Expression={$_.Versions -split "|"}} 

Mathias says你也可以使用Export-CLIXML,你不会需要做的加入或任何东西。我个人认为这是更复杂的输出,那么你在这里做什么。