Changing powershell pipe type to hash table (or any other enumerated type)

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

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

Import-csv puts the array into the pipeline, how can I change it to a hash table 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 the entire hash table as a new pipeline or create a new pipeline with hashtable type?

+4
source share
2 answers

What do you plan to use as keys for the hash table? besides this, it should be fairly easy to do even with a simple foreach object:

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

I donโ€™t see the need for any way to โ€œchange the type of pipelineโ€, honestly ...?

+9
source

Another possibility is to use a more compact foreach form:

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

which leaves $ Out set for the hash table of values, rather than converting the pipeline to create the hash table. But you, of course, can pass $ Out to 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.

+1
source

Source: https://habr.com/ru/post/1415533/


All Articles