Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell skip first 2 lines of txt file when importing it

Tags:

powershell

I have a powershell script designed to read a txt file on a remote server and import it into SQL.

I want to be able to skip the first 2 lines of the txt file. I am currently using the code below to import the file. The txt file is delimited

$datatable = new-object System.Data.DataTable
$reader = New-Object System.IO.StreamReader($empFile)     
$columns = (Get-Content $empfile -First 1).Split($empFileDelimiter) 

    if ($FirstRowColumnNames -eq $true) 

        { 
            $null = $reader.readLine() 

        } 

    foreach ($column in $columns) 

        {  
            $null = $datatable.Columns.Add() 
        } 

    # Read in the data, line by line, not column by column 
    while (($line = $reader.ReadLine()) -ne $null)  

        { 

            $null = $datatable.Rows.Add($line.Split($empFiledelimiter)) 

The column parameter takes the first line of the txt file and creates the columns for the PS datatable.

The problem I have is the first two lines of the txt file are not needed and I need to skip them and use the third line of the txt file for the columns. I have the following line of code which will do this but I am uncertain how to integrate it into my code.

get-content $empFile | select-object -skip 2 
like image 820
Silentbob Avatar asked Dec 18 '15 09:12

Silentbob


3 Answers

Create an array for the $empfile without the first two lines, then use the first item of the array for the Columns, like this:

$Content = Get-Content $empFile | Select-Object -Skip 2 
$columns = $Content[0].Split($empFileDelimiter)
like image 175
Avshalom Avatar answered Sep 30 '22 12:09

Avshalom


just a quick one liner

(Get-Content $empFile| Select-Object -Skip 2) | Set-Content $empFile
like image 20
N.R. Avatar answered Sep 30 '22 12:09

N.R.


Put in two unused calls to ReadLine(). Something like this:

$datatable = new-object System.Data.DataTable
$reader = New-Object System.IO.StreamReader($empFile)
$reader.ReadLine()
$reader.ReadLine()
$columns = ($reader.ReadLine()).Split($empFileDelimiter) 
...
like image 42
Brian O''Byrne Avatar answered Sep 30 '22 12:09

Brian O''Byrne