1 / 23
📜

Part 04 Unit 02

建立自動化腳本

把常用的指令存成腳本

一鍵執行,永久重複使用

使用鍵盤 ← → 或點擊按鈕翻頁

2 / 23

學習目標

完成本單元後,你將學會:

  • 什麼是 PowerShell 腳本 (.ps1)
  • 如何建立和儲存腳本檔案
  • 如何執行腳本
  • 建立帶有參數的腳本

💡 寫一次,用一輩子!自動化讓工作更有效率

3 / 23

為什麼要用腳本?

😰 每次都打指令

  • 每次都要記住指令
  • 容易打錯
  • 複雜指令很難記
  • 無法分享給同事

🚀 使用腳本

  • 寫一次永久使用
  • 不會出錯
  • 再複雜都能重用
  • 輕鬆分享給他人
4 / 23

什麼是 PowerShell 腳本?

PowerShell 腳本是副檔名為 .ps1 的文字檔案

裡面包含一系列的 PowerShell 指令

類似於:

  • Windows 批次檔 (.bat)
  • Linux Shell 腳本 (.sh)
  • Python 腳本 (.py)

💡 本質上就是把你打的指令存成一個檔案

5 / 23

步驟 1:建立腳本檔案

方法一:在 Antigravity 中建立

  1. Ctrl + N 新增檔案
  2. Ctrl + S 儲存
  3. 檔名輸入 convert.ps1

方法二:使用終端機建立

# 在終端機中直接建立空白腳本 New-Item -Path "convert.ps1" -ItemType File
6 / 23

步驟 2:撰寫第一個腳本

在 convert.ps1 中輸入以下內容:

# convert.ps1 - 批次轉換 Markdown 到 Word # 用途:將當前資料夾所有 .md 轉成 .docx Write-Host "🚀 開始批次轉換..." -ForegroundColor Cyan Get-ChildItem *.md | ForEach-Object { Write-Host "📄 轉換: $($_.Name)" -ForegroundColor Yellow pandoc $_.Name -o ($_.BaseName + ".docx") } Write-Host "✅ 轉換完成!" -ForegroundColor Green

💡 以 # 開頭的行是註解,不會被執行

7 / 23

步驟 3:執行腳本

在終端機中執行:

# 方法一:完整路徑 .\convert.ps1 # 方法二:指定完整路徑 D:\腳本\convert.ps1

⚠️ 執行原則錯誤?

如果出現「無法載入檔案...」錯誤,請先執行:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
8 / 23

關於執行原則

Windows 預設禁止執行腳本(安全考量)

原則 說明
Restricted 禁止所有腳本(預設)
RemoteSigned 本機腳本可執行,下載的需簽署
Unrestricted 所有腳本都可執行(不建議)

💡 使用 RemoteSigned 是安全又實用的選擇

9 / 23

步驟 4:增強腳本功能

加入錯誤處理和統計

# convert.ps1 - 增強版批次轉換腳本 $files = Get-ChildItem *.md if ($files.Count -eq 0) { Write-Host "❌ 找不到任何 .md 檔案" -ForegroundColor Red exit } Write-Host "🔍 找到 $($files.Count) 個檔案" -ForegroundColor Cyan $success = 0; $failed = 0 foreach ($file in $files) { try { pandoc $file.Name -o ($file.BaseName + ".docx") Write-Host "✅ $($file.Name)" -ForegroundColor Green $success++ } catch { Write-Host "❌ $($file.Name)" -ForegroundColor Red $failed++ } } Write-Host "`n📊 結果:成功 $success / 失敗 $failed"
10 / 23

進階:帶參數的腳本

讓腳本可以接受輸入參數

# convert-format.ps1 - 可指定輸出格式 param( [string]$OutputFormat = "docx" ) Write-Host "🔄 轉換為 .$OutputFormat 格式" -ForegroundColor Cyan Get-ChildItem *.md | ForEach-Object { pandoc $_.Name -o ($_.BaseName + ".$OutputFormat") Write-Host "✅ $($_.Name) → $($_.BaseName).$OutputFormat" }

使用方式:

.\convert-format.ps1 -OutputFormat html .\convert-format.ps1 -OutputFormat pdf .\convert-format.ps1 # 預設使用 docx
11 / 23

進階:多參數腳本

# smart-convert.ps1 - 智慧轉換腳本 param( [string]$InputFolder = ".", [string]$OutputFolder = "output", [string]$Format = "docx" ) # 建立輸出資料夾 if (!(Test-Path $OutputFolder)) { New-Item -ItemType Directory -Path $OutputFolder | Out-Null } Write-Host "📁 輸入: $InputFolder" -ForegroundColor Cyan Write-Host "📂 輸出: $OutputFolder" -ForegroundColor Cyan Write-Host "📄 格式: $Format" -ForegroundColor Cyan Get-ChildItem "$InputFolder\*.md" | ForEach-Object { $output = "$OutputFolder\$($_.BaseName).$Format" pandoc $_.FullName -o $output Write-Host "✅ $($_.Name)" }
12 / 23

使用多參數腳本

# 使用預設值 .\smart-convert.ps1 # 指定輸出資料夾 .\smart-convert.ps1 -OutputFolder "D:\Word文件" # 指定所有參數 .\smart-convert.ps1 -InputFolder "D:\筆記" ` -OutputFolder "D:\輸出" ` -Format "html"

💡 使用 ` (反引號) 可以換行繼續指令

13 / 23

腳本存放最佳實踐

建議建立專門的腳本資料夾

📁 D:\Scripts\
├── 📜 convert.ps1
├── 📜 convert-format.ps1
├── 📜 smart-convert.ps1
├── 📜 batch-rename.ps1
└── 📜 cleanup.ps1

💡 把常用腳本集中管理,方便查找和維護

14 / 23

進階:加入系統 PATH

讓腳本可以在任何地方執行

# 暫時加入 PATH(當前工作階段有效) $env:Path += ";D:\Scripts" # 永久加入 PATH [Environment]::SetEnvironmentVariable( "Path", $env:Path + ";D:\Scripts", "User" )

💡 加入 PATH 後,可以直接輸入 convert.ps1 執行

15 / 23

進階:雙擊執行腳本

方法:建立批次檔呼叫 PowerShell 腳本

建立 轉換文件.bat

@echo off powershell -ExecutionPolicy Bypass -File "%~dp0convert.ps1" pause

解析:

  • %~dp0 - 批次檔所在目錄
  • -ExecutionPolicy Bypass - 略過執行原則
  • pause - 執行完畢等待按鍵
16 / 23

實用腳本範例 1:監控轉換

watch-convert.ps1 - 監控資料夾自動轉換

# 監控資料夾,有新 .md 檔案時自動轉換 param([string]$WatchFolder = ".") Write-Host "👀 監控中: $WatchFolder" -ForegroundColor Cyan Write-Host "按 Ctrl+C 停止..." -ForegroundColor Yellow $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = $WatchFolder $watcher.Filter = "*.md" $watcher.EnableRaisingEvents = $true $action = { $path = $Event.SourceEventArgs.FullPath $name = $Event.SourceEventArgs.Name Start-Sleep -Seconds 1 $output = $path -replace '\.md$', '.docx' pandoc $path -o $output Write-Host "✅ 已轉換: $name" -ForegroundColor Green } Register-ObjectEvent $watcher "Created" -Action $action | Out-Null while ($true) { Start-Sleep -Seconds 1 }
17 / 23

實用腳本範例 2:雙向轉換

bidirectional.ps1 - 雙向格式轉換

# 自動判斷並轉換:MD↔DOCX param([string]$File) if (!(Test-Path $File)) { Write-Host "❌ 檔案不存在: $File" -ForegroundColor Red exit } $ext = [System.IO.Path]::GetExtension($File) $base = [System.IO.Path]::GetFileNameWithoutExtension($File) switch ($ext) { ".md" { $output = "$base.docx" pandoc $File -o $output Write-Host "✅ MD → DOCX: $output" -ForegroundColor Green } ".docx" { $output = "$base.md" pandoc $File -o $output Write-Host "✅ DOCX → MD: $output" -ForegroundColor Green } default { Write-Host "❌ 不支援的格式: $ext" -ForegroundColor Red } }
18 / 23

實用腳本範例 3:備份並轉換

backup-convert.ps1 - 備份後轉換

# 先備份原始檔案,再進行轉換 param( [string]$BackupFolder = "backup" ) $timestamp = Get-Date -Format "yyyyMMdd_HHmmss" $backupPath = "$BackupFolder\$timestamp" # 建立備份資料夾 New-Item -ItemType Directory -Path $backupPath -Force | Out-Null # 備份所有 .md 檔案 Get-ChildItem *.md | Copy-Item -Destination $backupPath Write-Host "📦 已備份到: $backupPath" -ForegroundColor Cyan # 執行轉換 Get-ChildItem *.md | ForEach-Object { pandoc $_.Name -o ($_.BaseName + ".docx") Write-Host "✅ $($_.Name)" -ForegroundColor Green }
19 / 23

腳本除錯技巧

常見除錯方法

方法 用途
Write-Host 輸出訊息追蹤執行流程
$VerbosePreference = "Continue" 顯示詳細資訊
-WhatIf 模擬執行不實際操作
try/catch 捕捉並處理錯誤
# 使用 -WhatIf 測試 Get-ChildItem *.md | Remove-Item -WhatIf
20 / 23

腳本撰寫最佳實踐

  • ✅ 在開頭加上說明註解
  • ✅ 使用有意義的變數名稱
  • ✅ 加入錯誤處理
  • ✅ 提供使用範例
  • ✅ 設定合理的預設值
  • ❌ 不要硬編碼路徑
  • ❌ 不要省略錯誤處理
  • ❌ 不要使用太短的變數名
21 / 23

動手練習

練習任務

  1. 建立腳本 my-convert.ps1
  2. 腳本功能:將 .md 轉成 .html
  3. 加入進度顯示
  4. 加入完成統計
  5. 測試腳本執行
22 / 23

練習答案

🔒 輸入密碼查看答案

# my-convert.ps1 $files = Get-ChildItem *.md $total = $files.Count $current = 0 if ($total -eq 0) { Write-Host "找不到 .md 檔案" -ForegroundColor Red exit } foreach ($file in $files) { $current++ Write-Host "[$current/$total] $($file.Name)" -ForegroundColor Yellow pandoc $file.Name -o ($file.BaseName + ".html") --standalone } Write-Host "`n✅ 完成!共轉換 $total 個檔案" -ForegroundColor Green
23 / 23

本單元總結

你學會了:

  • 建立 PowerShell 腳本 (.ps1)
  • 設定執行原則
  • 使用 param 定義參數
  • 加入錯誤處理和進度顯示

腳本讓自動化變得簡單!

寫一次,永久使用,分享給所有人

下一單元:AI 產生腳本 🤖