9

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 
Silentbob
  • 2,805
  • 7
  • 38
  • 70

3 Answers3

21

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)
Avshalom
  • 8,657
  • 1
  • 25
  • 43
5

just a quick one liner

(Get-Content $empFile| Select-Object -Skip 2) | Set-Content $empFile
N.R.
  • 230
  • 3
  • 11
3

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) 
...
Brian O''Byrne
  • 550
  • 2
  • 10