Skip to content

Instantly share code, notes, and snippets.

@varlen
Created December 2, 2015 04:55
Show Gist options
  • Save varlen/ad018fb685eaecda972b to your computer and use it in GitHub Desktop.
Save varlen/ad018fb685eaecda972b to your computer and use it in GitHub Desktop.
Quick and dirty hack to rename a batch of files on Windows using PowerShell.
function Select-Folder($message='Select a folder', $path = 0) {
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null) {
$folder.self.Path
}
}
$Title = "Renomear Fotos Automaticamente";
$Info = "Escolha como você deseja reorganizar os nomes dos arquivos das fotos:"
$options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Data Tirada", "&Numerar todas de 1 até N", "&Cancelar")
[int]$defaultchoice = 2
$opt = $host.UI.PromptForChoice($Title , $Info , $Options, $defaultchoice)
$myPath = Select-Folder -m "Selecione a pasta que contem as fotos:";
if ( $myPath -eq $null ) { $opt = 2; }
switch($opt)
{
0 { Write-Host "-> Renomear por data" -ForegroundColor Blue;
# Generate filenames based on the data the picture was taken
$myPath = $myPath + "\";
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.namespace( $myPath )
foreach( $File in $objFolder.items() ) {
If ( $data = $objFolder.getDetailsOf( $File, 12 ) ) {
# Great, we've got metadata
} else {
# No metadata :/ Use creation date
$data = $objFolder.getDetailsOf( $File, 4 );
};
$time = $data.Split(" ")[1];
$date2 = $data.Split(" ")[0];
$hour = $time.Split(":")[0];
$minute = $time.Split(":")[1];
$day = $date2.Split("/")[0];
$month = $date2.Split("/")[1];
$year = $date2.Split("/")[2];
$second = Get-Random -Minimum 0 -Maximum 60;
if ( $second -lt 10 ) {
$second = "0$second";
};
$3rand = Get-Random -Minimum 100 -Maximum 1000;
$newname = "$year-$month-$day-$hour-$minute-$second-$3rand";
$extension = $File.Path.replace( $myPath , '' ).replace( $File.Name, '' );
$newname += $extension;
Rename-Item $File.Path $newname;
Write-Host $newname;
}
ii $myPath;
}
1 { Write-Host "-> Numerar de 1 até N" -ForegroundColor Blue;
$prefix = Read-Host "Escreva um prefixo para o nome dos arquivos( Opcional ):";
If ( $prefix -ne '' ) { $prefix = $prefix + '-' };
$count = 1;
$myPath = $myPath;
ls "$myPath\*.*" | Sort-Object CreationTime | Foreach-Object {
$new_name = "$prefix$count" + $_.extension;
Write-Host "$_ `t->`t`t $new_name";
Rename-Item $_ $new_name;
$count++;
}
ii $myPath;
}
2 { Write-Host "Ok, tchau!" -ForegroundColor Green}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment