问题
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