← Engineering Workflow

ENGINEERING WORKFLOW · 63

PowerShell Foundation:Command、Argument、Pipeline、Current Directory

Shell 不是「黑色視窗」。它是一個 command interpreter:讀你輸入的文字、解析 command 與 arguments、啟動 process 或執行 cmdlet,再把 stdout/stderr/object pipeline 傳給下一步。

Learning outcomes

1. Shell 先解析,再執行

Get-Location
Get-ChildItem
node .\scripts\check-site.mjs
git status

Get-Location 是 PowerShell cmdlet;node、git 是 external executables。Shell 負責找到它們、組裝 arguments、啟動並顯示結果。

2. Current directory 是 relative path 的 reference

PS C:\Users\Anson> cd D:\Projects\software-learning
PS D:\Projects\software-learning> node .\scripts\check-site.mjs

同一個 .\scripts\... 在不同 current directory 會指向不同位置。看到「file not found」先查 Get-Location。

3. Path 有空白時要正確 quoting

Set-Location "D:\My Projects\software-learning"

& "C:\Program Files\nodejs\node.exe" ".\script.js"

& call operator 可執行由字串/變數提供的 command path。它後面需要的是可執行 command,不是任意物件。

4. PowerShell pipeline 傳的是 objects

Get-Process |
  Where-Object CPU -gt 10 |
  Sort-Object CPU -Descending |
  Select-Object -First 5

這不是單純用空格切文字欄位,而是把 process objects 經 property/filter/sort pipeline 傳遞。

5. Exit code 與 error evidence

node .\scripts\check-site.mjs
$LASTEXITCODE

External process exit code 是 automation/CI 很重要的機器可讀結果。Console 顯示紅字不一定等於 external process exit non-zero,反之亦然。

Project checkpoint:Course Workspace v2

用 PowerShell 從任意起始目錄可靠地進入 repo、檢查 Git 狀態、執行 Node checker,並記錄每一步的 cwd 與 exit code。

Set-Location "D:\Projects\software-learning"
git status
node .\scripts\check-site.mjs
Write-Host "exit=$LASTEXITCODE"

Debug evidence:& $adb 為什麼會失敗?

先印出變數內容與型別,確認它真的含 executable path,而不是空值、陣列、錯誤物件。Call operator 只負責「執行這個 command」,不會把任何值自動變成合法 command。

Knowledge check

  1. Shell、cmdlet、external process 各是哪一層?
  2. relative path 為什麼依 cwd 改變?
  3. PowerShell pipeline 與傳統純文字 pipeline 有何差別?
  4. 故意從錯誤目錄執行 checker,再用 evidence 找到原因。