4

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Aiken
  • 43
  • 1
  • 3

2 Answers2

5

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.

Community
  • 1
  • 1
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
  • I feared that might be the case. I was able to get it to work by sending a string array of "key=value" combos and then using string.split(=) to get everything into the hashtable correctly. Thank you. – Chris Aiken Sep 12 '13 at 19:00
  • If you're passing your parameters using ps.Commands.AddParameter(string, object) then you can pass array, string, and int types at the least. Not just string – skukx Mar 24 '15 at 00:14