Reputation: 4527
I've simplified my situation as much as possible. I have a PowerShell script that programmatically starts a process with the "Run as administrator" option using the Start-Process cmdlet:
param
(
# Arguments to pass to the process, if any
[string[]] $ArgList
)
if($ArgList)
{
Start-Process -FilePath notepad.exe -ArgumentList $ArgList -Verb RunAs
}
else
{
Start-Process -FilePath notepad.exe -Verb RunAs
}
Since ArgumentList
cannot be NULL nor empty, I had to add the if-else
to avoid a ParameterArgumentValidationError error.
Everything works as expected with no problem, but I was just wondering if there's a more elegant (but still simple) way to accomplish that without using the if-else
blocks.
Upvotes: 3
Views: 3549
Reputation: 111
I am using Powershell 7 and do not have this problem, I run
Start-Process -ArgumentList $args
in a function where $args
is sometimes null and it works fine.
However, my script does not run on Windows PowerShell.
It looks like Powershell 7 no longer requires you to have the if-else statement here.
Upvotes: 0
Reputation: 109005
You can use the "splat" operator to dynamically add parameters.
Define a hash with keys for parameter names. And then pass that to the cmdlet:
$extras = @{}
if (condition) { $extras["ArgumentList"] = whatever }
Start-Process -FilePath = "notepad.exe" @extras
Upvotes: 6
Reputation: 58931
There is a way using the splat operator @
(see Richard answerd) and maybe using a format string with a condition. However, I think the If-else
Statement is the most readable and clear way to do this and I wouldn't try to simplify it.
Upvotes: 0