powershellone-liner

PowerShell - How to achieve this logic as in bash command line { A ; { B && C ;} ;}


I am trying to achieve a specific logic in PowerShell 1-liner that is similar to the following bash command:

{ $another_command_group ;} && { A ; { B && C ;} ;} && { $another_command_group ;}

{ A ; { B && C ;} ;}

The logic of this command is as follows:

  1. A=0, B=0, C=0, then it will execute nothing, and this Command Group will return a 0
  2. A=0, B=0, C=1, then it will execute nothing, and this Command Group will return a 0
  3. A=0, B=1, C=0, then it will execute Command B only, and this Command Group will return a 0
  4. A=0, B=1, C=1, then it will execute Command B and Command C, and this Command Group will return a 1
  5. A=1, B=0, C=0, then it will execute Command A only, and this Command Group will return a 0
  6. A=1, B=0, C=1, then it will execute Command A only, and this Command Group will return a 0
  7. A=1, B=1, C=0, then it will execute Command A and Command B, and this Command Group will return a 0
  8. A=1, B=1, C=1, then it will execute All Command A, B, C, and this Command Group will return a 1

PowerShell version: 7.26

OS: Windows

What I already tried:

| Missing closing ')' in expression.


I am having trouble finding a one-liner Command to replicate this logic in PowerShell. I would greatly appreciate any suggestions or solutions.


Solution

  • Therefore, unfortunately, a hypothetical pipeline chain involving script-block calls (the analog of a group command in Bash (POSIX-compatible shells)) must be broken up into multiple statements involving tests of the automatic $LASTEXITCODE variable, which does reflect the exit code of the most recent external-program / script-file call:

    & { $another_command_group }
    if ($LASTEXITCODE -eq 0) { & { A ; B && C } }
    if ($LASTEXITCODE -eq 0) { & { $another_command_group } }
    

    However, as you've discovered yourself - if practical - you can reformulate a script-block call to a logically equivalent single pipeline chain, whose success status does work as expected.

    The example you provided is that & { A ; (B && C) } (which itself is the loose analog of command group { A ; { B && C ;} ;} from your Bash command) can be reformulated as a single pipeline chain as follows:

    ( ( A && B && C ) || ( B && C ) )
    

    The above preserves the success status of whatever program executes last, and can therefore be used as-is in a larger pipeline chain.