Rename batch files using Windows Power Shell

4

How to rename all files in a folder whose name is an (integer) number followed by a certain extension (my choice) using the Windows Power Shell ?

  

Example: The folder as is:

1.txt
2.txt
7.txt
arquivo.html
  

How to stay after renaming:

file1.txt
file2.txt
file7.txt
arquivo.html
    
asked by anonymous 05.11.2015 / 18:39

3 answers

2

You can resolve the problem by combining the Get-ChildItem cmdlets to list the files in the directory, and Rename-Item to rename them

$raiz = "c:\ps"
$arquivos = Get-ChildItem $raiz  -Filter "*.txt" | Where-Object {$_.Name -match "^\d"} 
foreach($item in $arquivos){
    Rename-Item -NewName ("novo"+$item.Name) -Path ($raiz+$item.Name)
}

The first part of the line filters all files with .txt extension, the second part takes the pipe from the cmdlet and applies a regex to the file name it says to only capture the files that the names begin with number and third part is the assignment of the selected files to be renamed.

Rename-Item changes the filename with the prefix "new" followed by the old name (which was a number)

$arquivos = Get-ChildItem $raiz  -Filter "*.txt" | Where-Object {$_.Name -match "^\d"} 
|3 parte    |1 parte                             |2 parte
    
06.11.2015 / 03:12
5

Suppose you have a directory with corrupted filenames. You only know that they are all .png files, but the extensions have been renamed to random names. You would then like to rename everything to .png at once.

Using Windows PowerShell:

 dir | % {ren $_ ($_.name.substring(0, $_.name.length-4) + ‘.png’ ) } 

The first command, dir, gets a list of files from the current directory and passes objects (not text!) to the next command in the pipeline. The next one then (% means foreach-object) executes the block (between {e}) for each of the items.

In this case, the rename command passing the name ($_) and the new name ($_.name.substring(0, $_.name.length-4) + ‘.png’ )

Source: link

    
05.11.2015 / 18:43
3

I used the following command to rename all the files of a certain folder and a certain extension:

Dir *.txt | ForEach-Object  -begin { $count=1 }  -process { rename-item $_ -NewName "$count.txt"; $count++ }

It must be in the folder you want to rename the files to.

NOTE: It does not distinguish names made up of numbers.

    
05.11.2015 / 19:03