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
Call the function with only the required inputs
Now call the first function with as many dynamic parameters as you like. For example
Hope this helps you out and if it does, please let me know.
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
Post a Comment
Comments with irrelevant links will be deleted.