Csharp/C#教程:从C#调用powershell cmdlet分享


从C#调用powershell cmdlet

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

我跑这个时总是遇到exception。 是否可以像这样运行Where-Object cmdlet?

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) 

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

这会转储以下信息。 它不像v3中的AST解析器那么丰富,但它仍然有用:

     内容类型      ------- ----      Get-ChildItem命令      | 操作者      where-object命令      -filter CommandParameter      {GroupStart      _变量      。 操作者     长度成员      -gt运算符      1000000号      } GroupEnd 

希望这可以帮助。

上述就是C#学习教程:从C#调用powershell cmdlet分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991776.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐