从C#调用PowerShell命令 [英] Invoking powershell cmdlets from C#
问题描述
我想学习如何调用从C#PS的cmdlet,以及所遇到的PowerShell的类。它工作正常的基本使用,但现在我想执行这个PS命令:
I'm trying to learn how to call PS cmdlets from C#, and have come across the PowerShell class. It works fine for basic use, but now I wanted to execute this PS command:
Get-ChildItem | where {$_.Length -gt 1000000}
我试图通过PowerShell的类建筑,但我似乎无法做到这一点。这是我的code迄今:
I tried building this through the powershell class, but I can't seem to do this. This is my code so far:
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ps.AddParameter("Length");
ps.AddParameter("-gt");
ps.AddParameter("10000");
// Call the PowerShell.Invoke() method to run the
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(
"{0,-24}{1}",
result.Members["Length"].Value,
result.Members["Name"].Value);
} // End foreach.
当我运行这个
我总是得到一个异常。是否有可能像这样运行在哪里对象cmdlet?
I always get an exception when I run this. Is it possible to run the Where-Object cmdlet like this?
推荐答案
长度
, -gt
和 10000
不是参数为位置对象
。只有一个参数, FilterScript
在位置0,与类型的值脚本块
其中包含的前pression 的。
Length
, -gt
and 10000
are not parameters to Where-Object
. There is only one parameter, FilterScript
at position 0, with a value of type ScriptBlock
which contains an expression.
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ScriptBlock filter = ScriptBlock.Create("$_.Length -gt 10000")
ps.AddParameter("FilterScript", filter)
如果您有需要分解更复杂的语句,可以考虑使用标记生成器(在2版或更高版本提供)了解结构较好:
If you have more complex statements that you need to decompose, consider using the tokenizer (available in v2 or later) to understand the structure better:
# use single quotes to allow $_ inside string
PS> $script = 'Get-ChildItem | where-object -filter {$_.Length -gt 1000000 }'
PS> $parser = [System.Management.Automation.PSParser]
PS> $parser::Tokenize($script, [ref]$null) | select content, type | ft -auto
这转储以下信息。这不是富比在V3的AST解析器,但它仍然是有用的:
This dumps out the following information. It's not as rich as the AST parser in v3, but it's still useful:
Content Type
------- ----
Get-ChildItem Command
| Operator
where-object Command
-filter CommandParameter
{ GroupStart
_ Variable
. Operator
Length Member
-gt Operator
1000000 Number
} GroupEnd
希望这有助于。
这篇关于从C#调用PowerShell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!