Fabian Fulde
Fabian Fulde

Reputation: 340

Powershell Call-Operator(&) with Parameters from Variable

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?

Upvotes: 8

Views: 9975

Answers (4)

Norbert Nemec
Norbert Nemec

Reputation: 73

Simple solution with minimal change to the original:

$scriptPath = "C:\temp\Create-File.ps1"
$parameters = "-Path C:\temp\testfile.txt -DoSomethingSpecial"

& $scriptPath $parameters.Split()

Upvotes: 0

Tomer W
Tomer W

Reputation: 3443

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

Upvotes: 9

henrycarteruk
henrycarteruk

Reputation: 13237

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

Upvotes: 4

Milad
Milad

Reputation: 479

You can run it by Start-Process

Start-Process powershell -ArgumentList "$scriptPath $parameters"

Upvotes: 2

Related Questions