1

In the code below I'm trying to pass a hashtable into a function but it always changes its type to an Object[]

 function Show-Hashtable{
    param(
         [Parameter(Mandatory = $true)][Hashtable] $input
    )
        return 0
    }
    
    function Show-HashtableV2{
    param(
         [Parameter(Mandatory = $true)][ref] $input
    )
        write-host $input.value.GetType().Name
        
        return 0
    }
    

    [Hashtable]$ht=@{}
    
    $ht.add( "key", "val" )
    
    # for test
    [int]$x = Show-HashtableV2 ([ref]$ht)
    
    # main issue
    [int]$x = Show-Hashtable $ht.clone()

Above I gave a try with $ht.Clone() instead of $ht but with no luck.

what I'm getting:

Object[]
Show-Hashtable : Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".
At C:\_PowerShellRepo\Untitled6.ps1:26 char:11
+ [int]$x = Show-Hashtable $ht #.clone()
+           ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Show-Hashtable], PSInvalidCastException
    + FullyQualifiedErrorId : ConvertToFinalInvalidCastException,Show-Hashtable

I am asking for the direction in which to look. What is wrong with my code?

Fuel
  • 13
  • 2

1 Answers1

1

$input is an automatic variable that contains an enumerator that enumerates all input that is passed to a function. Your parameter name conflicts with that (I wonder why PowerShell doesn't output a warning in this case).

The solution is simple, just name the parameter differently, e. g. InputObject:

function Show-HashtableV2{
param(
     [Parameter(Mandatory = $true)][ref] $InputObject
)
    write-host $InputObject.value.GetType().Name
    
    return 0
}

Now the function prints System.Collections.Hashtable.

zett42
  • 25,437
  • 3
  • 35
  • 72
  • 1
    Yes, it is regrettable that PowerShell doesn't prevent assigning to what should be read-only automatic variables - see [this answer](https://stackoverflow.com/a/58820780/45375) for background information. – mklement0 Mar 05 '21 at 15:14