简体   繁体   中英

PowerShell Start-Process cmdlet when ArgumentList is empty

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM