Execute process conditionally in Windows PowerShell (e.g. the && and || operators in Bash)

Posted by Dustin on Stack Overflow See other posts from Stack Overflow or by Dustin
Published on 2009-12-16T20:00:25Z Indexed on 2010/04/07 1:23 UTC
Read the original article Hit count: 286

I'm wondering if anybody knows of a way to conditionally execute a program depending on the exit success/failure of the previous program. Is there any way for me to execute a program2 immediately after program1 if program1 exits successfully without testing the LASTEXITCODE variable? I tried the -band and -and operators to no avail, though I had a feeling they wouldn't work anyway, and the best substitute is a combination of a semicolon and an if statement. I mean, when it comes to building a package somewhat automatically from source on Linux, the && operator can't be beaten:

# Configure a package, compile it and install it
./configure && make && sudo make install

PowerShell would require me to do the following, assuming I could actually use the same build system in PowerShell:

# Configure a package, compile it and install it
.\configure ; if ($LASTEXITCODE -eq 0) { make ; if ($LASTEXITCODE -eq 0) { sudo make install } }

Sure, I could use multiple lines, save it in a file and execute the script, but the idea is for it to be concise (save keystrokes). Perhaps it's just a difference between PowerShell and Bash (and even the built-in Windows command prompt which supports the && operator) I'll need to adjust to, but if there's a cleaner way to do it, I'd love to know.

© Stack Overflow or respective owner

Related posts about powershell

Related posts about execute