Mark Tsizis
Mark Tsizis

Reputation: 276

PowerShell how to present function parameters in the form of CSV

I'm new to PowerShell and I have very simple task: to output three function parameters as CSV string. Here what I get:

function ToCsv($v1, $v2, $v3) {
    Write-Host $v1, $v2, $v3
    Write-Host "$v1,$v2,$v3"
    Write-Host $v1 + "," + $v2 + "," + $v3
}

ToCsv("One", "Two", "Three")

One Two Three  
One Two Three,,
One Two Three + , +  + , +

What would be the right way to output a bunch of function parameters as comma-separated string?

I'm using PowerShell 5.1

Upvotes: 0

Views: 88

Answers (1)

RetiredGeek
RetiredGeek

Reputation: 3168

Mark,

It takes a little work but not biggie.

Function ToCsv($v1, $v2, $v3) {

 #Convert arguments to an Ordered Hash Table
  $MyArgs = [Ordered]@{
    Arg1 = "$v1"
    Arg2 = "$v2"
    Arg3 = "$v3"
  }

  #Convert the Hash table to a PS Custom Object.
  $object = new-object psobject -Property $MyArgs
  
  #Export the PS Custom Object as a CSV file.
  Export-csv -InputObject $object -Path G:\BEKDocs\Test.csv -NoTypeInformation
  
}

ToCsv "One" "Two" "Three"

Results: (as seen in NP++)

"Arg1","Arg2","Arg3"
"One","Two","Three"

HTH

Update:

Here's a better solution that will handle any number of arguments.

Function ToCsv {

  $ArgCnt = $Args.Count

  $object = new-object psobject

  For ($Cntr = 0; $Cntr -lt $ArgCnt; $Cntr++) {

    $AMArgs = @{InputObject = $object
                MemberType = "NoteProperty"
                Name = $("Arg" + $($Cntr + 1))
                Value = "$($Args[$($Cntr)])"
               }
  
    Add-Member @AMArgs
  }

   Export-CSV -InputObject $object -Path G:\BEKDocs\Test.csv -NoTypeInformation

} #End Function ToCSV

ToCsv "One" "Two" "Three" "Four"

Results: (as seen in NP++)

"Arg1","Arg2","Arg3","Arg4"
"One","Two","Three","Four"

Upvotes: 1

Related Questions