简体   繁体   English

将哈希表从C#传递到PowerShell

[英]Passing a hashtable from C# to PowerShell

I am attempting unsuccessfully to pass a hashtable from C# to PowerShell as a script parameter. 我尝试将哈希表从C#作为脚本参数传递给PowerShell,但未成功。 The script and parameters work properly when I execute within PowerShell, so I'm assuming my error is on the C# side. 当我在PowerShell中执行时,脚本和参数可以正常工作,因此我假设我的错误在C#端。

In C#, I am simply using Command.Parameters.Add() as I would for any other parameter. 在C#中,就像在其他任何参数中一样,我只是简单地使用Command.Parameters.Add()。 All the other parameters that I pass to the script are being received correctly, but the hashtable is null. 我传递给脚本的所有其他参数都可以正确接收,但哈希表为null。

From the C# side, I have tried using both a Hashtable object and a Dictionary<string, string> object, but neither appears to work. 从C#方面,我尝试同时使用Hashtable对象和Dictionary <string,string>对象,但两者似乎都不起作用。 In both cases, I have confirmed that the object is instantiated and has values before passing to PowerShell. 在这两种情况下,我都已确认对象已实例化,并且在传递给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. 我不知道是否有限制,但是如果没有限制,则需要将哈希表转换为字符串并在PowerShell脚本中进行解析。

Using this answer and the Command.Parameters.Add( string, object ) method overload, I was able to pass a hashtable to a script. 使用此答案Command.Parameters.Add( string, object )方法重载,我能够将哈希表传递给脚本。 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. 它从$ht.Count显示1 ,从枚举哈希表值显示a = b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM