Powershell 将文件重命名为递增数字,根据当前数字值添加前缀零

问题描述 投票:0回答:1

我正在尝试组织我的图片文件,以便它们按以下顺序命名:001, 002, ..., 010, 011, ..., 100, 101, ...

我能够得到一个迭代每个文件的代码,并将每个文件重命名为递增的数字:1,2,3,4,...

我也可以在前面手动添加“0”或“00”。

我想要的是如果当前数字是 <10, add "0" if current number is >=10 && <100 and add nothing if current number is >100

添加“00”

问题是我不知道如何在Powershell循环中实现if语句。这是我能找到的:

$nr = 1
Dir | %{Rename-Item $_ -NewName (‘00{0}.jpg’ -f $nr++)}

是否可以在这样的循环中添加“If”语句?我几乎没有使用 Powershell 的经验。

powershell loops if-statement rename
1个回答
0
投票

您可以使用

D
格式说明符表示您的整数。有关更多信息,请参阅 标准格式说明符

示例:

0..50 | ForEach-Object { $_.ToString('D3') }

# Also valid using `String.Format` (`-f` operator in PowerShell)
0..50 | ForEach-Object { '{0:D3}' -f $_ }

应用于您的代码:

$nr = 1
Get-ChildItem | ForEach-Object { $_ | Rename-Item -NewName ('{0:D3}.jpg' -f $nr++) }
© www.soinside.com 2019 - 2024. All rights reserved.