Reputation: 177
I'm looking to import a csv file. Take the first row(with headers) and add it to an array in powershell.
$csv = Import-CSV "test.csv"
$array = @()
Upvotes: 0
Views: 2331
Reputation: 61068
I'm not quite sure what you are asking here, but it looks to me that you want to get the headers of a CSV file as array: (Take the first row(with headers) and add it to an array in powershell)
If that is the case, here's a small function that can do that for you:
function Get-CsvHeaders {
# returns an array with the names of the headers in a csv file in the correct order
[CmdletBinding(DefaultParameterSetName = 'ByDelimiter')]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[string]$Path,
[Parameter(Mandatory = $false)]
[ValidateSet ('ASCII', 'BigEndianUnicode', 'Default', 'OEM', 'Unicode', 'UTF32', 'UTF7', 'UTF8')]
[string]$Encoding = $null,
[Parameter(Mandatory = $false, ParameterSetName = 'ByDelimiter')]
[char]$Delimiter = ',',
[Parameter(Mandatory = $false, ParameterSetName = 'ByCulture')]
[switch]$UseCulture
)
$splatParams = @{ 'Path' = $Path }
switch ($PSCmdlet.ParameterSetName) {
'ByDelimiter' { $splatParams.Delimiter = $Delimiter; break }
'ByCulture' { $splatParams.UseCulture = $true; break }
}
if ($Encoding) { $splatParams.Encoding = $Encoding }
$data = Import-Csv @splatParams -ErrorAction SilentlyContinue
$data[0].PSObject.properties.name
}
Usage:
$headersArray = Get-CsvHeaders -Path 'test.csv'
Upvotes: 0
Reputation: 1664
Would you need an explicit conversion to array when import-csv is giving you a nice enumerable array of System.Object instances?
When you use import-csv , PowerShell will read the header row and give you back an array of custom objects. Each of these objects will have properties which match the Header column.
Example of test.csv
Id,FirstName
1,Name001
2,Name002
Results after import-csv
You can iterate through the collection as shown below
$csv = Import-CSV "test.csv"
foreach($item in $csv)
{
$msg=("Id={0} , Name={1}" -f $item.Id, $item.FirstName)
Write-Host $msg
}
#Add the first item to your own array
$arrMy=@()
$arrMy+=$csv[0]
$arrMy
Output
Id=1 , Name=Name001
Id=2 , Name=Name002
Id FirstName
-- ---------
1 Name001
MSDN
Getting deeper - what does import-csv actually return?
It returns an array with N objects of type System.Management.Automation.PSCustomObject. Here N=no of rows in the CSV file.
Upvotes: 1