【问题标题】:How to specify optional argument for a command operator invokation?如何为命令运算符调用指定可选参数?
【发布时间】:2019-07-02 01:06:40
【问题描述】:

我有以下命令调用

& ".\script1.ps1" -switch1 "$DBN" "$($Server[-1])" "$Creds" "$ConnectionID" "$ConnectionDataSource"

我想将 ConnectionID 和 Connection DataSource 设为可选

我该怎么做?

此命令仅在我为 ConnectionID 和 Connection Data Source 输入内容时才有效。否则,如果我不为这两个参数输入任何内容,它们将不起作用!

这里是这个 script1.ps1 中的参数(我称之为 IN script2.ps1):

param(
[Parameter(Mandatory=$true)]
    [string]$DBN,

[Parameter(Mandatory=$true)]
    [string]$Server,

[Parameter(Mandatory=$false)]
[ValidateScript({![string]::IsNullOrEmpty($_.Trim())})]
    [string]$Creds,

[Parameter(Mandatory=$false, HelpMessage="Enter a UserID for the connection")]
[ValidateScript({![string]::IsNullOrEmpty($_.Trim())})]
[string]$ConnectionID, 

[Parameter(Mandatory=$false, HelpMessage="Enter a Data Source for the connection. Must enter the ConnectionID first")]
[ValidateScript({![string]::IsNullOrEmpty($_.Trim())})]
[string]$ConnectionDataSource
)

这里是这个 script2.ps1(我从中调用 script1.ps1)中的参数:

param(
[Parameter(Mandatory=$true)]
    [string]$DBN,

[Parameter(Mandatory=$false, HelpMessage="Enter a UserID for the connection")]
[string]$ConnectionID, 

[Parameter(Mandatory=$false, HelpMessage="Enter a Data Source for the connection. Must enter the ConnectionID first")]
[string]$ConnectionDataSource
)

在没有这 2 个输入的情况下运行 script1.ps1 就可以了。

我是这样运行的:

PS> script1.ps1 DB1 Server1

所以我知道我必须在我调用 script1 的第二个脚本的调用运算符中做一些事情

我正在寻找这样的东西:

& ".\script1.ps1" -switch1 "$DBN" "$($Server[-1])" "$Creds" [optional]"$ConnectionID" [optional]"$ConnectionDataSource"

【问题讨论】:

  • 可能会抛出If 声明。 if(-not $ConnectionID) { $ConnectionID = "Default Value"} 这将允许您提供或不提供连接 ID。如果没有连接 ID,那么它将默认为某物。
  • @Drew 不幸的是,参数必须是动态的。它要么是用户输入的,要么是来自 HashVault 的默认值:/
  • 其他参数能不能不漏写?我认为您可以使用ValueFromRemainingArguments 解决它。
  • @rokumaru 很有趣,你可以详细说明你的意思,不要省略
  • @Cataster 如 Shadowfax 所述,在您的问题中发布 COMPLETE PARAM 块!

标签: powershell


【解决方案1】:

想通了!这是因为我在 script1.ps1 参数中有这个

[ValidateScript({![string]::IsNullOrEmpty($_.Trim())})]

通过注释掉,甚至用[AllowNull] 属性替换它,它就可以工作了!

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 2021-06-18
    • 2023-03-28
    • 1970-01-01
    • 2012-11-12
    • 2017-07-30
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多