gpt4 book ai didi

function - 获取 .ps1 文件中特定函数的最后一行

转载 作者:行者123 更新时间:2023-12-03 22:23:54 24 4
gpt4 key购买 nike

我想获取 .ps1 文件中特定函数的最后一行。我已经用 powershell v3 代码完成了这个:

function GetEndLineNumber($ParseFile, $functionName))
{
$AbstractSyntaxTree = $NewParser::ParseFile($ParseFile, [ref]$null, [ref]$null)
$functionsInFile = $AbstractSyntaxTree.FindAll({$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]}, $true)
#endregion

$initializeFunction = $null
foreach($function in $functionsInFile)
{
if($function.Name -eq $functionName)
{
$initializeFunction = $function
break
}
}

if($initializeFunction -eq $null){ return 0 }

$initializeFunctionBody = $initializeFunction.Body

return $initializeFunctionBody.Extent.EndLineNumber
}

但是这个脚本也应该在 v2 上运行,我尝试使用 System.Management.Language.PSParser 和 ScriptBlock。但没有任何成功。有人知道如何获取 .ps1 文件中特定函数名称的最后一行(作为 int 或字符串)吗?

编辑:

我认为这里有一些误解:我想获取 .ps1 脚本中特定函数的最后一行。不是函数中特定函数的最后一行。因为我必须在最后将自己的代码添加到这个函数中这是我的脚本的一个简单示例:

测试.ps1

1function test321
2 {
3 Write-Host "test3142"
4 }
5
6function test1
7{
8 if($true)
9 {
10 Write-Host "hello"
11 }
12 #comment
13
14 Write-host "end"
15
16}
17
18function test2
19{
20 #bla
21}

我想要一个名为 e.g. 的函数像 GetEndLineNumber($scriptFile, $functionName) 它应该像这样工作:

测试2.ps1

$path = "C:\Scripts\test.ps1"
$lastLine = GetEndLineNumber $path "test1"

$lastLine should be in this case 15 or 16.

最佳答案

在 PowerShell V2 中,我们可以使用 System.Management.Automation.PSParser 并执行一些操作使用生成的 token 解析我们自己:

function GetEndLineNumber {
param(
$scriptFile,
$functionName
)

$code = Get-Content -LiteralPath $scriptFile
$tokens = [System.Management.Automation.PSParser]::Tokenize($code, [ref]$null)

$waitForFuncName = $false
$funcFound = $false
$level = 0

foreach($t in $tokens) {
switch($t.Type) {
Keyword {
if ($t.Content -eq 'function') {
$waitForFuncName = $true
}
}
CommandArgument {
if ($waitForFuncName) {
$waitForFuncName = $false
$funcFound = $t.Content -eq $functionName
}
}
GroupStart {
++$level
}
GroupEnd {
--$level
if ($funcFound -and $level -eq 0 -and $t.Content -eq '}') {
return $t.StartLine
}
}
}
}
}

我没有彻底测试它,但我尝试了一些函数和脚本,它返回正确的行号。

关于function - 获取 .ps1 文件中特定函数的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com