Removing lines from CSV file using Powershell
I have a CSV file with registration information. The date / time information in the file is recorded in UNIX stamp format.
I want to delete all lines older than 5 minutes. I use the following code for this:
$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300
$Content = Import-Csv "logfile.csv" | where {$_.DateCompleted -gt $FiveMinutesAgo}
$Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'
The CSV file looks like this:
"DateInitiated";"DateStarted";"DateCompleted";"InitiatedBy";"Action";"Status"
"1496659208";"1496659264";"1496752840";"administrator";"Reboot server";"Completed"
Regardless of whether those five minutes have passed or not, my CSV file ends up completely empty after executing the script lines above.
+3
source to share
1 answer
I couldn't replicate it when testing (but maybe the actual source file is needed). I think the problem is that you need to specify both the encoding and the separator by Import-CSV
, like Export on.
Try the following:
$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300
$Content = Import-Csv "test.csv" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo}
$Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'
+2
source to share