資料格式與 API
現代的自動化工作,大部分都在處理 CSV、JSON 這類結構化資料,以及呼叫網路上的 REST API。PowerShell 的優勢是:這些資料讀進來之後直接就是物件,不需要自己剖析字串,能立刻套用 管線 的篩選與排序。
CSV
# 讀取:每一列變成一個物件,欄位名稱變成屬性
$users = Import-Csv .\users.csv
$users | Where-Object Department -eq 'IT' | Select-Object Name, Email
# 匯出:把任何物件輸出成 CSV
Get-Process |
Select-Object Name, Id, WorkingSet |
Export-Csv .\processes.csv -NoTypeInformation -Encoding utf8
要點:
Import-Csv讀進來的值都是字串。要做數值比較時先轉型,例如[int]$_.Age -gt 30。- 匯出前先用
Select-Object挑好要的欄位,避免輸出一堆用不到的屬性。 - Windows PowerShell 5.1 需要加
-NoTypeInformation避免多出一行型別資訊;PowerShell 7 預設就不會輸出,加了也無妨。
JSON
$json = '{"name":"Victor","skills":["PowerShell","Python"],"address":{"city":"Taipei"}}'
# JSON 字串 → 物件
$obj = $json | ConvertFrom-Json
$obj.name # Victor
$obj.skills[0] # PowerShell
$obj.address.city # Taipei
# 物件 → JSON 字串
$obj | ConvertTo-Json -Depth 5
ConvertTo-Json 預設只展開兩層
巢狀物件超過兩層時,更深的內容會被壓成一段字串而遺失細節。轉換巢狀資料時,記得加上 -Depth(例如 -Depth 5)。
讀寫 JSON 檔案:
$config = Get-Content .\config.json -Raw | ConvertFrom-Json
$config.port = 9090
$config | ConvertTo-Json -Depth 5 | Set-Content .\config.json
呼叫 REST API
Invoke-RestMethod 會送出 HTTP 請求,並自動把回傳的 JSON 轉成物件:
$repo = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
$repo.name
$repo.stargazers_count
帶參數、標頭與 POST 內容:
$headers = @{ Accept = 'application/vnd.github+json' }
# GET 加查詢參數:直接寫在網址裡
Invoke-RestMethod -Uri 'https://api.github.com/search/repositories?q=powershell&per_page=3' -Headers $headers
# POST 送出 JSON
$body = @{ title = 'Hello'; body = '內容' } | ConvertTo-Json
Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType 'application/json'
Invoke-RestMethod 適合回傳結構化資料的 API;如果你要看狀態碼、回應標頭或抓整個網頁,改用 Invoke-WebRequest。
不要把密碼或 API 金鑰寫進腳本
金鑰請放在環境變數($env:API_KEY)、Get-Credential 提示輸入,或專門的機密管理工具(例如 Microsoft 的 SecretManagement 模組)。腳本常會被上傳到 Git,寫死的金鑰等於公開。
其他常用的輸出
| 目的 | 做法 |
|---|---|
| 存成純文字報表 | Out-File .\report.txt |
| 螢幕上的表格 | Format-Table -AutoSize |
| 互動式挑選與篩選(Windows) | Out-GridView |
| 忽略輸出 | Out-Null |
推薦影音
資料與物件
簡述:John Savill 的 PowerShell Master Class 資料單元(約 46 分鐘),說明認證資訊(credentials)、資料剖析與物件操作,對應本頁的資料處理與金鑰保護。錄於 2019 年,觀念在 PowerShell 7 仍適用。