听起来您根本不需要强制参数。使其成为强制性将需要输入,这使得默认值无用。但是,让我们回到您描述的错误。
该属性按预期工作。问题是你如何调用你的脚本。让我们尝试以下代码作为函数和脚本:
[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 ""