带序号的前缀文件名。被提示(powershell)

时间:2017-11-02 15:45:40

标签: windows powershell powershell-v2.0 powershell-v3.0

我正在尝试插入数字作为前缀" 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

2 个答案:

答案 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.ext211.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++
}