从脚本中获取函数列表 [英] Get List Of Functions From Script

查看:38
本文介绍了从脚本中获取函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a .ps1 file with the following functions

function SomeFunction {}

function AnotherFunction {}

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

How can I get a list of all those functions and invoke them?

我想做这样的事情:

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

推荐答案

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

You could use the Get-ChildItem to retrieve all functions and store them into a variable. Then load the script into to runspace and retrieve all functions again and use the Where-Object cmdlet to filter all new functions by excluding all previously retrieved functions. Finally iterate over all new functions and invoke them:

$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
}

这篇关于从脚本中获取函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆