3

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.

mguassa
  • 3,491
  • 2
  • 13
  • 19

2 Answers2

6

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
Matt
  • 42,566
  • 8
  • 67
  • 104
Richard
  • 103,472
  • 21
  • 199
  • 258
  • 1
    Thank you, I didn't know the splat operator. That's not complicated at all but I think the original code is more readable so I'll probably keep my _if-else_ blocks. Answer upvoted though. – mguassa Jul 10 '15 at 12:09
  • @mguassa Your solution might look cleaner, but it is NOT a good idea in general, as it involves duplication of code and maintaining duplicate pieces of code. This answer - is the right way to do it. – Alek May 10 '20 at 06:35
0

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.

Martin Brandl
  • 51,813
  • 12
  • 118
  • 151