Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Call-Operator(&) with Parameters from Variable

Tags:

powershell

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?

like image 694
Fabian Fulde Avatar asked Oct 01 '18 08:10

Fabian Fulde


2 Answers

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:

  • double dash syntax for unix style --param1 value1
  • Slash syntax for Windows style /param1 value1
  • Equals sign required (or colon) -param1=value1 or -param1:value1
  • No value for parameter -boolean_param1
  • additional verbs (values without a param name) 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
like image 70
Tomer W Avatar answered Sep 27 '22 01:09

Tomer W


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
like image 27
henrycarteruk Avatar answered Sep 25 '22 01:09

henrycarteruk