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!
&& 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.
Try this:
$errorActionPreference='Stop'; csc /t:exe /out:a.exe SomeFile.cs; a.exe
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.
PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True
($MyVar -ne $null)
returned true and (Get-Content $MyVar)
also returned true.
PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False
($MyVar -ne $null)
returned false and so far I must assume the (Get-Content $MyVar)
also returned false.
PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False
($MyVar -ne $null)
returned false and proved the second condition (Get-Content "C:\MyTxt.txt")
never ran, by returning false on the whole command.
Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and
as follows:
(build_command) -and (run_tests_command)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With