PowerShell $args probleme [duplicate]

非 Y 不嫁゛ 提交于 2019-12-11 07:06:28

问题


I try to make this script working

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
}

When I call the function with arguments

test_var "c" "$b" "$a" 

The function work correctly but I can't display the name of the actual $arg because the value was empty .


回答1:


Like Mathias mentioned in his comment, your question is a bit unclear. However:

PowerShell already has a built-in mechanism to validate arguments. Instead of using $args consider using predefined arguments for your function. In the following example, the argument $a is mandatory whereas $b is optional:

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

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

}


来源:https://stackoverflow.com/questions/43341573/powershell-args-probleme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!