使用 C# 中的 PowerShell 计算属性 [英] Using PowerShell Calculated Properties from C#
问题描述
所以我想从 C# 执行 PowerShell 计算属性(我希望这是正确的名称).
So I want to execute PowerShell Calculated Properties (I hope that's the correct name) from C#.
我在 PS (Exchange) 控制台中的 CmdLet 如下所示:
My CmdLet in the PS (Exchange) Console looks like this:
Get-Something -ResultSize unlimited |Select-Object DisplayName,@{name="RenamedColumn;expression={$_.Name}},ToBeExpanded -Expand ToBeExpanded |Select-Object DisplayNameRenamedColumn,ToBeExpandedGuid
这很好用,当我尝试从 C# 执行它时出现问题.
This works just fine, the problem occures when I try to execute it from C#.
我的代码如下所示:
List<string> parameters = new List<string>()
{
"DisplayName","@{{name=\"RenamedColumn\";expression={{$_.Name }} }}","ToBeExpanded"
};
List<string> parameters2 = new List<string>()
{
"DisplayName","RenamedColumn","ToBeExpanded","ToBeExpandedGuid"
};
powershell.AddCommand("Get-Something");
powershell.AddParameter("ResultSize","unlimited");
powershell.AddCommand("Select-Object");
powershell.AddParameter("Property",parameters);
powershell.AddParameter("ExpandProperty","ToBeExpanded");
powershell.AddCommand("Select-Object");
powershell.AddParameters("Property",parameters2);
result = powershell.Invoke();
然后我的结果包含空的 ToBeExpandedGuid
(null).所以我在没有第二个选择的情况下尝试了这个命令,它告诉我它有这个列:
My result then contains the empty ToBeExpandedGuid
(null). So I tried the command without the second select and it shows me that it has the column:
@{{name=\"RenamedColumn\";expression={{$_.Name }} }}
所以我的想法是 powershell 无法识别这种重命名...现在我的问题是如何使用 C# 中的类似内容?有什么解决办法吗?
So my thought was that powershell doesn't recognize this renaming... Now my question how do I use something like this from C#? Is there any solution?
推荐答案
在 PowerShell @{Name="RenamedColumn";Expression={$_.Name}}
不是字符串而是 Hashtable
,因此在 C# 中,您还必须创建一个 Hashtable
(或其他实现 IDictionary
的集合)以将其传递给 Select-Object
cmdlet:
In PowerShell @{Name="RenamedColumn";Expression={$_.Name}}
is not a string but a Hashtable
, so in C# you also have to create a Hashtable
(or other collection implementing IDictionary
) to pass it to Select-Object
cmdlet:
new Hashtable{
{"Name","RenamedColumn"},
{"Expression",ScriptBlock.Create("$_.Name")}
}
附注
如果您想要的只是重命名,那么这里不需要 ScriptBlock
:
@{Name="RenamedColumn";Expression="Name"}
new Hashtable{
{"Name","RenamedColumn"},
{"Expression","Name"}
}
这篇关于使用 C# 中的 PowerShell 计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!