需求:批量重命名形如 [abcd]2008.01.01.測試.txt 的文件為 2008.01.01.txt (去除首尾括號內容)。Linux 下輕鬆搞定,Windows 下選擇 PowerShell 實踐,過程中踩中 Rename-Item 不支援方括號路徑的坑,最終用 Move-Item -LiteralPath 完美解決。
dir (Get-ChildItem) 輸出 FileInfo/DirectoryInfo,可直接調用屬性方法。Get-Member 探索對象結構:dir | Get-Member。ls=dir=gci, ?=Where-Object, %=ForEach-Object,簡潔如 Perl/Awk。# 僅列出只讀文件
dir | ? { $_.IsReadOnly }
# 列出子目錄及文件數
ls | ? { $_.PSIsContainer } | % { "$($_.FullName): $($_.GetFiles().Length)" }
# 計算總文件數 (模擬 awk 模式)
ls | ? { $_.PSIsContainer } | % { $c=0 } { $c+=$_.GetFiles().Length } { "Total: $c" }
# 報錯:路徑不存在
Rename-Item 'F:/temp/[10]' 'F:/temp/10'
# 錯誤:Rename-Item : 指定路徑 F:/temp/[10] 下的對象不存在。
方括號在 PowerShell 路徑中屬通配符字符,轉義極其麻煩 (`[ `] 仍失效),這是已知 Bug。
Move-Item 的 -LiteralPath 參數完全禁用通配符解析,按字面路徑操作,完美繞過方括號問題。
# 最終一鍵重命名命令
ls *.avi | % {
if ($_.FullName -match '(.*)/\[.*?\]/(\d{4}\.\d{2}\.\d{2}).*\.avi') {
mv -LiteralPath $_.FullName "$($matches[1]$matches[2]).avi"
}
}
-match 正則提取路徑前綴 ($matches[1]) 與日期 ($matches[2])。mv 為 Move-Item 別名,-LiteralPath 確保源路徑字面解析。實踐出真知,遇 Bug 更長見識。PowerShell 物件管道 + 正則 + LiteralPath,讓 Windows 批量文件操作同樣優雅高效。