Home > OS >  Pass a Hashtable as Parameter to powershell.exe
Pass a Hashtable as Parameter to powershell.exe

Time:08-31

How do I pass a hashtable as parameter to powershell.exe?

OutHash.ps1:

Param(
   [hashtable]$hash
)

$hash

Call:

powershell.exe -File .\OutHash.ps1 -hash @{'A'=1}

Output:

Cannot process argument transformation on parameter 'hash'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to type "System.Collections.Hashtable".

Expected output:

Name                           Value                                                                                                                                                                                                                             
----                           -----                                                                                                                                                                                                                             
A                              1  

Inside the powershell console, this call returns the expected output:

.\OutHash.ps1 -hash @{'A'=1}

CodePudding user response:

My "userfriendly" serialized solution:

Param(

    [string]$String
)

$Hash = $String -replace ",","`n" | ConvertFrom-StringData
$Hash

Call

powershell -file .\OutHash.ps1 -String "A=1,B=1"

CodePudding user response:

As commented by @Mathias:

You don't. The operating system's execution environment has no concept of a "hashtable", all you can pass is strings.

From the error message, I presume that you launching the PowerShell.exe command from PowerShell itself, as a alternative supporting complex hash tables, you might encode your command including the hashtable and invoke that:

$Command        = { .\OutHash.ps1 -hash @{ 'e-mail' = 'doe,[email protected]' } }
$Bytes          = [System.Text.Encoding]::Unicode.GetBytes($Command.ToString())
$EncodedCommand = [Convert]::ToBase64String($Bytes)

PowerShell.exe -EncodedCommand $EncodedCommand

CodePudding user response:

The default -Command works from cmd:

powershell .\outhash @{a=1}

Name                           Value
----                           -----
a                              1
  • Related