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

后端 未结 12 866
南笙
南笙 2020-11-29 17:33

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

Unfortunatel

相关标签:
12条回答
  • 2020-11-29 18:11

    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!
    
    
    0 讨论(0)
  • 2020-11-29 18:13

    A verbose equivalent is to combine $LASTEXITCODE and -eq 0:

    msbuild.exe args; if ($LASTEXITCODE -eq 0) { echo 'it built'; } else { echo 'it failed'; }
    

    I'm not sure why if ($?) didn't work for me, but this one did.

    0 讨论(0)
  • 2020-11-29 18:17

    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.

    0 讨论(0)
  • 2020-11-29 18:19

    I think a simple if statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:

    # Set the first command to a variable
    $a=somecommand
    
    # Temporary variable to store exit status of the last command (since we can't write to "$?")
    $test=$?
    
    # Run the test
    if ($test=$true) { 2nd-command }
    

    So for the OP's example, it would be:

    a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }
    
    0 讨论(0)
  • 2020-11-29 18:20

    Just install PowerShell 7 (go here, and scroll and expand the assets section). This release has implemented the pipeline chain operators.

    0 讨论(0)
  • 2020-11-29 18:21

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

    0 讨论(0)
提交回复
热议问题