1

I want to read a csv file in 2 columns that when i will open my excel it will shows the informations of my CSV file displayed in 2 columns.

Actually, i only display in one column with the Following code :

Function Read-File {
    Param([string]$file, [string]$head)
    if (Test-Path $file) {
        Write-Verbose "$file exists, importing list."
        $data = Import-Csv -Path $file
        $s = @()
        if ($data.$head) {
            foreach ($device in $data) {
                try {
                    $s += $device.$head
                    Write-Verbose -Message "$device.$head"
                } catch {
                    Write-Error -Message "Failed to add $device to list."
                }
            }
        } else {
            Write-Error -Message "No such column, $head, in CSV file $file."
        }

        return $s
    }
}

$list = Read-File $file $fileColumn

So now i want to do it but in 2 columns , i'm a beginner in PowerShell so i would apreciate some help :) thank you

this is my CSV file :

Asset Number, Serial Number
cd5013172cffd6a317bd2a6003414c1,N5WWGGNL
8df47f5b1f1fcda12ed9d390c1c55feaab8,SN65AGGNL
dc0d1aaba9d55ee8992c657,B2NGAA3501119

i am only trying to display thoses both ( asset number and serial number) on 2 columns on my excel , dont worry thoses informations are not sensitive at all so its ok :)

3
  • I've fixed the broken syntax, @Theo. How to transition from reading only 1 value (which is what the code currently does) to 2 is what Jordy is asking about, I think. Commented Nov 22, 2019 at 14:47
  • @mklement0 by the way , its saying that it is impossible to link the arg to the parameter " path " because it is an empty string , on the if (test-path $file) :/ what should i do i am not sure Commented Nov 22, 2019 at 15:51
  • 1
    That implies that you passed a $null value or empty string as the -File argument to your ReadFile function. You can detect this problem earlier by declaring your -File parameter to only accept non-empty input: [ValidateNotNullOrEmpty()][string]$file Commented Nov 22, 2019 at 15:57

1 Answer 1

2
  • Use Select-Object to extract multiple properties from input objects (wrapped in custom object instances, [pscustomobject]).

  • Use implicit output from your function - no need to collect results in an array first, especially not by building it inefficiently with +=, which behind the scenes creates a new array in every iteration.

    • Note that return is never required to return (output) data from a function in PowerShell; any command whose output is neither captured, suppressed, nor redirected contributes to function's overall output.
Function Read-File {

  # Not that $column (formerly: $head) now accepts an *array* of strings,
  # [string[]]
  Param([string] $file, [string[]] $column)

  if (Test-Path $file) {

    Write-Verbose "$file exists, importing list."

    # Import the CSV file, create custom objects with only the column(s)
    # of interest, and output the result.
    # Also store the result in variable $result via -OutVariable, for
    # inspection below.
    Import-Csv -Path $file | Select-Object -Property $column -OutVariable result

    # If at least 1 object was output, see if all columns specified exist
    # in the CSV data.
    if ($result.Count) {
      foreach ($col in $column) {
        if ($null -eq $result[0].$col) {
          Write-Error -Message "No such column in CSV file $file`: $column"
        }
      }  
    }

  }

}

# Sample call with 2 column names.
$list = Read-File $file 'Asset Number', 'Serial Number'

$list can then be piped to Export-Csv to create a new CSV file, which you can open in Excel:

# Export the selected properties to a new CSV file.
$list | Export-Csv -NoTypeInformation new.csv

# Open the new file with the registered application, asssumed to be Excel.
Invoke-Item new.csv
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.