Windows PowerShell,PadLeft

Windows PowerShell, PadLeft

我需要使文件名字符串像 text_000.txt,其中 000 应该增加每个文件,但我遇到了这样的问题,在 10 次迭代后,文件名变得多余

我需要获取类似“text_001.mp3”的文件名 9 个文件没问题,但在我得到“text_0010”

之后

这是代码

*param (
[string]$dir = "C:\Users\Администратор\Desktop\music"
)
Set-Location -Path $dir
$count=1
Get-ChildItem -Path $dir | Sort-Object -Property LastWriteTime | % { Rename-Item $_ -NewName (‘text' + '{0}'.PadLeft(5,"0") -f $count++ + '.txt') }*

直接格式化文件名 number with leading zeros 可能更容易,例如:

'text_{0:000}.txt' -f 17
text_017.txt

还知道这将正确溢出(防止重复文件名):

'text_{0:000}.txt' -f 1234
text_1234.txt

你的情况:

|% { Rename-Item $_ -NewName ('text_{0:000}.txt' -f $count++) }