第 5 章
常用指令實戰:查看內容、複製、搬移、刪除
本章重點
- 用
Get-Content查看檔案內容 - 用
Copy-Item複製檔案 - 用
Move-Item搬移或改名 - 用
Remove-Item刪除檔案 - 學會批次操作多個檔案
查看檔案內容:Get-Content
# 顯示整個檔案內容
Get-Content .\readme.txt
# 只顯示前 5 行
Get-Content .\log.txt -TotalCount 5
# 只顯示最後 10 行
Get-Content .\log.txt -Tail 10
# 搜尋包含特定關鍵字的行
Get-Content .\log.txt | Where-Object { $_ -like "*error*" }
別名:
Get-Content 可縮寫為 gc 或 cat。
複製:Copy-Item
# 複製單一檔案
Copy-Item .\hello.txt .\backup\hello.txt
# 複製到另一個資料夾(保留原名)
Copy-Item .\hello.txt .\backup\
# 複製整個資料夾(含子資料夾)
Copy-Item .\myfolder\ .\backup\myfolder\ -Recurse
# 複製所有 .txt 檔到另一個資料夾
Copy-Item .\*.txt .\backup\
搬移與改名:Move-Item
# 搬移檔案到另一個資料夾
Move-Item .\hello.txt .\archive\
# 直接改名(在同一個資料夾)
Move-Item .\old-name.txt .\new-name.txt
# 搬移並改名
Move-Item .\report.txt .\archive\report-2024.txt
# 搬移整個資料夾
Move-Item .\myfolder\ C:\backup\
刪除:Remove-Item
# 刪除單一檔案
Remove-Item .\temp.txt
# 刪除資料夾(含所有內容)
Remove-Item .\temp-folder\ -Recurse
# 刪除所有 .log 檔
Remove-Item .\*.log
# 刪除前先確認
Remove-Item .\important.txt -Confirm
刪除沒有資源回收桶:
PowerShell 的
Remove-Item 直接刪除,不會移到資源回收桶。
重要檔案操作前請先備份,或加上 -WhatIf 參數先預覽會發生什麼事。
# -WhatIf 只預覽,不真的執行
Remove-Item .\*.log -WhatIf
批次操作:搭配管線
# 找到所有超過 30 天的 .log 檔並刪除
$cutoff = (Get-Date).AddDays(-30)
Get-ChildItem .\logs\ -Filter "*.log" |
Where-Object { $_.LastWriteTime -lt $cutoff } |
Remove-Item
# 把所有 .txt 檔複製到備份資料夾
Get-ChildItem .\*.txt | Copy-Item -Destination .\backup\
小練習:
- 在桌面建立
test.txt:New-Item ~\Desktop\test.txt -Value "測試內容" - 查看內容:
Get-Content ~\Desktop\test.txt - 複製到目前資料夾:
Copy-Item ~\Desktop\test.txt .\test-copy.txt - 改名:
Move-Item .\test-copy.txt .\test-renamed.txt - 刪除(加 -WhatIf 先預覽):
Remove-Item .\test-renamed.txt -WhatIf
小結
Get-Content、Copy-Item、Move-Item、Remove-Item
是日常操作的四大指令。搭配管線可以做批次處理。
操作前善用 -WhatIf 可以避免誤刪。
下一章,進入變數與資料處理。