PowerShell $ args问题

时间:2017-04-11 09:13:06

标签: powershell powershell-v3.0

我尝试让这个脚本正常工作

Function test_var
{$return = 0
foreach ($arg in $args)
{ 
if (!$arg) {(Write-Host "ERROR : $arg.Name Missing variable" -ForegroundColor Red -BackgroundColor Black)
$return = 1}
}
return $return
}

当我用参数

调用函数时
test_var "c" "$b" "$a" 

该功能正常运行但我无法显示实际$arg的名称,因为该值为空。

1 个答案:

答案 0 :(得分:2)

像Mathias在评论中提到的那样,你的问题有点不清楚。但是:

PowerShell已经有一个内置机制来验证参数。而不是使用$args考虑为您的函数使用预定义的参数。在以下示例中,参数$a必需,而$b是可选的:

function Test-Var
{
    Param
    (
        [Parameter(Mandatory=$true)]
        $a,

        [Parameter(Mandatory=$false)]
        $b
    )

}