PowerShell - Pass Dynamic Arguments from Function to Function

If you are interested in passing dynamic arguments from function to function in PowerShell, I think the following will help you out:

Create the function(s) like this
function MyFunction1 {
  [CmdletBinding()]
  param (
    [string]$requiredParm1,
    [string]$requiredParm2,
  
    [parameter(ValueFromRemainingArguments=$True)]
    $dynamicArgs
  )

  $props = @()

  if($dynamicArgs) {
      $num = 0
      for ($num = 0; $num -lt $dynamicArgs.Count; $num = $num + 2)
      {
          $format_string = (([string]$dynamicArgs[$num]) + " '"  + [string]$dynamicArgs[$num+1] + "' ``")
          $props += $format_string
      }
  }
  
  $string_props = $($props | Out-String)

  $second_function = "MyFunction2 -requiredParm1 $requiredParm1 "
  $second_function += "-requiredParm2 $requiredParm2 "
  $second_function += "$string_props;"

  Invoke-Expression $second_function
}

function MyFunction2 {
  [CmdletBinding()]
  
  param (
    [string]$requiredParm1,
    [string]$requiredParm2,
  
    [parameter(ValueFromRemainingArguments=$True)]
    $dynamicArgs
  )
  
  # Do work with values...
  $props = @()
  
  if($dynamicArgs) {
      $num = 0
      for ($num = 0; $num -lt $dynamicArgs.Count; $num = $num + 2)
      {
          $format_string = (([string]$dynamicArgs[$num]) + " '"  + [string]$dynamicArgs[$num+1] + "' ")
          $props += $format_string
      }
  }

  $out_string $($props | Out-String)
  Write-Host $out_string
  # Process the $out_string how you like or pass to a function that expects dynamic args
  
}

Call the function with only the required inputs
MyFunction1 -requiredParm1 'foo' -requiredParm2 'bar' # no output
#And the output should be just a new line

Now call the first function with as many dynamic parameters as you like. For example
MyFunction1 -requiredParm1 'foo' -requiredParm2 'bar' -something 'special' -something2 'case'
And the output should be:
-something 'special'
-something2 'case'

Hope this helps you out and if it does, please let me know.

Comments

Popular posts from this blog

Azure DevOps - Auto Approve PR with PAT

Ubuntu 18.04 - Install Android Emulator

Ansible Module - VMWare Update Guest PCI Device