简体   繁体   English

从C#调用powershell cmdlet

[英]Invoking powershell cmdlets from C#

I'm trying to learn how to call PS cmdlets from C#, and have come across the PowerShell class. 我正在尝试学习如何从C#调用PS cmdlet,并且遇到了PowerShell类。 It works fine for basic use, but now I wanted to execute this PS command: 它适用于基本用途,但现在我想执行此PS命令:

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

I tried building this through the powershell class, but I can't seem to do this. 我尝试通过powershell类来构建它,但我似乎无法做到这一点。 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.

I always get an exception when I run this. 我跑这个时总是遇到异常。 Is it possible to run the Where-Object cmdlet like this? 是否可以像这样运行Where-Object cmdlet?

Length , -gt and 10000 are not parameters to Where-Object . Length-gt10000不是Where-Object参数。 There is only one parameter, FilterScript at position 0, with a value of type ScriptBlock which contains an expression . 只有一个参数,位于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)

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: 如果您需要分解更复杂的语句,请考虑使用tokenizer(在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

This dumps out the following information. 这会丢弃以下信息。 It's not as rich as the AST parser in v3, but it's still useful: 它不像v3中的AST解析器那么丰富,但它仍然有用:

Content                   Type
    -------                   ----
    Get-ChildItem          Command
    |                     Operator
    where-object           Command
    -filter       CommandParameter
    {                   GroupStart
    _                     Variable
    .                     Operator
    Length                  Member
    -gt                   Operator
    1000000                 Number
    }                     GroupEnd

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM