Exlude a row on Import-Csv

时间:2019-03-19 14:51:23

标签: powershell csv

I have a question concerning Import-Csv in PowerShell. My script reads all *.csv files in my directory and writes it to my MS SQL database. So far so good, but I have a problem in these csv files. They all look the same like this:

Header1;Header2;Header3
-----;-----;-----
Data1;Data2;Data3
Data1;Data2;Data3

and so on.

My code looks like this:

foreach ($File in (Get-ChildItem -Path 'C:\data\*.csv')) {
    Import-Csv $File -Delim ';' | ForEach-Object {
        Invoke-Sqlcmd -Database $SQLDatabase -ServerInstance $SQLInstance -Query "insert into dbo.customer_data VALUES ('$($_."Instance Name"............)'

Works fine if I remove the line with "---", because PowerShell can't cast this to an integer.

Question: Are there solutions to ignore a row while working with Import-Csv? I found out I could skip lines with Get-Content, but it seems this can only skip a list of rows and not a specific one. I also thought about exporting csv files without this row with:

foreach ($File in (Get-ChildItem -Path 'C:\data\*.csv')) {
    Import-Csv $File -Delim ';' |
        where {$_."Instance Name" -ne "-------------"} |
        Export-Csv "C:\data\BaseName.csv" -NoTypeInfo

But I think this is not a good solution since files are doubled now and I have no clue about Name placeholders in PowerShell. Or can I actually get the current name of the csv file and overwrite it?

1 个答案:

答案 0 :(得分:3)

您无法使cmdlet Import-Csv跳过特定的行,但是您还有其他选择:

  1. 过滤掉之前从CSV转换的行:

    Get-Content $file | where { $_ -notmatch "--" } | ConvertFrom-Csv -Delim ";"
    
  2. 在导入CSV后过滤掉 项:

    Import-Csv $file -Delim ";" | where { $_ -notmatch "--" }
    
  3. 由@AnsgarWiechers提出(在导入后的 之后跳过第一项):

    Import-Csv $file -Delim ";" | select -Skip 1