有時候檔案名稱裡面會有數字,但是排序的時候因為是用字串排序,所以順序不如預期。 例如說有以下幾個檔案:
a1
a2
a10
a20
預期的排序應該如上,但是實際上排序出來會類似:
a1
a10
a2
a20
這個時候,個億透過powershell用regex的方式把數字的部分填充讓整個排序正常
Get-ChildItem | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(20) }) }
這個時候要注意通常資料夾名稱Windows預設使用括弧,所以像是(1),這個時候上面的方式可能不好用 這個時候建議可以把括弧替換掉,可以用:
Rename-Item –NewName { $_.name.replace(' ','_') -replace '[()]','_' }
整個搭配起來可以這樣:
- 先把括弧換成底線_
- 用數字排序方式把建立時間替換 - 最後外部排序可以用日期來排 - 避免掉要改名稱
$filePath = "C:\path\to\file"
dir $filePath | Rename-Item –NewName { $_.name.replace(' ','_') -replace '[()]','_' }
dir $filePath | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(20) }) } |
%{$index=1}{ Set-FileTimeStamps -path $_.FullName -date $($(get-date).AddMinutes($index).ToString("yyyy-MM-dd HH:mm:ss")); $index = $index+10}