从C#调用PowerShell cmdlets

24

我正在学习如何从C#中调用PowerShell cmdlets,发现了PowerShell类。它可以用于基本的使用,但现在我想执行这个PS命令:

Get-ChildItem | where {$_.Length -gt 1000000}

我尝试使用PowerShell类来构建这个,但似乎做不到。以下是我目前的代码:

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.

当我运行此命令时,经常遇到异常情况。是否可能像这样运行 Where-Object cmdlet?

1个回答

23

Length-gt10000都不是Where-Object的参数。该命令只有一个参数FilterScript,位于位置0,其值为类型为ScriptBlock的脚本块,其中包含一个表达式。

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ScriptBlock filter = ScriptBlock.Create("$_.Length -gt 10000")
ps.AddParameter("FilterScript", filter)

如果您有更复杂的语句需要分解,请考虑使用分词器(在v2或更高版本中可用)以更好地理解结构:

    # 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解析器丰富,但仍然很有用:

    内容                   类型
    -------                   ----
    Get-ChildItem          命令
    |                     运算符
    where-object           命令
    -filter       命令参数
    {                   分组开始
    _                     变量
    .                     运算符
    Length                  成员
    -gt                   运算符
    1000000                 数字
    }                     分组结束

希望这能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接