Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a hashtable as an argument to a function in PowerShell

Tags:

powershell

I have a problem in a PowerShell script:

When I want to pass a Hashtable to a function, this hashtable is not recognized as a 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

Why?

like image 384
Alsatian Avatar asked May 12 '15 11:05

Alsatian


2 Answers

$Input is an automatic variable that enumerates the input given.

Chose any other variable name and it'll work - although not necessarily as you might expect - to get the number of entries in a hashtable you need to inspect the Count property:

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

    $Table.Count
}

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

Also, the () suffix in the function name is unnecessary syntactic sugar with zero meaning when you declare your parameters inline with Param() - drop it

like image 143
Mathias R. Jessen Avatar answered Oct 13 '22 00:10

Mathias R. Jessen


I'm not really sure what to comment here, it seems self-explanatory. If not, leave a comment and I'll clarify.

$ExampleHashTable = @{
    "one" = "the loneliest number"
    "two" = "just as bad as one"
}

Function PassingAHashtableToAFunctionTest {
    param(
        [hashtable] $PassedHashTable,
        [string] $AHashTableElement
    )

    Write-Host "One is ... " 
    Write-Host $PassedHashTable["one"]
    Write-Host "Two is ... " 
    Write-Host $AHashTableElement
}

PassingAHashtableToAFunctionTest -PassedHashTable $ExampleHashTable `
    -AHashTableElement $ExampleHashTable["two"]

Output:

One is ... 
the loneliest number
Two is ... 
just as bad as one
like image 41
M H Avatar answered Oct 12 '22 23:10

M H