这并不完全是传统意义上的 CSV 文件。鉴于您对文件内容的描述,我想您已经知道这一点。
如果 datetime,temp truly 行中没有任何双引号,根据您的示例数据,那么以下脚本应该可以工作。该脚本是自包含的,因为它内联声明了示例数据。
重要提示:您需要修改包含$SensorList 变量声明的行。您必须使用传感器名称填充此变量,或者您可以参数化脚本以接受传感器名称数组。
更新:我更改了要参数化的脚本。
结果
脚本运行结果如下:
- sensor1.csv(带有相应数据)
- sensor2.csv(带有相应数据)
- 一些绿色文本将写入 PowerShell 主机,指示当前检测到哪个传感器
脚本
脚本的内容应如下所示。将脚本文件保存到文件夹,如c:\test\test.ps1,然后执行。
# Declare text as a PowerShell here-string
$Text = @"
"readerinfo","onlylistedonce"
"downloadinfo",YYYY/MM/DD 00:00:00
"timezone",-8
"headerstuff","headersuff"
"sensor1","sensorstuff"
"serial#","0000001"
"about15lines","ofthisstuff"
"header1","header2"
datetime,tempfromsensor1
datetime,tempfromsensor1
datetime,tempfromsensor1
"sensor2","sensorstuff"
"serial#","0000002"
"about15lines","ofthisstuff"
"header1","header2"
datetime,tempfromsensor2
datetime,tempfromsensor2
datetime,tempfromsensor2
"downloadcomplete"
"@.Split("`n");
# Declare the list of sensor names
$SensorList = @('sensor1', 'sensor2');
$CurrentSensor = $null;
# WARNING: Clean up all CSV files in the same directory as the script
Remove-Item -Path $PSScriptRoot\*.csv;
# Iterate over each line in the text file
foreach ($Line in $Text) {
#region Line matches double quote
if ($Line -match '"') {
# Parse the property/value pairs (where double quotes are present)
if ($Line -match '"(.*?)",("(?<value>.*)"|(?<value>.*))') {
$Entry = [PSCustomObject]@{
Property = $matches[1];
Value = $matches['value'];
};
if ($matches[1] -in $SensorList) {
$CurrentSensor = $matches[1];
Write-Host -ForegroundColor Green -Object ('Current sensor is: {0}' -f $CurrentSensor);
}
}
}
#endregion Line matches double quote
#region Line does not match double quote
else {
# Parse the datetime/temp pairs
if ($Line -match '(.*?),(.*)') {
$Entry = [PSCustomObject]@{
DateTime = $matches[1];
Temp = $matches[2];
};
# Write the sensor's datetime/temp to its file
Add-Content -Path ('{0}\{1}.csv' -f $PSScriptRoot, $CurrentSensor) -Value $Line;
}
}
#endregion Line does not match double quote
}