user3208164
user3208164

Reputation: 129

Delete first two columns in CSV with PowerShell

I need to delete the first two columns in a CSV. I do not know the header names, they are not static. I figured out how to remove the first two rows, but not the first two columns. The sample code I am working with is below

$csv     = Import-Csv 'input.csv'
$headers = $csv[0].PSObject.Properties | select -Expand Name
$step    = 4

for ($i = 0; $i -lt $headers.Count; $i += $step) {
  $csv | select $headers[$i..($i+$step-1)] |
    Export-Csv "output_$($i/$step).csv" -NoType
}

Upvotes: 1

Views: 3398

Answers (3)

Hunter Eidson
Hunter Eidson

Reputation: 1909

I think just changing the 0 in the for loop to a 2 should do it:

$csv     = Import-Csv 'input.csv'
$headers = $csv[0].PSObject.Properties | select -Expand Name
$step    = 4

for ($i = 2; $i -lt $headers.Count; $i += $step) {
  $csv | select $headers[$i..($i+$step-1)] |
    Export-Csv "new_output_$($i/$step).csv" -NoType
}

Upvotes: 2

mjolinor
mjolinor

Reputation: 68273

This seems to work:

$csv     = Import-Csv 'input.csv'
$include = $csv[0].psobject.properties | select -ExpandProperty Name -Skip 2
$csv | select $include -skip 2 | export-csv output.csv -NoTypeInformation

That should take care of pruning off the first 2 columns and then skipping the first 2 rows.

Upvotes: 2

Matt
Matt

Reputation: 46710

If you wanted to skip the first X columns you just need to adjust your $headers statement

$headers = $csv[0].PSObject.Properties | select -Skip 2 -Expand Name

The above would skip the first 2 columns by not processing the first 2 headers. The rest of the code will group columns of 4 after those 2.

Upvotes: 4

Related Questions