Search code examples
syntaxpowershell

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


Note: This question originally asked in 2009, when powershell did not have support for the && operator. In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7. https://stackoverflow.com/a/564092/234


Original Question

&& 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.


Solution

  • 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!
    

    Pay attention though that some cmdlet do not return any value, in which case such command when coerced will return false: