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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With