【发布时间】:2021-07-04 07:21:13
【问题描述】:
作为 Powershell 的初学者,我有一个无法解决的问题。我使用以下代码将不同 CSV 文件的平均值作为字符串:
# recovery of the list of csv files present in the folder "folder_1".
$files=(Get-ChildItem -path "C:\folder_1\" -Recurse -Include *.csv)
#loop to read each file and average the variables "PRESS_CELL" and "PRESS_DELTA
foreach($file in $files){
$varTemp = @((Get-Content $file | ConvertFrom-Csv | Measure-Object "PRESS_CELL","PRESS_DELTA" -Average | Export-Csv -Path "C:\folder_1\Alias.csv" -NoTypeInformation -Append))
Write-Host $varTemp
}
#added an increment to sort the data (averages)
$vartemp2 = Import-CSV "C:\folder_1\Alias.csv" | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } {
$_.LineNumber = $Line++
$_
} | Export-CSV "C:\folder_1\Alias2.csv" -NoTypeInformation
Write-Host $vartemp2
# sort data by "property" and by "LINENUMBER"
$vartemp3 = Import-Csv "C:\folder_1\Alias2.csv"
$vartemp3 | % { $_.LINENUMBER = [int]$_.LINENUMBER }
$vartemp3 | Sort-Object -Property @{ Expression = 'Property'; Ascending = $true }, @{ Expression = 'LINENUMBER'; Ascending = $true } |
Format-Table -Property "Average","Property","LINENUMBER"
# groups the values obtained in a table/customobject and export it to csv by column ?
$fields = [ordered]@{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average
}
$fields | export-csv C:\1_ICOS_data\Alias4.csv -Append ##DOESN'T WORK
[result][1]
但是,我想将结果导出为 CSV 表(每个结果 1 列,标题为 PRESS_CELL 和 PRESS_DELTA。当我使用管道时:
| export-csv C:\temp\alias.csv -Append
我得到一个结果:
带“有序”
"System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","False","System.Object","False"
还有 pscustomobject :
System.Object[],"System.Object[]"
【问题讨论】:
-
它返回一个数组吗?您可能必须在导出之前枚举它以获取字符串。试试
...Average | Out-String -
Average是在列Average中找到的所有值的数组。你想干什么?从所有这些值中创建一个平均值,或者 ?? -
您好,感谢您的帮助。我正在向您发送附加的完整代码。想法是读取文件夹中的所有 csv 文件并计算每列每个文件的平均值并将它们聚合到最终的 csv 文件中(每个文件在 1 分钟的时间步长上包含 30 分钟的数据,我想得到一个最终的csv 文件,其中包含每半小时的平均值)
-
感谢您的帮助!我得到这种类型:$fields| Get-Member TypeName : System.Collections.Specialized.OrderedDictionary 或 $fields |Get-Member TypeName : System.Management.Automation.PSCustomObject Name MemberType 定义 ---- ---------- ----- ----- PRESS_CELL NoteProperty Object[] PRESS_CELL=System.Object[] PRESS_DELTA NoteProperty Object[] PRESS_DELTA=System.Object[] 而且我想我需要在导出之前获取这两个变量的数组??
-
我希望在 csv 文件中的每列都有 $fields.PRESS_CELL 和 $fields_PRESS_DELTA。但我的印象是“值”在 powershell 结果中以逗号分隔的字符串给出: Name PRESS_CELL Value {45,6 , 46,7 , 248,9} 我想在我的 csv 中: PRESS_CELL 作为标题和 45,每行 6、46,7 和 248,9
标签: string powershell csv filesystemobject pscustomobject