Invoking powershell cmdlets from C#

本文关键字:from cmdlets powershell Invoking | 更新日期: 2023-09-27 18:17:58

我正在尝试学习如何从c#调用PS cmdlet,并且遇到了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吗?

Invoking powershell cmdlets from C#

Length, -gt10000不是Where-Object的参数。只有一个参数,位置0的FilterScript,其值类型为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 命令| 操作符都 命令过滤器CommandParameter{ GroupStart_ 变量。操作符长度 成员gt 操作符1000000 数量} GroupEnd之前