我需要從多功能腳本中獲取函數的名稱。這是我想出的。基於此,也許有人可以提供更短的版本。
# 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) }
如果你的'.ps1'是'.psm1'相反,它會是一個模塊,並獲得函數列表會那麼容易,因爲'(導入模塊C:\ someScript.psm1 -passThru ).ExportedFunctions.Values'。 (根據Martin的回答,用'&$ _。ScriptBlock'調用。) –