Rename all files in a folder to random names

Asked

Viewed 1,307 times

4

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

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

however the %RANDOM% puts the same number for all files and as these may not have the same name only ends up changing one.

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

1 answer

2


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 at the Get-ChildItem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.