How to Rename Files in a Loop in PowerShell

PowerShell is a Windows administrative tool capable of managing “File Explorer” operations such as copying, moving, deleting, and renaming files. More specifically, renaming files in File Explorer manually takes so much time. Instead of putting so much time and effort, utilize the PowerShell script to complete this task at once. PowerShell can rename a single file and also multiple files at once. This renaming operation of multiple files can be performed using a loop.

This post will overview a detailed guide to rename files in the PowerShell loop.

How to Rename Files in a Loop in PowerShell?

Renaming the file in Windows is considered a normal operation. As the file can be selected and renamed using the context menu. But if you have multiple files to rename, then doing so using the context will take so much time. However, the PowerShell script using the “ForEach()” loop can reduce the overall time.

Example

Let’s check the files before changing their name in a loop. For that reason, use the “Get-ChildItem” cmdlet along with the folder path, as shown below:

> Get-ChildItem "C:\Doc"

Now let’s rename the files in a loop using “ForEach()” loop:

$DocFiles = (Get-ChildItem "C:\Doc\*.*" | foreach-object {$_.name})
foreach ($file in $DocFiles)
{
$Rename = 'NewFile' + $file
Rename-Item "C:\Doc\$file" $Rename -verbose
clear-variable Rename
}

According to the above code:

  • Start with searching the files using the “Get-ChildItem” cmdlet.
  • After finding the files pass them to the “ForEach-Object()” using the “Pipeline |” and store all of this in the “$DocFiles” variable.
  • After that, the “foreach” function is defined to rename each file in the folder.
  • $Rename” variable will control how the files in the folder will be renamed with the “$file” section.
  • Finally, the new name has been passed to the “Rename-Item” command to complete the rename operation.
  • In the end, the “Rename” variable is cleared, and it can be used for the next loop:

The code has been executed successfully.

Now, let’s run the below command to check whether the files have been renamed or not:

> Get-ChildItem "C:\Doc"

As the output confirms that the files have been renamed successfully following the same starting pattern.

Conclusion

The renaming of files in a loop in PowerShell can be performed using the “ForEach()” loop. The “ForEach()” loop renames the files with the combination of the “Get-ChildItem” and “Rename-Item” cmdlets. The “Get-ChildItem” cmdlet gets the address of the folder in which multiple files are located, the “ForEach()” loop goes through each file, and then the “Rename-Item” cmdlet renames the files one by one. This tutorial has overviewed a detailed procedure to rename files in a loop in PowerShell.



from https://ift.tt/PFgZHQ7

Post a Comment

0 Comments