Get-ChildItem -LiteralPath . -Filter *.pdf | ForEach-Object -Begin {$c = 0} -Proces {Rename-Item -LiteralPath $_.FullName (Join-Path $_.DirectoryName ($_.Name -replace '^(.{1,8}).*?(\.[^\.]+)?$', ('$1' + "_$c" + '$2'))); $c++}join-path 是多餘的,不需要給完整的目標用完整路徑只是為了避開一個bug,不過為此 -LiteralPath .也應該要改成 -LiteralPath $PWD.Path$suffix=''; while(Test-path -LiteralPath ($newPath =Join-Path $_.DirectoryName ($baseName+$suffix+$extension))){$suffix = "_$c" -f c++}; Rename-Item $_ $newPath產生新路徑的地方大概改成這樣,至於把檔名拆成basename與副檔名的方法可以參考我上面用的正規表示法,因為5.1的split-path不支援分拆出basename
https://i.imgur.com/DkCaj7k.jpeg你可以參考這個函式這裡借用了.net 的 IO.Path 物件還有按照你的需求,不同檔案要重新計數,你不應該把初始值寫在 -Begin {} 中,因為它管道中只會執行一次,也就是只有第一個檔案之前會執行到應該在 -Process { } 中最上方