4

In terminal I used to run two commands at once using '&&' operator. For example if I want to compile and run C source code I only need to write: gcc code.c && ./a.out. But unfortunately it doesn't work in Powershell. How can I do this? And I'm sorry I couldn't find any easier method to do this. Therefore, I had to post it here! TIA!

bipll
  • 11,747
  • 1
  • 18
  • 32
Afif Al Mamun
  • 199
  • 1
  • 11
  • 1
    PowerShell does not support a `&&` construct. If you want to write a command which does this for you, check out [this](https://stackoverflow.com/q/8693675/712526) – jpaugh Feb 15 '18 at 17:20
  • 1
    (Take a look specifically at how to use [`$?`](https://stackoverflow.com/a/8693888/712526)) – jpaugh Feb 15 '18 at 17:22
  • Thank you. I am going to look at it. I had no idea that '&&' doesn't work in powershell. In cmd it works just fine. I am new with VSCode. They have only powershell there. It would be easier for me if it worked in PS. – Afif Al Mamun Feb 15 '18 at 17:27
  • Possible duplicate of [Multiple statements using &&](https://stackoverflow.com/questions/16012046/multiple-statements-using) – Bill_Stewart Feb 15 '18 at 17:36
  • 2
    Possible duplicate of [Can I get && to work in Powershell?](https://stackoverflow.com/questions/563600/can-i-get-to-work-in-powershell) – zdan Feb 15 '18 at 18:00
  • Vote here: [GitHub](https://github.com/PowerShell/PowerShell/issues/3241) and here: [UserVoice](https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/11087898-implement-the-and-operators-that-bash-has) – pilau Feb 07 '19 at 10:23

3 Answers3

8

After searching here and there I found out '&&' doesn't work in PS. There is '-and' command in lieu of '&&'. But in my case I actually wanted to execute two command at once and it didn't work. I found a way to do this. A simple semicolon could do the work. For example: If I want to compile and run a C++ code, I just need to write g++ /directory/code.cpp; ./a.exe. But if someone uses this they should be aware of that the second command will work even though the first one doesn't execute due to any error unlike the '&&' operator!

Afif Al Mamun
  • 199
  • 1
  • 11
0

You can use a semicolon [;] . Something like this:

(command); (command)

(Write-Host "this");  (Write-Host " or that")

(gcc .\code.c);  (.\a.out)
Kevin Bridges
  • 176
  • 2
  • 10
0

Check here if you really need the abortive nature of the && and not just "two commands, one line".

$ErrorActionPreference="Stop"
# Line break
fakeCommand; echo "Here"
Chris
  • 5,788
  • 4
  • 29
  • 40