mardi 1 décembre 2020

Passing $args[x] in an if statement in .ps1 (PowerShell) does not seem to work when it does not exist

Suppose I have the following testArgsX.ps1 file:

$ARG_X_PARAMETER=1
If ($args[0] -ne "") {
    echo ARGS[X]="`"$args[0]`""
    $ARG_X_PARAMETER=$args[0]
}
echo ARG_X_PARAMETER=$ARG_X_PARAMETER

When I execute it either in a command prompt (C:\Test> powershell .\testArgsX.ps1) or in PowerShell prompt (PS C:\Test> .\testArgsX.ps1), it outputs the following:

ARGS[X]="[0]"
ARG_X_PARAMETER=

It seems that $args[0], in the if-condition, is not interpreted as a scalar value. Although I understand there are 2 ways to circumvent this problem (shown below). I want to know why it does not interpret it as a scalar value and if there is a way to fix it so that it does.

  1. Take out the entire if statement (IF ... { ... }) and replace it with Param ( [Int]$RUN_JUST_ONCE = 1 )
  2. Change the if condition from If ($args[0] -ne "") { to If ($args.Length -gt 0) {

Aucun commentaire:

Enregistrer un commentaire