2

スクリプトの 2 点間で定義されている関数を特定するにはどうすればよいですか?

例えば

function dontCare()
{}
# Start here
function A()
{}

function B()
{}
# Know that A and B have been defined

この2点で差を取ろうと考えてGet_ChildItem function:*いたのですが、関数が定義されているとうまくいきません。

4

3 に答える 3

1

スクリプトを解析し、すべての関数を一覧表示して、結果のロジックを簡単にすることができます。

$content = Get-Content .\script.ps1
$tokens = [System.Management.Automation.PSParser]::Tokenize($content,[ref]$null)

for($i=0; $i -lt $tokens.Count; $i++)
{
    if($tokens[$i].Content -eq 'function')
    {
        $tokens[$i+1]
    }
}

vでは、ASTを使用することもできます。RaviによるISE関数エクスプローラーアドオンを参照してください: http ://www.ravichaganti.com/blog/?p = 2518

于 2013-01-05T10:30:26.017 に答える
1

それがどのように機能するかはわかりません。スクリプトで関数を定義する場合は、関数を定義することを知っておく必要があります。他のスクリプトをドットソーシングしていますか?

そうでない場合は、これでそこにたどり着くはずです(スクリプトの実行前に A と B が定義されていたとしても):

# NewScript.ps1
function dontCare()
{}
# Start here
$Me = (Resolve-Path -Path $MyInvocation.MyCommand.Path).ProviderPath

$defined = ls function: | 
    where { $_.ScriptBlock.File -eq $Me } |
    foreach { $_.Name }

function A()
{}

function B()
{}
# Know that A and B have been defined
ls function: |
    where { 
        $_.ScriptBlock.File -eq $Me -and
        $defined -notcontains $_.Name
    } |
    foreach { $_.Name }
# end of script body, trying it...

.\NewScript.ps1
A
B

スクリプトをドットソーシングしている場合は、さらに簡単になります。

# NewScript2.ps1
function dontCare2()
{}
# Start here
$He = (Resolve-Path -Path .\NewScript.ps1).ProviderPath

. $He | Out-Null

ls function: |
    where { 
        $_.ScriptBlock.File -eq $He
    } |
    foreach { $_.Name }
# end of script body, trying it...

.\NewScript2.ps1
A
B
dontCare

私にとっては、ドットソーシングのシナリオだけがある程度理にかなっています(外部ソースを使用しているため、それが何を定義しているかはわかりません)が、両方が必要になる可能性があると思いました...;)

于 2013-01-06T09:15:47.573 に答える
0

次のようなことができます。

$exists = get-command -erroraction silentlycontinue A

結果に応じてロジックを分岐できます。

于 2013-01-05T03:44:06.993 に答える