powershell - 在ps1中查找函数并调用

标签 powershell powershell-3.0

如何找到特定.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/

相关文章:

powershell - 如何使用 "DO... Until"作为脚本日期提示

powershell - 使用powershell删除文件中的NUL字符

c# - 使用 Powershell 自动禁用 Windows 更新

powershell - 使用 SharePoint 2010 的 OData API 替换附加文件

powershell-3.0 - 如何从 Powershell 中的字符串中删除大括号

powershell - 为什么 add_EventName 不能与 Timer 一起使用?

windows - Powershell 和德语变音符号

Vim 与 Powershell

windows - 如何更改 powershell 中的单个语法着色?

powershell - 用于创建文件夹的批处理文件,增量文件夹名称为Name 1、Name 2、