当我的脚本没有提供参数时,我希望在Write-Error
消息中将参数/变量名称包含为字符串:
$RequiredArgs = @($Arg1, $Arg2, $Arg3, $Arg4)
foreach ($Arg in $RequiredArgs) {
if (!($Arg)) {
Write-Error "Argument: $Arg is required."
throw
}
}
目前输出Argument: is required.
。我试过引用变量名:
Write-Error "Argument: "$Arg" is required."
但是这显示错误:Write-Error: A positional parameter cannot be found that accepts argument ' is required.
有没有办法输出变量名,即使没有设置参数?
答案 0 :(得分:2)
是的,使用单个引号:
Write-Error 'Argument: "$Arg" is required.'
考虑使用强制参数属性在脚本中指定所需的参数:
Param
(
[Parameter(Mandatory=$true)]
$Arg1
)
Write-Host "Hello $Arg1"
答案 1 :(得分:0)
除了马丁已经提到的你可以做到这一点 -
$RequiredArgs = @($Arg1, $Arg2, $Arg3, $Arg4)
foreach ($Arg in $RequiredArgs) {
if (!($Arg)) {
Write-Error "Argument: $($Arg) is required."
throw
}
}
$($Arg)
语法有助于评估$Arg
中的表达式。有关详细信息,请参阅this SO链接。