Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

syntax - Can I get "&&" or "-and" to work in PowerShell?

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

csc /t:exe /out:a.exe SomeFile.cs && a.exe

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...