我如何允许powershell接受命名参数的空字符串?

时间:2018-05-01 10:08:49

标签: powershell

我正在调用powershell脚本:

powershell.exe -file basic.ps1 -User ""

我有其他参数,这有点淡化。

PS脚本接受参数:

[CmdLetBinding()]
param(
 [Parameter(Mandatory=$true)]
[AllowEmptyString()]
[string]$User = 't'
)

当我运行命令时,我得到:

  

缺少参数' User'的参数。指定类型为' System.String'的参数。然后再试一次。

我假设AllowEmptyString允许这样做?

1 个答案:

答案 0 :(得分:5)

听起来你根本不想要一个强制参数。强制执行将需要输入,使默认值无效。但是,让我们回到你描述的错误。

该属性按预期工作。问题是你如何调用你的脚本。让我们尝试以下代码作为函数和脚本:

[CmdLetBinding()]
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[string]$User = 't'
)

"`$User has value '$user'. Is it null? $($user -eq $null). Type is $($user.GetType().Name)"

演示:

#Inside a function
PS> t -User ""
$User has value ''. Is it null? False. Type is String

#Inside a script
PS> .\Untitled-5.ps1 -User ""
$User has value ''. Is it null? False. Type is String

#Running the following command from cmd
cmd> powershell.exe -file Untitled-5.ps1 -User "" 
$User has value ''. Is it null? False. Type is String

但是,当您在PowerShell会话中运行最后一行时,PowerShell将解析该字符串,从而导致该参数为空值(无引号)。

PS> powershell.exe -file Untitled-5.ps1 -User "" 
D:\Downloads\Untitled-5.ps1 : Missing an argument for parameter 'User'. Specify a parameter of type 'System.String' and
 try again.
    + CategoryInfo          : InvalidArgument: (:) [Untitled-5.ps1], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument,Untitled-5.ps1

Powershell.exe不适合在PowerShell进程中使用。您可以通过直接在PowerShell进程内调用脚本(第二个示例),从cmd / run / scheduled task ++(其他任何地方)运行PowerShell.exe …或确保PS不解析您的参数来解决此问题。实际上会输入报价。

这可以通过转义引号

来完成
PS> powershell -File Untitled-5.ps1 -User `"`"

或使用--%

PS> powershell -File Untitled-5.ps1 --% -User ""