powershellsyntaxcommand-line-arguments

How do I do the bash equivalent of $PROGPATH/program in Powershell?


In GNU/Linux I would do:

PROGPATH=/long/and/complicated/path/to/some/bin
$PROGPATH/program args...

but in Powershell if I try this:

$PROGPATH=\long\and\complicated\path\to\some\bin
$PROGPATH\program args...

I get:

At script.ps1:2 char:...
+ $PROGPATH\program args ...
+          ~~~~~~~~
Unexpected token '\program' in expression or statement.
+ CategoryInfo          : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken

So how do I do this simple thing I know how to do in bash, in Powershell?


Solution

  • js2010's helpful answer shows the correct solution:

    Because your command name/path contains a variable reference ($PROGPATH/...), you must invoke it with &: & $PROGPATH\program args...
    The same applies if a grouping expression, (...) is used, or a subexpression, $(...) is involved.

    Additionally, the same applies if a command name/path is quoted ('...' or "...")[1], as is required if the path contains spaces, for instance.

    To put it differently: Direct invocation is only supported if the command name/path is a verbatim, unquoted string[1]; in all other cases, & must be used.

    As for why:

    &, the call operator is necessary to force interpretation of a statement as a command, i.e. to have it parsed in argument mode (see below), so as to result in command execution rather than expression evaluation.

    PowerShell has two fundamental parsing modes:

    PowerShell decides based on a statement's first token what parsing mode to apply:

    If, among other things, the first token starts with a variable reference or is a quoted string, PowerShell parses in expression mode.


    [1] Note that if your executable path is a literal string (doesn't contain variable references of expressions) you may alternatively `-escape individual characters (spaces) in lieu of enclosing entire string in '...' or "...", in which case & is then not necessary; e.g.:
    C:\Program` Files\Notepad++\notepad++.exe
    With a literal string you can even employ partial single- or double-quoting as long as the first token is unquoted; e.g.:
    C:\"Program Files"\Notepad++\notepad++.exe