【问题标题】:Invoking powershell cmdlets from C#从 C# 调用 powershell cmdlet
【发布时间】:2013-06-08 17:04:20
【问题描述】:

我正在尝试学习如何从 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?

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

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

    内容类型 -------- ---- 获取子项命令 |操作员 where-object 命令 -filter 命令参数 { 组开始 _ 多变的 .操作员 长度成员 -gt 运算符 1000000 号码 } 组结束

    希望这会有所帮助。

    【讨论】:

    • 啊,太好了,我现在明白了。感谢您的解释和代码:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2018-12-14
    相关资源
    最近更新 更多