Powershell SQL删除最后一行

时间:2017-08-14 15:34:14

标签: sql powershell

我有多个需要在SQL Server管理工作室中导入的文本文件。我在powershell中编写了一个代码来导入某些文件。但我有一个文件,其中一行只包含' ---------------------------------- -----'

例如

test | test2 | test3

A | B | C

Q | W |ë

' -----------'

有没有办法忽略或跳过这一行。我已经尝试过select-object -skiplast 1

Function AutoImportCommaFlatFiles($location, $file, $extension, $server, $database)
{
    $full = $location + $file + $extension
 ##   $columns = Get-Content $full | Select-Object -skip 1 | set-Content $full
    $all = Get-Content $full | select-Object -skip 3 
    $columns = $all[0] 
    $columns = $columns.Replace(" ","")
    $columns = $columns.Replace("||","Column Emtpy|Column Empty 2|")
     $columns = $columns.Replace("","Column Emtpy3")
     $columns = $columns.TrimEnd('|') 
     $columns = $columns.Replace("|","] VARCHAR(100), [")
    $table = "CREATE TABLE " + $file + "([" + $columns + "] VARCHAR(100))"
    $connection = New-Object System.Data.SqlClient.SqlConnection
    $buildTable = New-Object System.Data.SqlClient.SqlCommand
    $insertData = New-Object System.Data.SqlClient.SqlCommand
    $connection.ConnectionString = "Data Source=" + $server + ";Database=" + $database + ";integrated security=true"
    $buildTable.CommandText = $table
    $buildTable.Connection = $connection
    ## Added to function;
    $x = 0
    $insertData.CommandText = "EXECUTE stp_CommaBulkInsert @1,@2"
    $insertData.Parameters.Add("@1", $full)
    $insertData.Parameters.Add("@2", $file)
    $insertData.Connection = $connection
    $connection.Open()
    $buildTable.ExecuteNonQuery()
    $connection.Close()
    ## Added to function
    $x = 1
    if ($x = 1)
    {
        $connection.Open()
        $insertData.ExecuteNonQuery()
        $connection.Close()
    }
}

2 个答案:

答案 0 :(得分:0)

并且像这样:

(Get-Content $full | Select-Object -skiplast 1) | set-Content $full
$all = Get-Content $full

答案 1 :(得分:0)

为什么你不使用import-csv命令,像这样:

$all=import-csv c:\temp\result.csv -Delimiter '|' -Header col1, col2, col3 | where col2 -ne $null