从脚本中获取函数列表

Bac*_*ave 4 powershell

如果我有一个具有以下功能的 .ps1 文件

function SomeFunction {}

function AnotherFunction {}
Run Code Online (Sandbox Code Playgroud)

如何获取所有这些函数的列表并调用它们?

我想做这样的事情:

$functionsFromFile = Get-ListOfFunctions -Path 'C:\someScript.ps1'
foreach($function in $functionsFromFile)
{
   $function.Run() #SomeFunction and AnotherFunction execute
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ndl 7

您可以使用Get-ChildItem来检索所有函数并将它们存储到变量中。然后将脚本加载到运行空间并再次检索所有函数,并使用Where-Objectcmdlet 通过排除所有先前检索的函数来过滤所有新函数。最后迭代所有新函数并调用它们:

$currentFunctions = Get-ChildItem function:
# dot source your script to load it to the current runspace
. "C:\someScript.ps1"
$scriptFunctions = Get-ChildItem function: | Where-Object { $currentFunctions -notcontains $_ }

$scriptFunctions | ForEach-Object {
      & $_.ScriptBlock
}
Run Code Online (Sandbox Code Playgroud)

  • 有时,您必须顺便过来评论一个非常好的想法。不错的技巧:-) (3认同)