我想将一个关联数组从C#传递给Powershell.作为一个例子,我想执行这个PowerShell代码行:
PS C:\> get-command | select name, @{N="Foo";E={"Bar"}} -first 3
Name Foo
---- ---
Add-Content Bar
Add-History Bar
Add-Member Bar
Run Code Online (Sandbox Code Playgroud)
我想通过不同命令的管道而不是标记为脚本的单个命令来执行此操作.这是代码:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("get-command");
Command c = new Command("select-object");
List properties = new List();
properties.Add("name");
properties.Add("@{N=\"Foo\";E={\"Bar\"}}");
c.Parameters.Add("Property", properties.ToArray());
c.Parameters.Add("First", 3);
pipeline.Commands.Add(c);
pipeline.Commands.Add("Out-String");
Collection retval = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in retval)
Console.WriteLine(obj.ToString());
Run Code Online (Sandbox Code Playgroud)
但是,作为参数传递给Select-Object的关联数组未被正确解析.这是另一方面的结果:
PS C:\test> c:\test\Bin\Debug\test.exe
Name @{N="Foo";E={"Bar"}}
---- --------------------
Add-Content
Add-History
Add-Member
Run Code Online (Sandbox Code Playgroud)
我如何设置Select-Object命令参数有什么问题?
我有一个来自.Net的对象,它具有SyncHashTable类型的属性,在抛出异常时无法查看.
单行复制:
[HashTable]::Synchronized(@{})
Run Code Online (Sandbox Code Playgroud)
多行更容易玩repro:
$ht = new-object hashtable
$ht.add("foo", "bar")
$hts = [Hashtable]::Synchronized($ht)
$hts
Run Code Online (Sandbox Code Playgroud)
错误:
format-default : Object reference not set to an instance of an object.
+ CategoryInfo : NotSpecified: (:) [format-default], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.FormatDefaultCommand
Run Code Online (Sandbox Code Playgroud)
有人对此有任何见解吗?