I have a .txt file that looks like this (These are only the first few lines):
2003.09.23.,05:05:21:64,134,177,101
2009.03.10.,17:46:17:81,57,102,57
2018.01.05.,00:30:37:04,354,145,156
2011.07.11.,23:21:53:43,310,125,47
2011.06.26.,07:42:10:30,383,180,171
2014.01.24.,04:56:59:60,238,2,65
2012.07.28.,17:40:45:53,341,16,69
2006.03.17.,19:31:56:27,116,185,85
2006.12.28.,22:44:11:00,374,62,39
2009.08.03.,05:22:41:73,238,109,83
I've successfully written a program that reads the file line by line and splits the contents at the commas, however it's not storing the different values in the specified arrays the way I want it to.
foreach($line in Get-Content .\auto.txt) {
if($line -match $regex){
$splitline = $line.Split(",")
#Write-Host $splitline[0]
$date = $splitline[0]
$time = $splitline[1]
$speed = $splitline[2]
$distancefront = $splitline[3]
$distanceback = $splitline[4]
}
}
The commented Write-Host $splitline[0]
command above returns 2003.09.23.
the way it should, however if I call the first element of the array with Write-Host $date[0]
, it returns 2
. It seems to be storing the date character by character. I'm new to powershell, could anyone please give me some guidance for how to get around this? Thank you in advance.
CodePudding user response:
You need to assign an empty array to the variables before you start using the addition operator - otherwise PowerShell will go "Huh, $null "some string"
, that's gonna result in "some string"
", and you'll end up with a string instead of an array.
$date = @()
$time = @()
$speed = @()
$distancefront = @()
$distanceback = @()
foreach($line in Get-Content .\auto.txt) {
if($line -match $regex){
$splitline = $line.Split(",")
#Write-Host $splitline[0]
$date = $splitline[0]
$time = $splitline[1]
$speed = $splitline[2]
$distancefront = $splitline[3]
$distanceback = $splitline[4]
}
}
The more idiomatic approach, however, would be to offload parsing completely to ConvertFrom-Csv
or Import-Csv
- this way you'll end up with a single array of objects (1 per row), instead of 5 disjointed arrays with the individual column values:
$data = Import-Csv .\auto.txt -Header Date,Time,Speed,DistanceFront,DistanceBack
After which you can do:
PS ~> $data[0]
Date : 2003.09.23.
Time : 05:05:21:64
Speed : 134
DistanceFront : 177
DistanceBack : 101
PS ~> $data[0].Date
2003.09.23.
PS ~> $data[0].Time
05:05:21:64