1

When a parameter is not supplied to my script, I want to include the parameter/variable name as a string in the Write-Error message:

$RequiredArgs = @($Arg1, $Arg2, $Arg3, $Arg4)

foreach ($Arg in $RequiredArgs) {
    if (!($Arg)) {
        Write-Error "Argument: $Arg is required."
        throw
    }
}

This currently outputs Argument: is required.. I have tried quoting the variable name:

Write-Error "Argument: "$Arg" is required."

But this shows the error: Write-Error: A positional parameter cannot be found that accepts argument ' is required.

Is there a way to output the variable name, even if the parameter is not set?

Jelphy
  • 961
  • 2
  • 11
  • 28

2 Answers2

2

Yes, use single quotes:

Write-Error 'Argument: "$Arg" is required.'

Consider to use the Mandatory parameter attribute to specify required paramter in your script:

Param
(
    [Parameter(Mandatory=$true)]
    $Arg1
)

Write-Host "Hello $Arg1"

Now if you try to execute the script and omit the parameter you will get prompted for them: enter image description here

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • This outputs: `Argument: "$Arg" is required.` When: `Argument: "$Arg2" is required` or `$Arg3`, `$Arg4` is expected? – Jelphy Feb 28 '18 at 13:52
0

Apart from what Martin has already mentioned you can do this -

$RequiredArgs = @($Arg1, $Arg2, $Arg3, $Arg4)

foreach ($Arg in $RequiredArgs) {
    if (!($Arg)) {
        Write-Error "Argument: $($Arg) is required."
        throw
    }
}

The $($Arg) syntax helps with evaluating the expression inside $Arg. See this SO link for details.

Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27