powershellhashtablepowershell-7.2

Passing Hashtable Parameter from CommandLine PowerShell 7.2


I am trying to create a PowerShell script, and one of the parameters of the script is a Hashtable. I am using PowerShell 7.2 for this project, and whenever I try to pass a Hashtable in through the command line, it passes it as the string System.Collections.Hashtable instead of the Hashtable itself. This causes the script to throw an error as the parameter is types as a Hashtable.

Here is a shortened version of the script I have written.

#requires -version 7.2

[CmdletBinding(PositionalBinding = $False)]
param ([hashtable] $TestTable)

$TestTable

I have tried the following command in the PowerShell command line.
pwsh .\ScriptName.ps1 -TestTable @{Test = "This is a test"}
pwsh -Command .\ScriptName.ps1 -TestTable @{Test = "This is a test"}
And many variants of these attempting different combinations of commas, quotes, brackets, and @ symbols.

When I run either of the two commands listed above I get the error ScriptName.ps1: Cannot process argument transformation on parameter 'TestTable'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to type "System.Collections.Hashtable".

I am trying to stick with PowerShell 7.2 for the project. When I remove the requirement for 7.2 and run the command without pwsh, it works perfectly, but I have not been able to find a solution that works for 7.2. If anyone knows how to do this, I would greatly appreciate an explanation.


Solution

  • I have tried the following command in the PowerShell command line.

    There's usually no good reason to call pwsh, the PowerShell (Core) CLI, from PowerShell, given that you can invoke .ps1 files directly, in-process:

    .\ScriptName.ps1 -TestTable @{Test = "This is a test"}
    

    If you want to call via the CLI nonetheless (e.g. to confine to a child process any session-level changes a (potentially ill-behaved) script may make), use a script block ({ ... }) for your invocation:

    pwsh { .\ScriptName.ps1 -TestTable @{Test = "This is a test"} }
    

    Note: