Возможно ли в Powershell вызвать неизвестную сигнатуру функции «например, System.Data.DataTable DoWork (HashTable Row)» в неизвестном файле? - PullRequest
0 голосов
/ 25 января 2019

Можно ли в Powershell вызывать сигнатуру известной функции «например, System.Data.DataTable DoWork (HashTable Row)» в неизвестном файле?

Я хотел бы написать скрипт, который бы смотрел в каталог, и для каждого найденного скрипта PS найдите функцию DoWork и вызовите ее.

Возможно ли это?

Ответы [ 3 ]

0 голосов
/ 25 января 2019

Вы можете использовать синтаксический анализатор , чтобы обнаружить вызов определенных членов объекта (например, имя функции DoWork):

foreach($scriptFile in Get-ChildItem .\script\folder\ -Filter *.ps1){
    # Parse file
    $AST = [System.Management.Automation.Language.Parser]::ParseFile($scriptFile.FullName,[ref]$null,[ref]$null)

    # Look for invocations of `.DoWork()`
    $DoWorkExpressions = $AST.FindAll({
        $args[0] -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and
        $args[0].Member.Value -eq 'DoWork'
    }, $true)

    if($DoWorkExpressions.Count -gt 0){
        # There's a call to .DoWork() in $scriptFile
        # Do further AST analysis or execute the file
    }
}
0 голосов
/ 25 января 2019

Благодаря Матиасу Р. Йессену у меня есть решение ниже:

foreach($scriptFile in Get-ChildItem .\Test\ -Filter *.ps1){
    # Parse file
    $AST = [System.Management.Automation.Language.Parser]::ParseFile($scriptFile.FullName,[ref]$null,[ref]$null)
    $scriptName = $scriptFile.Name.Replace(".", "_");

    # Look for invocations of `.DoWork()`
    $DoWorkExpressions = $AST.FindAll({ param($p) 
        $p -is [System.Management.Automation.Language.FunctionDefinitionAst] -and
        $p.Name -eq 'DoSomething'
    }, $true)

    if($DoWorkExpressions.Count -gt 0){
        # There's a call to .DoWork() in $scriptFile
        # Do further AST analysis or execute the file
        $newFunctionName = $scriptName + '_' + $DoWorkExpressions[0].Name;
        $newFunction = 'function ' + $newFunctionName + $DoWorkExpressions[0].Body.Extent.Text;

        # invoke part
        Write-Output $newFunction

        Invoke-Expression $newFunction
        $result = &$newFunctionName 'bob'
        Write-Output "${newFunctionName} 'bob' = $result"
    }
}
0 голосов
/ 25 января 2019

Это решение, которое я придумал. Это не совсем завершено.

foreach file in my directory{

    load file contents and set $myFunction{

        $myFunction = "function write-greeting { param([string] `$a) return ""hello world `$a""; }"
        Write-Output $myFunction

        Invoke-Expression $myFunction
        $result = write-greeting('bob');

        Write-Output $result
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...