DEV Community

codemee
codemee

Posted on

PowerShell pipeline chain operator 的小陷阱

PowerShell 7 提供有pipeline chain operator,也就是 &&||,不過使用上必須注意,不然就會遇到意外的結果。

運算子的兩端都要是指令

看到 &&||,很容易就會寫出類似這樣的指令:

 cd \temp && exit
Enter fullscreen mode Exit fullscreen mode

不過這會得到以下錯誤訊息:

exit: The term 'exit' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Enter fullscreen mode Exit fullscreen mode

這是因為 &&|| 的左右兩邊都要是指令(包含 cmdlet、函式、腳本檔、外部程式等),但 exit 是 PowerShell 的保留字,在語法上是陳述句,並不是指令,所以你可以看到錯誤訊息明確表示無法執行 exit

沒有 pipeline 的功能

這組運算子名稱中的 "pipeline" 也很容易誤解,以為他們是有條件的 pipeline,例如,你可能會期望以下指令可以在 \temp 資料夾存在的情況下,將資料夾內的檔案清單傳給右邊的 measure-object

 test-path \temp
True
 ls \temp && Measure-Object
Enter fullscreen mode Exit fullscreen mode

但其實並不會,你會看到類似以下的結果:

    Directory: C:\temp

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----         2025/12/9 下午 04:23                F6722
d----        2025/12/11 下午 10:49                test_wt
d----        2025/12/11 下午 10:45                tmr
-a---         2025/5/22 下午 10:50            162 tomica.jpg
-a---         2025/3/18 下午 04:55         521370 train1.jpeg
-a---         2025/3/18 下午 04:55         879688 train2.jpeg
-a---         2025/8/29 下午 11:56       10824402 VVAICar_Test.apk

Count             : 0
Average           : 
Sum               : 
Maximum           : 
Minimum           : 
StandardDeviation : 
Property          : 
Enter fullscreen mode Exit fullscreen mode

也就是 pipeline chain operator 只會串接指令,但不會傳送輸出結果,如果命名為 chain operator 好像比較適當。

Top comments (0)