Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a hashtable from C# to PowerShell

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.

like image 765
Chris Aiken Avatar asked Feb 15 '23 07:02

Chris Aiken


1 Answers

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.

like image 106
Emperor XLII Avatar answered Feb 23 '23 16:02

Emperor XLII