G'day everyone,
I'm trying to execute a function in PowerShell with the Parameters coming from a Variable I'm not sure if it's possible in the way I want it to but maybe someone has any idea how I would go about doing that.
$scriptPath = "C:\temp\Create-File.ps1"
$parameters = "-Path C:\temp\testfile.txt -DoSomethingSpecial"
& $scriptPath $parameters
Something along those lines, I don't know in which order the Parameters get entered so I can't use $args[n..m] or binding by position for that. Maybe there is some other Cmdlet I don't know about that is capable of doing that?
Passing an Object as @James C. suggested in his answer allows only to pass parameters in Powershell syntax (e.g. -param1 value1 -param2 value2
)
When you need more control over the parameters you pass such as:
--param1 value1
/param1 value1
-param1=value1
or -param1:value1
-boolean_param1
value1 value2
you can use an array instead of an object
take ipconfig
command for example to renew all connections with "con" in their name:
$cmd = "ipconfig"
$params = @('/renew', '*Con*');
& $cmd $params
or the specific question given example:
$params = @('-Path', 'C:\temp\testfile.txt', '-DoSomethingSpecial')
.\Create-File.ps1 @params
You can use a hastable and Splatting to do this.
Simply set each param name and value in the variable as you would a normal hastable, then pass this in using @params
syntax.
The switch param however, needs a $true
value for it to function correctly.
$params = @{
Path = 'C:\temp\testfile.txt'
DoSomethingSpecial = $true
}
.\Create-File.ps1 @params
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With