[英]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:
我有一个 PowerShell 脚本,它使用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.由于
ArgumentList
不能为 NULL 也不能为空,因此我必须添加if-else
以避免出现ParameterArgumentValidationError错误。
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.一切都按预期工作,没有问题,但我只是想知道是否有更优雅(但仍然简单)的方法来完成它而无需使用
if-else
块。
You can use the "splat" operator to dynamically add parameters. 您可以使用“ splat”运算符动态添加参数。
Define a hash with keys for parameter names. 定义带有参数名称键的哈希。 And then pass that to the cmdlet:
然后将其传递给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. 有一种方法可以使用splat运算符
@
(请参阅Richard回答),也可以使用带条件的格式字符串。 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. 但是,我认为
If-else
语句是执行此操作的最易读和清晰的方法 ,我不会尝试简化它。
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.我正在使用 Powershell 7 并且没有这个问题,我在 function 中运行
Start-Process -ArgumentList $args
其中$args
有时是 null 并且它工作正常。
However, my script does not run on Windows PowerShell.但是,我的脚本没有在 Windows PowerShell 上运行。
It looks like Powershell 7 no longer requires you to have the if-else statement here.看起来 Powershell 7 不再要求您在此处使用 if-else 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.