简体   繁体   中英

Pass a Hashtable as Parameter to powershell.exe

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}

My "userfriendly" serialized solution:

Param(

    [string]$String
)

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

Call

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

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,john@fabrikam.com' } }
$Bytes          = [System.Text.Encoding]::Unicode.GetBytes($Command.ToString())
$EncodedCommand = [Convert]::ToBase64String($Bytes)

PowerShell.exe -EncodedCommand $EncodedCommand

The default -Command works from cmd:

powershell .\outhash @{a=1}

Name                           Value
----                           -----
a                              1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM