我正在尝试学习如何从 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?
Length
, -gt
and 10000
不是参数Where-Object
。只有一个参数,FilterScript
在位置 0,值为 typeScriptBlock
其中包含一个表达.
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 解析器那么丰富,但仍然很有用:
Content Type
------- ----
Get-ChildItem Command
| Operator
where-object Command
-filter CommandParameter
{ GroupStart
_ Variable
. Operator
Length Member
-gt Operator
1000000 Number
} GroupEnd
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)