第 9 章

實用小自動化:整理檔案、批次改名、簡單系統資訊查詢

本章重點

  • 寫一個自動整理下載資料夾的腳本
  • 批次替多個檔案改名
  • 查詢系統資訊並輸出報告
  • 學會把腳本排程自動執行

範例一:自動整理下載資料夾

依副檔名分類,把檔案搬到對應的子資料夾:

# organize-downloads.ps1
$source = "$env:USERPROFILE\Downloads"

$rules = @{
    "Images"    = @(".jpg", ".jpeg", ".png", ".gif", ".webp")
    "Documents" = @(".pdf", ".docx", ".xlsx", ".txt", ".md")
    "Archives"  = @(".zip", ".rar", ".7z")
    "Videos"    = @(".mp4", ".mkv", ".avi", ".mov")
}

foreach ($folder in $rules.Keys) {
    $dest = Join-Path $source $folder
    if (-not (Test-Path $dest)) {
        New-Item $dest -ItemType Directory | Out-Null
    }

    foreach ($ext in $rules[$folder]) {
        Get-ChildItem $source -Filter "*$ext" -File | ForEach-Object {
            Move-Item $_.FullName $dest
            Write-Output "已移動:$($_.Name) → $folder"
        }
    }
}

Write-Output "整理完成!"

範例二:批次改名

# 把所有 .txt 檔加上日期前綴
$date = Get-Date -Format "yyyyMMdd"

Get-ChildItem .\*.txt | ForEach-Object {
    $newName = "$date-$($_.Name)"
    Rename-Item $_.FullName $newName
    Write-Output "改名:$($_.Name) → $newName"
}

# 把檔名中的空格換成底線
Get-ChildItem . -File | ForEach-Object {
    $newName = $_.Name -replace ' ', '_'
    if ($newName -ne $_.Name) {
        Rename-Item $_.FullName $newName
    }
}

範例三:系統資訊查詢報告

# sysinfo.ps1
$report = @"
=== 系統資訊報告 ===
產生時間:$(Get-Date)

電腦名稱:$env:COMPUTERNAME
使用者:$env:USERNAME
OS:$((Get-CimInstance Win32_OperatingSystem).Caption)
PowerShell:$($PSVersionTable.PSVersion)

--- CPU ---
$((Get-CimInstance Win32_Processor).Name)

--- 記憶體 ---
總計:$([math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 1)) GB

--- 磁碟 ---
"@

Get-PSDrive -PSProvider FileSystem | ForEach-Object {
    $used = [math]::Round(($_.Used / 1GB), 1)
    $free = [math]::Round(($_.Free / 1GB), 1)
    $report += "$($_.Name):  已用 ${used}GB  剩餘 ${free}GB`n"
}

Write-Output $report
$report | Out-File ".\sysinfo-$(Get-Date -Format 'yyyyMMdd').txt"

補充:用工作排程器定時執行

把腳本排程為每天自動執行:

# 建立排程工作(需系統管理員)
$action = New-ScheduledTaskAction `
    -Execute "powershell.exe" `
    -Argument "-ExecutionPolicy RemoteSigned -File C:\scripts\organize-downloads.ps1"

$trigger = New-ScheduledTaskTrigger -Daily -At "09:00"

Register-ScheduledTask `
    -TaskName "整理下載資料夾" `
    -Action $action `
    -Trigger $trigger `
    -RunLevel Highest
不想用排程器? 也可以把腳本放在開機啟動資料夾,或用 Windows 工作排程器的 GUI 介面設定。
小練習:
  1. 在桌面建立幾個不同副檔名的空白檔案(.txt、.jpg、.pdf)
  2. 修改「自動整理」腳本,改為整理桌面
  3. 執行後確認檔案是否移到對應資料夾

小結

這一章把前幾章學到的所有技巧整合起來,寫出真正有用的腳本。 整理檔案、批次改名、查詢系統資訊,都是日常實用的場景。 只要掌握這些模式,就能套用到各種不同的自動化需求。

最後一章,聊聊如何持續進步。