Search code examples
powershellcmdsyntaxgitlab-cicommand-line-arguments

Change command which works in cmd.exe to work in powershell.exe


I have a command which works without issue in cmd.exe:

%TESTING_INSTALLATION_PATH%\\client\\batch.exe --log-level=error --run %CI_BUILDS_DIR%\\autotest\\jobs\\clear.py

But it doesn't work in PowerShell like this:

$TESTING_INSTALLATION_PATH\\client\\batch.exe --log-level=error --run $CI_BUILDS_DIR\\autotest\\jobs\\clear.py

But received this:

строка:1 знак:30
+ $TESTING_INSTALLATION_PATH\\client\\batch.exe --log-level=error  ...
+                             ~~~~~~~~~~~~~~~~~
Unexpected token "\\client\\batch.exe" ........................
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

Solution

    • %TESTING_INSTALLATION_PATH%, for instance, is a cmd.exe-format reference to an environment variable; the equivalent PowerShell expression is therefore: $env:TESTING_INSTALLATION_PATH - see the conceptual about_Environment_Variables help topic.

    • For syntactic reasons, invoking executables whose name or path is quoted and/or contains variable references requires use of the call operator, &.

    • Finally, \ is not special, neither in cmd.exe nor in PowerShell, so there is no need to escape it as \\; cmd.exe's escape char. is ^, whereas PowerShell's is `, the so called backtick.

    Therefore:

    # NOTE:
    #  & to invoke a path containing variable references.
    #  $env: to reference environment variables
    #  Single \ only.
    & $env:TESTING_INSTALLATION_PATH\client\batch.exe --log-level=error --run $env:CI_BUILDS_DIR\autotest\jobs\clear.py