2016-12-05 33 views
1

如果我有以下功能获取列表功能从脚本

function SomeFunction {} 

function AnotherFunction {} 

名为.ps1文件,我怎么能得到的所有这些功能的列表,并调用它们?

我想要做这样的事情:

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

如果你的'.ps1'是'.psm1'相反,它会是一个模块,并获得函数列表会那么容易,因为'(导入模块C:\ someScript.psm1 -passThru ).ExportedFunctions.Values'。 (根据Martin的回答,用'&$ _。ScriptBlock'调用。) –

回答

1

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

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

我需要从多功能脚本中获取函数的名称。这是我想出的。基于此,也许有人可以提供更短的版本。

# Get text lines from file that contain 'function' 
$functionList = Select-String -Path $scriptName -Pattern "function" 

# Iterate through all of the returned lines 
foreach ($functionDef in $functionList) 
{ 
    # Get index into string where function definition is and skip the space 
    $funcIndex = ([string]$functionDef).LastIndexOf(" ") + 1 

    # Get the function name from the end of the string 
    $FunctionExport = ([string]$functionDef).Substring($funcIndex) 

    Write-Output $FunctionExport 
} 

我想出了一个较短的版本找到并列出在脚本列表的功能。这并不完美,并且会有问题,因为该模式只是“功能”一词,并且如果此方法假定它在任何地方找到了找到该关键字的功能。

要遍历文件并获取列表,我使用'Get-ChildItem'函数并使用递归选项传递路径和文件筛选器规范。

通过管道传递给'Select-String'并查找'Function'关键字。它不区分大小写,并会接受“功能”或“功能”。如果需要添加“-CaseSensitive”,则有一个区分大小写的选项。

然后迭代输出以获取实际的函数名称。 “Line”成员是一个字符串类型,我使用从第9位开始的“Substring”选项,它是刚刚通过“函数”标识符的长度。

$scriptPath = "c:\\Project" 
$scriptFilter = "*.ps1" 

(Get-ChildItem -Path $scriptPath -Filter $scriptFilter -Recurse | Select-String -Pattern "function") | %{ $_.Line.Substring(9) }