如何找到特定.ps1文件中存在的所有源点函数,并在循环中调用这些方法? (不需要参数)
我们知道使用Get-ChildItem function:\将列出 shell 中的所有方法。
一种解决方案是对.ps1文件中的所有函数使用特定的命名约定,并使用Get-ChildItem函数:\ unique_pattern *搜索。这确实有点脆弱。
另外,我也不知道如何基于Get-ChildItem的返回信息调用该函数。任何的想法?
最佳答案
使用PowerShell 3.0+ Language namespace解析器列出ps1文件中的所有顶级函数名称:
$code = Get-Content -literal 'R:\source.ps1' -raw
$fns = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
EndBlock.Statements.
FindAll([Func[Management.Automation.Language.Ast,bool]]{
$args[0] -is [Management.Automation.Language.FunctionDefinitionAst]
}, $false) |
Select -expand Name
对脚本进行点源处理后,按名称在变量中调用函数:
& $name param1 param2 param3
关于powershell - 在ps1中查找函数并调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744785/