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
  • 4,051
  • 2
  • 14
  • 19

3 Answers3

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
  • 45,022
  • 8
  • 78
  • 119
Richard
  • 106,783
  • 21
  • 203
  • 265
  • 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
  • 56,134
  • 13
  • 133
  • 172
0

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.

Noel H
  • 71
  • 1
  • 2