0

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.

2
  • "I want the list of pre-invocation arguments" - why? Commented Oct 25, 2021 at 15:02
  • $PSBoundParameters or $MyInvocation.BoundParameters should give you what you're looking for. Commented Oct 25, 2021 at 15:09

1 Answer 1

1

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): ''
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.