Question:
This script will do some processing on csv file notably removing first line (subsequent to How to export to “non-standard” CSV with Powershell ) :
1 2 3 4 5 6 7 |
Import-Csv in.csv -header Date,Time,O,H,L,C,V|select * -ExcludeProperty time| %{$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_}| ConvertTo-Csv -NoTypeInformation| select -skip 1| %{$_ -replace '"'}| Set-Content out.csv -encoding ascii |
Now I need to refine it by also removing last line. I tried to add :
select -skip ($_.Count – 1)
but it generates exception.
So what the right syntax ?
Answer:
Depending on the version of PowerShell you have, you can use the -SkipLast
parameter, e.g.:
1 2 |
... | Select -Skip 1 | Select -SkipLast 1 |
SkipLast
is available for PowerShell 5.0 and higher.
If you don’t have that parameter, you can install it via the Microsoft Website. Windows 7 is the earliest OS version that can run PowerShell 5.
If that’s not possible, use:
1 2 3 4 5 6 7 8 9 |
$csv = Import-Csv in.csv -header Date,Time,O,H,L,C,V | ` Select * -ExcludeProperty time | ` Foreach {$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_} | ` ConvertTo-Csv -NoTypeInformation for ($i = 1; $i -lt ($csv.Length - 1); $i++) { $csv[$i] -replace '"' | Add-Content out.csv -encoding ascii } |