2016-12-05 65 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) }