Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing powershell pipeline type to hashtable (or any other enumerable type)

I like to write a cmdlet "Convert-ToHashTable" which performs following task:

$HashTable = Import-Csv Table.csv | Convert-ToHashTable

Import-csv places an array on the pipeline, how can i change it to a hashtable in my Convert-ToHashTable cmdlet? In the Process part of the cmdlet i can access the elements, but i don't know how to change the type of the pipeline itself

Process { Write-Verbose "Process $($myinvocation.mycommand)" $CurrentInput = $_ ... }

Is there a way to return a complete hashtable as the new pipeline or create a new pipeline with type hashtable?

like image 305
Thomas Maierhofer Avatar asked Jun 01 '12 09:06

Thomas Maierhofer


2 Answers

What do you plan to use as keys for hashtable? other than that, it should be pretty easy to do even with simple foreach-object:

Import-Csv Table.csv | Foreach-Object -begin {
    $Out = @{}
} -process {
    $Out.Add('Thing you want to use as key',$_)
} -end {
    $Out
}

Don't see need for any "change pipeline type" magic, honestly...?

like image 84
BartekB Avatar answered Sep 21 '22 11:09

BartekB


Another possibility is to use the more compact form of foreach:

$Out = @{}
Import-Csv Table.csv | %{ $Out[$_.Key] = $_.Value }

Which leaves $Out set to the hashtable of values rather than converting the pipeline to produce a hashtable. But you can of course then pipe $Out into something else.

Also note that there is a subtle difference between $Out.Add(x, y) and $Out[x] = y. The former throws an exception if the element is already present, and the latter replaces it.

like image 25
StephenD Avatar answered Sep 19 '22 11:09

StephenD