Pipeline Chain operators

Another experimental feature from PowerShell v7 preview 5 brings pipeline chain operators to PowerShell.

PS> Get-ExperimentalFeature -Name PSPipelineChainOperators | Format-List Name, Description

Name        : PSPipelineChainOperators

Description : Allow use of && and || as operators between pipeline invocations

The operators work as follows

<command1> && <command2>  means that command2 will fire if command1 completes without errors

You could write that in PowerShell now as

<command1>;  if ($?) { <command2> }

If command1 works and $? is $true (no errors) fire command2

<command1> || <command2>  means that command2 will fire if command1 has errors

i.e.

<command1>;  if (-not $?) { <command2> }

Like all experimental features it has to be enabled and PowerShell restarted

PS> Enable-ExperimentalFeature -Name PSPipelineChainOperators

WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell.

The best way to explain these operators is to show some examples

This is from the RFC

PS> 1,2,3 | ForEach-Object { $_ + 1 } && Write-Output ‘Hello’

2

3

4

Hello

PS> Get-Item -Path c:\nosuchfile -ErrorAction SilentlyContinue || Write-Output ‘ERROR’

ERROR

The message is written because the file isn’t found

PS> $path = ‘C:\test\DebugJob2.ps1’

PS> Get-Item -Path $path -ErrorAction SilentlyContinue && Remove-Item -Path $path

results in the file being deleted

Subsequently running

PS> Get-Item -Path $path -ErrorAction SilentlyContinue || Write-Output ‘No such file’

No such file

generates the message because the file isn’t there.

The chain operators work if there’s an error or not with the execution of command1 so you can’t use the test cmdlets such as Test-Path because they return booleans.

These operators follow the bash model of working on errors which isn’t necessarily the way PowerShell will work for you. I’m in two minds as to whether these operators are useful or not as the examples above feel contrived and I’m not convinced at the moment that the mental gymnastics required to accommodate  these operators in my code are worth it. Time will tell.

This entry was posted in PowerShell 7. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s