Home > database >  Excel/Powershell start a loop from row 2
Excel/Powershell start a loop from row 2

Time:10-27

Actually I have this loop :

foreach($line in Get-Content .\script2.csv) 
{ $firstname = $line.split(';')[0] 
 $lastname = $line.split(';')[1]
 $email = $line.split(';')[2]
 $newLine = "$firstname,""$lastname"",""$email"""
 $newLine >> newCSV.csv }

I use it to extract data and paste it in a correct format.

I would like to know what is the correct syntax to start it from the row 2 and not taking all my sheet ?

Thanks !

CodePudding user response:

Use Select -Skip $N to skip the first $N items of a collection:

foreach($line in Get-Content .\script2.csv |Select -Skip 1)
{
  $firstname = $line.split(';')[0] 
  $lastname = $line.split(';')[1]
  $email = $line.split(';')[2]
  $newLine = "$firstname,""$lastname"",""$email"""
  $newLine >> newCSV.csv
}

CodePudding user response:

If what you want to do is to convert a CSV file that uses the semi-colon ; as delimiter to a new Csv file that uses the comma , as delimiter, and in the process remove the header line from it, you can do:

Import-Csv -Path D:\Test\blah.csv -Delimiter ';' | ConvertTo-Csv | Out-String -Stream | Select-Object -Skip 1 | Set-Content -Path 'D:\Test\newCSV.csv'
  • Related