Pass a Hashtable as Parameter to powershell.exe

Viewed 70

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

The powershell.exe is started by the IntuneManagementExtension. The behavior can be reproduce by start a powershell.exe from a running powershell console.

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}
3 Answers

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. It should work from Intune. You may have to put the full path to the script. "-command" and "-hash" are optional.

powershell.exe -command c:\temp\outhash.ps1 -hash @{A=1}

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