【发布时间】:2019-03-11 19:19:58
【问题描述】:
我希望有人可以帮助我。我在 PowerShell 中构建了一个函数来导入具有两个标题行的分隔文件。我将两个标题行合并为一个,并在下面添加数据。这在 PowerShell 中运行良好:
$Delimiter = ";"
# Load 2nd and 3rd row which contain header informstion
$imData = (Get-Content -Path $csv_file | Select-Object -Skip 1 | select -First 2 ).split($Delimiter)
$columnsCount = $imData.Count/2
# Check if first row header is emtpy, if not, add information to second row
for($i=0; $i -lt $columnsCount;$i++){
if(![string]::IsNullOrEmpty($imData[$i].Substring(1,$imData[$i].Length-2))){
$imData[$i+$columnsCount] = $imData[$i] #.Substring(1,$imData[$i].Length-2)
}
}
$csvData = Get-Content -Path $csv_file | Select-Object -Skip 3
# Remove first row, second row contains header
$imData = $imData[$columnsCount..($imData.Length-1)]
$csvData = $csvData | ConvertFrom-Csv -Delimiter $Delimiter -WarningAction Ignore -Header $imData
最终的 $csvData 是正确的,我可以使用它。 但是,在 PowerShell Core 中它不起作用。它以 Get-Content 命令开始,该命令不会在每列的开头和结尾自动添加“。其次,当我在 PowerShell Core 中调用此代码时,它不会设置标头。实际上,它甚至没有像在 PowerShell 中那样创建正确的 csv 对象。在我的核心代码下面:
$delimiter = ";"
#[array]$header = ::new()
# Load 2nd and 3rd row which contain header informstion
[array]$imData = (Get-Content -Path $path | Select-Object -Skip 1 | Select-Object -First 2 ).split($delimiter)
# Set header count
$columnsCount = $imData.Count/2
# Check if first row header is emtpy, if not, add information to second row
for($i=0; $i -lt $columnsCount;$i++){
# Check if column header is empty
if(![string]::IsNullOrEmpty($imData[$i])){
#if(![string]::IsNullOrEmpty($imData[$i].Substring(1,$imData[$i].Length-2))){
$imData[$i+$columnsCount] = $imData[$i] #.Substring(1,$imData[$i].Length-2)
}
}
# Import CSV without header
$csvData = Get-Content -Path $path | Select-Object -Skip 3
# Remove first row, second row contains header
$imData = $imData[$columnsCount..($imData.Length-1)]
# Add header to CSV
$header = ((($imData -split (" " )))) | ConvertFrom-Csv -Delimiter $delimiter
$csvData = $csvData | ConvertFrom-Csv -Delimiter $delimiter -Header $header
$csvData = $header + $csvData
我已经尝试了不同的方法,但似乎没有任何效果。 我希望有人有黄金提示。 谢谢 斯蒂芬
【问题讨论】:
-
据我所知,
Get-Content不会自动在列中添加引号。为什么你认为会这样? -
我很抱歉。让所有人都同意我很愚蠢。我的错误是我用管道 Out-Null 调用了该函数,这就是为什么没有返回任何值...我在下面添加了完整的代码
-
不用担心,@Stephan - 虽然如果您一开始就尝试提供MCVE (Minimal, Complete, and Verifiable Example),您可能在提问之前就发现了错误。鉴于您的问题不太可能使未来的读者受益,我可以建议您删除它吗?
标签: powershell