有没有办法在PowerShell脚本中显示所有函数?

goucqfw6  于 2023-01-13  发布在  Shell
关注(0)|答案(4)|浏览(192)

是否有任何命令可列出我在脚本中创建的所有函数?

就像我创建了函数doXY和函数getABC或者类似的东西。
然后我键入命令,它显示:
1.函数doXY
1.函数getABC
会是一个很酷的功能^^
谢谢你的帮助。

8e2ybdfx

8e2ybdfx1#

您可以让PowerShell分析脚本,然后在生成的抽象语法树(AST)中找到函数定义。
Get-Command可能是访问AST的最简单方法:

# Use Get-Command to parse the script
$myScript = Get-Command .\path\to\script.ps1
$scriptAST = $myScript.ScriptBlock.AST

# Search the AST for function definitions
$functionDefinitions = $scriptAST.FindAll({
  $args[0] -is [Management.Automation.Language.FunctionDefinitionAst]
}, $false)

# Report function name and line number in the script
$functionDefinitions |ForEach-Object {
    Write-Host "Function '$($_.Name)' found on line $($_.StartLineNumber)!"
}

如果需要,您还可以使用它来分析函数的内容和参数。

iqjalb3h

iqjalb3h2#

其中脚本名为things.ps1,类似于...

cat ./things.ps1 | grep function

适用于MacOS/Linux或

cat ./things.ps1 | select-string function

适用于Windows。

bprjcwpo

bprjcwpo3#

这是PowerShell帮助文件中所示的内置功能。
About_Providers
类似的问题以前也有人问过。因此,这是以下内容的潜在副本:
How to get a list of custom Powershell functions?
答案...使用PSDrive功能

# To get a list of available functions
Get-ChildItem function:\

# To remove a powershell function
# removes `someFunction`
Remove-Item function:\someFunction

或者

Function Get-MyCommands {
    Get-Content -Path $profile | Select-String -Pattern "^function.+" | ForEach-Object {
        [Regex]::Matches($_, "^function ([a-z.-]+)","IgnoreCase").Groups[1].Value
    } | Where-Object { $_ -ine "prompt" } | Sort-Object
}

或者这个
Get List Of Functions From Script

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

至于这个...
谢谢,这就是我想要的,但是它也显示了像A:,B:,Get-Verb,Clear-Host,...
这是设计好的。如果你想用另一种方式,那么你必须编写它。要在任何脚本中获得函数名,它必须首先加载到内存中,然后你可以点源定义并获得内部信息。如果你只想获得函数名,你可以使用regex来获得它们。
或者像这样简单...

Function Show-ScriptFunctions
{
    [cmdletbinding()]
    [Alias('ssf')]

    Param 
    (
        [string]$FullPathToScriptFile
    )

    (Get-Content -Path $FullPathToScriptFile) | 
    Select-String -Pattern 'function'
}

ssf -FullPathToScriptFile 'D:\Scripts\Format-NumericRange.ps1'

# Results
<#
function Format-NumericRange 
function Flush-NumberBuffer 
#>
csga3l58

csga3l584#

此函数将解析.ps1文件中包含的所有函数,然后返回找到的每个函数的对象。
输出可以直接通过管道传输到Invoke-Expression,以将返回的函数加载到当前范围中。
还可以提供所需名称的数组或正则表达式来约束结果。
我的用例是,我需要一种方法来从我不拥有的较大脚本加载单个函数,这样我就可以进行纠缠测试。
注:只在PowerShell 7中测试过,但我怀疑它在旧版本中也能工作。

function Get-Function {
    <# 
    .SYNOPSIS 
        Returns a named function from a .ps1 file without executing the file

    .DESCRIPTION
        This is useful where you have a blended file containing functions and executed instructions.

        If neither -Names nor -Regex are provided then all functions in the file are returned.
        Returned objects can be piped directly into Invoke-Expression which will place them into the current scope.

        Returns an array of objects with the following
            - .ToString()
            - .Name
            - .Parameters
            - .Body
            - .Extent
            - .IsFilter
            - .IsWorkFlow
            - .Parent

    .PARAMETER -Names 
        Array of Strings; Optional
        If provided then function objects of these names will be returned
        The name must exactly match the provided value
        Case Insensitive.

    .PARAMETER -Regex
        Regular Expression; Optional
        If provided then function objects with names that match will be returned
        Case Insensitive

    .EXAMPLE
        Get all the functions names included in the file
            Get-Function -name TestA | select name

    .EXAMPLE
        Import a function into the current scope
            Get-Function -name TestA | Invoke-Expression

    #>
    param (
        $File = "c:\fullpath\SomePowerShellScriptFile.ps1"
        , 
        [alias("Name", "FunctionNames", "Functions")]
        $Names
        ,
        [alias("NameRegex")]
        $Regex
        ) # end function
    # get the script and parse it
    $Script = Get-Command /Users/royomi/Documents/dev/javascript/BenderBot_AI/Import-Function.ps1
    $AllFunctions = $Script.ScriptBlock.AST.FindAll({$args[0] -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)

    # return all requested functions
    $AllFunctions | Where-Object { `
        ( $Names -and $Names -icontains $_.Name ) `
        -or ( $Regex -and $Names -imatch $Regex ) `
        -or (-not $Names -and -not $Regex) `
        } # end where-object
    } # end function Get-Function

相关问题