pico
pico

Reputation: 1910

In powershell, getting pre-invocation arguments of a function after calling param?

Let's say I have a function that I call like this:

myfunction -msg1 'this is message 1'  -msg2 'this is message2'

And here is my function:

function myfunction {
    param([string]$msg1, [string]$msg2)

    #HOW WOULD I Get the pre-invocation argument the function here? that is:
    $preinvoke = @( "-msg1", 'this is message 1', '-msg2', 'this is message2')

    write-host "You called this command like this: myfunction $preinvoke"
}   
     

Is there a way to automatically set $preinvoke based on there real flags to the function after calling param? My impression is that param eats all the arguments... I want the list of pre-invokation arguments to the function after calling param.

Upvotes: 0

Views: 115

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Use the $MyInvocation automatic variable:

function Test-Invocation
{
  param([string]$msg1, [string]$msg2)

  # $MyInvocation.Line will give you the originating call
  $originalInvocation = $MyInvocation.Line
  Write-Host "Original invocation: ${originalInvocation}"

  # Which you can then parse/tokenize again if need be
  $tokens = @()
  $AST = [System.Management.Automation.Language.Parser]::ParseInput($originalInvocation, [ref]$tokens, [ref]$null)

  Write-Host "Original Invocation contains the following tokens:"
  foreach($token in $tokens){
    Write-Host ("  {0,15} (flags: {1,20}): '{2}'" -f $token.Kind,$token.TokenFlags,$token.Text)
  }
}

Then use/test like this:

PS ~> Test-Invocation -msg1 'this is message 1'  -msg2 'this is message2'
Original Invocation contains the following tokens:
          Generic (flags:          CommandName): 'Test-Invocation'
        Parameter (flags:                 None): '-msg1'
    StringLiteral (flags:   ParseModeInvariant): ''this is message 1''
        Parameter (flags:                 None): '-msg2'
    StringLiteral (flags:   ParseModeInvariant): ''this is message2''
       EndOfInput (flags:   ParseModeInvariant): ''

Upvotes: 1

Related Questions