Home > Mobile >  Run powershell script as administrator via batch file with parameter passing
Run powershell script as administrator via batch file with parameter passing

Time:06-10

When I run the script, without an administrator, via batch file it passes the parameter, but when I run the script, as an administrator, it does not pass the parameter.

I'm trying the command in the link below, but with no success:
enter image description here

Conclusion:
When the script is running, without being an administrator, via a batch file it works correctly even if the parameter used in the script is defined as an environment parameter, eg: [decimal]$env:_vLUF and regardless of the parameter value being negative, eg : -11.0.

Why Powershell when running a script without being as an administrator correctly interprets the minus sign in the argument and when run as an administrator it does not interpret the minus sign correctly is a question I leave to the experts!

However, my question was very well answered by Mr. @mklement0.

CodePudding user response:

Your .ps1 script's parameter declaration is flawed:

Param(
     [decimal]$env:_vLUF  # !! WRONG - don't use $env:
)

It should be:

Param(
     [decimal] $_vLUF  # OK - regular PowerShell variable
)

Parameters in PowerShell are declared as regular variables, not as environment variable ($env:).

(While environment variables can be passed as an argument (parameter value), an alternative is to simply reference them by name directly in the body of your script.)


Your PowerShell CLI call has problems too, namely with quoting.

Try the following instead:

powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -Verb RunAs powershell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"D:\z_Batchs e Scripts\Batchs\Normaliza_LUFS\ArqsNorms_LUFS_pass.ps1\" -_vLUF %_vLUF%'"

Specifically:

  • Embedded " chars. must be escaped as \" (sic) when using the Windows PowerShell CLI (powershell.exe); however, given that %_vLUF% represents a [decimal], you needn't quote it at all.

    • However, you appear to have hit a bug: if the argument starts with -, such as in negative number -11.0, the -File CLI parameter invariably interprets it as a parameter name - even quoting doesn't help.

    • The workaround, as used above is to use a named argument, i.e. to precede the value with the target parameter name: -_vLUF %_vLUF%

  • As an aside: There's no reason to use & { ... } in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use ... directly, as shown above. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected.

  • Related