Passing a hash table as an argument to a function in PowerShell

I have a problem in a PowerShell script:

When I want to pass a hashtable to a function, that hashtable is not recognized as hashtable.

function getLength(){ param( [hashtable]$input ) $input.Length| Write-Output } $table = @{}; $obj = New-Object PSObject;$obj | Add-Member NoteProperty Size 2895 | Add-Member NoteProperty Count 5124587 $table["Test"] = $obj $table.GetType() | Write-Output ' Hashtable $tx_table = getLength $table 'Unable to convert System.Collections.ArrayList+ArrayListEnumeratorSimple in System.Collections.Hashtable 

What for?

+6
source share
1 answer

$Input is an automatic variable that lists the input entered.

Choose any other variable name and it will work - although not necessarily, as you might expect - to get the number of entries in the hash table, you need to check the Count property:

 function Get-Length { param( [hashtable]$Table ) $Table.Count } 

Write-Output implied when you just leave $Table.Count as it is.

In addition, the suffix () in the function name is unnecessary syntactic sugar with a zero value when you declare your parameters inline with Param() - discard it

+13
source

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


All Articles