【问题标题】:Always append arguments to command in Powershell始终将参数附加到 Powershell 中的命令
【发布时间】:2021-06-24 04:56:14
【问题描述】:

我需要在 Powershell 中重复运行一些命令,在内容和长度上有一些可变参数,但有些参数必须始终存在。我不想忘记这些参数,那么有没有办法创建一个函数来做到这一点?

我尝试过使用Invoke-Expression 之类的东西,但是当我在命令中使用方括号时,Powershell 认为它是一种类型并告诉我我的强制转换无效。如果我转义参数列表并以Key=Value 的形式提供参数,PowerShell 会将其解析为System.Object[],并且命令失败。我认为最好不要问如何解决这个问题,而要问如何解决我的根本问题。

您可以认为这与How to always append an ampersand for certain commands? (MacOS / bash) 有点重复,但适用于 PowerShell。

【问题讨论】:

  • 尝试添加您实际尝试做的代码示例?我假设您尝试附加的命令不是 PS 命令,但您的问题并不清楚。

标签: powershell arguments


【解决方案1】:

只需将您自己的命令版本编写为带有强制参数的函数:

Function RunMyCommand {
    Param(
        [Parameter(Position=0,mandatory=$true)][string]$Argument1,
        [Parameter(Position=1,mandatory=$true)][int]$Argument2,
        [Parameter(Position=2,mandatory=$true)]$Argument3
    )
    # Amend this according to the syntax and string manipulation required for your command
    ThisIsMyCommand $Argument1 $Argument2 $Argument3
}

RunMyCommand -Argument1 ThisString -Argument2 ThisNumber -Argument3 ThisAnything

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多