我正在尝试插入数字作为前缀" n__
"对于CWD
中的每个文件名(不递归)。 n
是一个增量为+1的数字,用户需要输入第一个值。要编号,文件必须根据文件名以最低值优先顺序预先排序。
$i = Read-Host 'Enter first file number'
$confirmation = Read-Host "Re-enter first file number"
if ($confirmation -eq '=') {
# proceed
}
Get-ChildItem | Sort-Object | Rename-Item -NewName { "$i+1" + "__" + $_.Name }
我在i +上缺少什么,以确保文件按编号排序?
预期结果:
101__121.ext
102__211.ext
103__375.ext
答案 0 :(得分:1)
# putting [int] before the variable will insure that your input is an integer and not a string
[int] $i = Read-Host 'Enter first file number'
[int] $confirmation = Read-Host "Re-enter first file number"
# Your if statement seemed to not make sense. This is my take
if ($confirmation -eq $i)
{
Get-ChildItem | Sort-Object | Foreach-Object -Process {
$NewName = '{0}__{1}' -f $i,$_.Name # String formatting e.x. 1__FileName.txt
$_ | Rename-Item -NewName $NewName # rename item
$i ++ # increment number before next iteration
}
}
else
{
Write-Warning -Message "Your input did not match"
}
答案 1 :(得分:1)
假设文件是数字名称(121.ext
,211.ext
等)
[Int]$UserInput = Read-Host -Prompt 'Enter first file number'
[Int]$Confirmation = Read-Host -Prompt 'Re-enter first file number'
If ($Confirmation -ne $UserInput) { Exit }
$Collection = Get-ChildItem | Sort-Object -Property @{Expression={[Int]$_.BaseName}}
While (($UserInput - $Confirmation) -lt $Collection.Count)
{
$Collection[$UserInput - $Confirmation] |
Rename-Item -NewName "$($UserInput)__$($_.Name)"
$UserInput++
}