şaloma
şaloma

Reputation: 411

Rename file names incrementally

I would like to rename file names in a folder incrementally by prefixing a string. I have found this Windows PowerShell script which only prefixes a string:

cd C:\Users\strz\Desktop\Data_zMob\processed_\PROD_3Euro_OK\Z_586_20160307_0850
$files=get-childitem
foreach ($file in $files) {
Rename-Item $file.name ("stringToAppend" + $file.name)
} 

I am not familiar with this scripting language at all. So I tried this:

    cd C:\Users\strz\Desktop\Data_zMob\processed_\PROD_3Euro_OK\Z_586_20160307_0850
    $files=get-childitem
    $lotId=1
    foreach ($file in $files) {
    Rename-Item $file.name ($lotId + $file.name)
    $lotId++
    } 

It failed, of course. How can I achieve this?

Upvotes: 0

Views: 341

Answers (1)

Matt
Matt

Reputation: 46700

Cannot convert value "data.csv" to type "System.Int32". Error: "Input string was not in a correct format."
At line:5 char:1
+ Rename-Item $file.name ($lotId + $file.name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

Is the error you were most likely getting was because of this line

Rename-Item $file.name ($lotId + $file.name)

$lotid is an integer and you were trying to perform a mathematical operation with a string which is not possible where file names are concerened. The simplest thing to do to make this work is place the variable in quotes so that it is only treated as a string during the rename.

Rename-Item $file.name ("$lotId" + $file.name)

Since you know the path you are working on I would shy away from relying on the current path being the working path. Something like this would also do what you want. Remove -WhatIf when you are done your testing.

$lotId = 1
$path =  "D:\Temp\New folder"
Get-ChildItem $path | Foreach-object{
    Rename-Item -Path $_.FullName -NewName ("{0}{1}" -f $lotId++,$_.Name) -WhatIf
}

We update $lotId++ during each loop pass so there is no need for a separate line to increase that. There are other snippets that would work for sure. This is the first one I did that didn't do anything crazy.

Upvotes: 2

Related Questions