Rename all files in a folder to random names

Posted on

Question :

I need a command to rename all files in a folder to a random name, which keep the same file extension, and preferably with numbers, what I’ve achieved so far was this:

forfiles /P c:teste /c "cmd /c rename @path %RANDOM%.@ext"

however %RANDOM% puts the same number for all files and as these can not have the same name it only changes one.

Powershell is a very different language from day to day so here I ask a solution from someone with experience in it


Answer :

You can do the following:

$caminho = Get-Location # Pode alterar se quiser outro caminho que não o actual

# Lista todos os ficheiros que existam no caminho actual
foreach($ficheiro in $(Get-ChildItem -File -Path $caminho)) {

    # Guarda a extensão original do ficheiro 
    $extensao = [System.IO.Path]::GetExtension($ficheiro.FullName);

    # E cria um nome aleatório e altera a extensão para a extensão original do ficheiro
    $nomeAleatorio = [System.IO.Path]::ChangeExtension([System.IO.Path]::GetRandomFileName(), $extensao)

    # Cria o nome caminho do ficheiro com base no caminho actual e no novo nome.
    $novoCaminho = Join-Path $(Split-Path $ficheiro.FullName -Parent) $nomeAleatorio

    Write-Host "A alterar o nome da ficheiro $($ficheiro.Name) para $nomeAleatorio"

    Move-Item -Path $ficheiro.FullName -Destination $novoCaminho

If you need to apply the same logic to all files in the directory and subdirectories, add the switch -Recursive to Get-ChildItem .


Leave a Reply

Your email address will not be published. Required fields are marked *