&&
is notoriously hard to search for on Google Search, but the best I\'ve found is this article which says to use -and
.
Unfortunatel
In CMD, '&&' means "execute command 1, and if it succeeds, execute command 2". I have used it for things like:
build && run_tests
In PowerShell, the closest thing you can do is:
(build) -and (run_tests)
It has the same logic, but the output text from the commands is lost. Maybe it is good enough for you, though.
If you're doing this in a script, you will probably be better off separating the statements, like this:
build
if ($?) {
run_tests
}
2019/11/27: The &&
operator is now available for PowerShell 7 Preview 5+:
PS > echo "Hello!" && echo "World!"
Hello!
World!
A verbose equivalent is to combine $LASTEXITCODE
and -eq 0
:
msbuild.exe args; if ($LASTEXITCODE -eq 0) { echo 'it built'; } else { echo 'it failed'; }
I'm not sure why if ($?)
didn't work for me, but this one did.
If your command is available in cmd.exe (something like python ./script.py
, but not PowerShell command like ii .
(this means to open the current directory by Windows Explorer)), you can run cmd.exe within PowerShell. The syntax is like this:
cmd /c "command1 && command2"
Here, &&
is provided by cmd syntax described in this question.
I think a simple if
statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:
# Set the first command to a variable
$a=somecommand
# Temporary variable to store exit status of the last command (since we can't write to "$?")
$test=$?
# Run the test
if ($test=$true) { 2nd-command }
So for the OP's example, it would be:
a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }
Just install PowerShell 7 (go here, and scroll and expand the assets section). This release has implemented the pipeline chain operators.
&& and || were on the list of things to implement (still are) but did not pop up as the next most useful thing to add. The reason is that we have -AND and -OR. If you think it is important, please file a suggestion on Connect and we'll consider it for V3.