I am attempting unsuccessfully to pass a hashtable from C# to PowerShell as a script parameter. The script and parameters work properly when I execute within PowerShell, so I'm assuming my error is on the C# side.
In C#, I am simply using Command.Parameters.Add() as I would for any other parameter. All the other parameters that I pass to the script are being received correctly, but the hashtable is null.
From the C# side, I have tried using both a Hashtable object and a Dictionary<string, string> object, but neither appears to work. In both cases, I have confirmed that the object is instantiated and has values before passing to PowerShell. I feel like there's a very obvious solution staring me in the face, but it just isn't clicking.
You can only pass strings as command line parameters.
I don't know if there a limit but if there isn't you will need to convert the hashtable to a string and parse it in your PowerShell script.
Using this answer and the Command.Parameters.Add( string, object )
method overload, I was able to pass a hashtable to a script. Here is the test code:
string script = @"
param( $ht )
Write-Host $ht.Count
$ht.GetEnumerator() | foreach { Write-Host $_.Key '=' $_.Value }
";
Command command = new Command( script, isScript: true );
var hashtable = new Hashtable { { "a", "b" } };
command.Parameters.Add( "ht", hashtable );
Pipeline pipeline = runspace.CreatePipeline( );
pipeline.Commands.Add( command );
pipeline.Invoke( );
It displays 1
from $ht.Count
, and a = b
from enumerating the hashtable values.
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.