How do I optionally specify parameters in Powershell?

Solution 1:

Part of the problem with your "like" example is that it's grouping everything that comes after cmd.exe and passing it to Start-Process as a single-string second positional parameter which is ArgumentList. So you're effectively running this:

Start-Process -FilePath 'cmd.exe' -ArgumentList "-argumentlist /k dir F:\ -windowstyle Minimized"

Splatting might help you out a bit here. You can use a hashtable to dynamically build the set of parameters that get sent before you actually call Start-Process. For example:

# initialize a hashtable we'll use to splat with later
# that has all of the params that will always be used.
# (it can also be empty)
$startParams = @{
    FilePath = 'cmd.exe'
}

# conditionally add your WindowStyle
if ($ws) {
    $startParams.WindowStyle = $ws
}

# conditionally add your ArgumentList
if ($parameters) {
    $startParams.ArgumentList = $parameters
}

# run the function with the splatted hashtable
Start-Process @startParams