I need to run a .exe with parameters, currently this takes two lines. I would like to be able to pass a string as a variable to a function, and only need to do this once.
This is how I am currently doing it, which takes two variables:
function Foo{
$ExeToStart = "C:\Program Files\x\program.exe"
Start-Process $ExeToStart -ArgumentList "--arg1","--arg2"
}
Is there a way of combining this so that I can just define a variable, "y" and pass it into the function as one line similar to below?
$x = "C:\Program Files\x\program.exe -ArgumentList "--arg1","--arg2""
function Foo{
Start-Process $x
}
Here is a way you can achieve what you want.
# Create an array of the program and arguments
$x = 'C:\Program Files\x\program.exe','--arg1','--arg2'
# Example with no parameters
Function Foo {
Start-Process -FilePath $args[0][0] -ArgumentList $args[0][1..$args[0].Count]
}
# Example using parmeters
Function Foo {
param([string[]]$program)
$params = @{
FilePath = $program[0]
}
if ($program.Count -gt 1) {
$params['ArgumentList'] = $program[1..$program.Count]
}
Start-Process @Params
}
# Call the function
Foo $x