我试图将哈希表作为脚本参数从 C# 传递到 PowerShell,但未成功。当我在 PowerShell 中执行时,脚本和参数工作正常,所以我假设我的错误在 C# 端。
在 C# 中,我只是像使用任何其他参数一样使用 Command.Parameters.Add()。我传递给脚本的所有其他参数都被正确接收,但哈希表为空。
在 C# 方面,我尝试过同时使用 Hashtable 对象和 Dictionary
最佳答案
使用 this answer和 Command.Parameters.Add( string, object )
方法重载,我能够将哈希表传递给脚本。这是测试代码:
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( );
它显示来自 $ht.Count
的 1
,以及来自枚举哈希表值的 a = b
。
关于c# - 将哈希表从 C# 传递到 PowerShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767254/