从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
, -gt
和10000
不是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
希望这可以帮助。