Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用powershell从文件中提取函数体_Powershell - Fatal编程技术网

使用powershell从文件中提取函数体

使用powershell从文件中提取函数体,powershell,Powershell,如何提取powershell函数定义的内容? 假设代码是这样的 Function fun1($choice){ switch($choice) { 1{ "within 1" } 2{ "within 2" } default{ "within default" } } } fun1 1 我只需要函数定义的内容,不需要其他文本。使

如何提取powershell函数定义的内容? 假设代码是这样的

Function fun1($choice){
   switch($choice)
    {
       1{
        "within 1"
        }
       2{
        "within 2"
        }
       default{
        "within default"
        }

    }

}

fun1 1
我只需要函数定义的内容,不需要其他文本。

使用PowerShell 3.0+AST解析器:

$code = Get-Content -literal 'R:\source.ps1' -raw
$name = 'fun1'

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{
        param ($ast)
        $ast.name -eq $name -and $ast.body
    }, $true) | ForEach {
        $_.body.extent.text
    }
输出$body中的单个多行字符串:

{
   switch($choice)
    {
       1{
        "within 1"
        }
       2{
        "within 2"
        }
       default{
        "within default"
        }

    }

}
要提取第一个函数定义体(不考虑名称),请执行以下操作:

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach {
        $_.body.extent.text
    }
要提取从
函数
关键字开始的整个函数定义,请使用
$\uuu0.extent.text

$fun = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach {
        $_.extent.text
    }

谢谢你的回答。你能推荐一些网站/博客来了解更多这方面的信息吗?我不记得了,但我想我在C#中找到了一些例子并加以改编。也许我的答案中链接了MSDN文档中的内容。