Last updated: Apr 4, 2024
Reading time·3 min
The error "The token '&&' is not a valid statement separator in this version"
occurs because the two ampersand characters &&
are not a valid statement
separator in PowerShell.
There are multiple ways to resolve the issue:
;
character to run the command separately.-and
statement separator.Here is an example of how the error occurs.
echo "bobby" && echo "hadz"
Running the command in PowerShell produces the following error.
The token '&&' is not a valid statement separator in this version. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidEndOfLine
One way to solve the error is to rerun the command in CMD (Command Prompt) or Git Bash.
To open CMD (Command Prompt):
Click on the search field and type cmd
:
Start the Command Prompt application.
echo "bobby && echo "hadz"
To open Git Bash (assuming you have Git installed):
git bash
.echo "bobby && echo "hadz"
Alternatively, you can use a semicolon separator in PowerShell.
echo "bobby" ; echo "hadz"
The semicolon separates the two commands, just like a semicolon is used to separate statements in programming languages (e.g. JavaScript).
However the semicolon ;
in PowerShell results in the unconditional sequencing
of commands.
&&
which only executes the right-hand side of the command on the left-hand side succeeds.The ||
(or) characters do the inverse - the right-hand side is only executed
if the left-hand side fails.
&&
in PowerShellIn some cases, you might only want to run the right-hand side if the left-hand side succeeds.
You can do this by using an if
statement.
echo "bobby"; if ($?) {echo "hadz"}
The $?
variable is a boolean that indicates whether the most recent command
has succeeded.
If this suits your use case, you could also run the commands one after the other.
The two ampersand &&
characters are meant to glue the two commands together.
You can split the commands on each usage of the &&
characters.
echo "bobby" echo "hadz"
-and
option when running the PowerShell commandYou can also use the -and
option instead of &&
when running the PowerShell
command.
echo "bobby" -and echo "hadz"
Notice that the and
is prefixed with a hyphen, so it becomes -and
.
Note that the &&
and ||
operators are available in PowerShell 7 and more
recent versions.
&&
and ||
are known as the
Pipeline chain operators
in PowerShell 7.
You can learn more about the related topics by checking out the following tutorials: