Powershell .CSV values piped to select-objects returns empty records?

十年热恋 提交于 2019-12-24 19:53:09

问题


When i use import-csv to retrieve data from a .csv file

I'm able to retrieve the data in the file in the console pane using Import-CSV:

import-csv \\TestPath\licenses_v2.csv 

However, when i pipe that output to a select-object statement the same amount of rows are retrieved but they're now all empty.

import-csv \\TestPath\licenses_v2.csv | 
select-object FirstName,LastName,Department,Title

This occured after i began testing the following two seperate scripts, in an attempt to TRUNCATE before an INSERT statement for a SQL table.

$database = 'DATABASE'
$server = 'SERVER'
$table = 'TABLE'
Import-CSV \\TESTPATH\licenses_v2.csv | 
ForEach-Object { Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "truncate table $table; insert into $table VALUES ('$($_.FirstName)','$($_.LastName)','$($_.Department)','$($_.Title)')" 
}

$database = 'DATABASE'
$server = 'SERVER'
$table = 'TABLE'
Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "truncate table $table"
Import-CSV \\TESTPATH\licenses_v2.csv | 
ForEach-Object { Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "insert into $table VALUES ('$($_.FirstName)','$($_.LastName)','$($_.Department)','$($_.Title)')" 
}

What do i have to do to reverse this?


回答1:


You're using a pipe delimited CSV, when the default is comma. You see data in screen #1 because it creates a single object for every column. You see the headers empty, because powershell does not match any objects under those literal headers (since there's only a single header, named a combination of all.)

Note that Select can return headers when matched with literally nothing:

'' | Select Name,Date

Name Date
---- ----

To fix, just use Import-Csv -Delimiter '|'

See https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-6#optional-parameters

If you specify a character other than the actual string delimiter in the file, Import-Csv cannot create objects from the CSV strings. Instead, it returns the strings.



来源:https://stackoverflow.com/questions/49782136/powershell-csv-values-piped-to-select-objects-returns-empty-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!