当ArgumentList为空时,PowerShell Start

编程入门 行业动态 更新时间:2024-10-20 15:50:02
当ArgumentList为空时,PowerShell Start-Process cmdlet(PowerShell Start-Process cmdlet when ArgumentList is empty)

我尽可能地简化了我的情况。 我有一个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
}
 

由于ArgumentList不能为NULL也不为空,我必须添加if-else以避免ParameterArgumentValidationError错误。

一切都按预期工作没有问题,但我只是想知道是否有更优雅(但仍然很简单)的方法来实现,而不使用if-else块。

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.

最满意答案

有一种方法可以使用splat运算符@ (参见Richard answerd)并使用带有条件的格式字符串。 但是,我认为If-else语句是最可读和最清晰的方法 ,我不会尝试简化它。

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.

更多推荐

本文发布于:2023-07-24 00:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   ArgumentList   Start   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!