Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

PowerShell – Rename Pictures to Image Taken

Posted on November 20, 2015December 17, 2023 By David Kittell
# If you haven't already done so you will need to run this to be able to execute PowerShell scripts
# You will need to run PowerShell as administrator to run this script
set-executionpolicy remotesigned

<# 
    .SYNOPSIS 
        Renames pictures. 
  
    .DESCRIPTION 
        The Rename-Pictures cmdlet to rename pictures to a format where the file creation time is first  
        in the name in this format: . The idea is that  
          
    .PARAMETER Path 
        Specifies the path to the folder where image files are located. Default is current location (Get-Location). 
  
    .EXAMPLE     
        PS C:\> Rename-Pictures 
   
        Description:  
        Renames all the pictures in folder you are in. 
  
    .EXAMPLE     
        PS C:\> Rename-Pictures -Path C:\Folder\Pics\  
   
        Description:  
        Renames all the pictures in the given folder path. 
          
    .NOTES 
        Author: Magnus Ringkjøb 
        E-mail: magnus.ringkjob@gmail.com 
        Image Dimensions Added By David Kittell - Kittell.net
#>

Param(
    [string]$Path
)

if ([string]::IsNullOrWhiteSpace($Path)) {
    $Path = (Get-Location)
}

$BackupFileName = '_backupdata.csv'
$ErrorFileName = '_errors.csv'

[reflection.assembly]::LoadFile("C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Drawing.dll") 
$Script:ErrorLogMsg = $Null
$Script:CorrectPath = $Null
  
$Path
  
$ImgsFound = (dir $Path -Include ('*.jpeg', '*.png', '*.gif', '*.jpg', '*.bmp', '*.png') -Recurse   | Select-Object -Property FullName, Name, BaseName, Extension)
  
          
# If any file was found 
  
# Array that takes in the old- and the new filename. This is used for saving a backup to .csv 
$BackupData = @() 
  
# Loops through the images found 
foreach ($Img in $ImgsFound) { 
    # Gets image data 
    $ImgData = New-Object System.Drawing.Bitmap($Img.FullName) 
 
 
    $ImgDimensions = $ImgData.Width.ToString() + $("x") + $ImgData.Height.ToString()
 
  
    try { 
        # Gets 'Date Taken' in bytes 
        [byte[]]$ImgBytes = $ImgData.GetPropertyItem(36867).Value 
    } 
    catch [System.Exception], [System.IO.IOException] { 
        [string]$ErrorMessage = ( 
                        (Get-Date).ToString('yyyyMMdd HH:mm:ss') + "`tERROR`tDid not change name for " + $Img.Name + ". Reason: " + $Error
        ) 
        $Script:ErrorLogMsg += $ErrorMessage + "`r`n"
        Write-Host -ForegroundColor Red -Object $ErrorMessage
  
        # Clears any error messages 
        $Error.Clear() 
  
        # No reason to continue. Move on to the next file 
        continue
    } 
  
    # Gets the date and time from bytes 
    [string]$dateString = [System.Text.Encoding]::ASCII.GetString($ImgBytes) 
    # Formats the date to the desired format 
    [string]$dateTaken = [datetime]::ParseExact($dateString, "yyyy:MM:dd HH:mm:ss`0", $Null).ToString('yyyy-MM-dd_HH.mm.ss.ms') 
    # The new file name for the image 
    #  [string]$NewFileName = $dateTaken + '-' + $Img.Name 
    [string]$NewFileName = $dateTaken + "_" + $ImgDimensions + [System.IO.Path]::GetExtension($Img.Name)
                  
    $ImgData.Dispose() 
    try {  
        Rename-Item -NewName $NewFileName -Path $Img.FullName -ErrorAction Stop 
        Write-Host -Object ("Renamed " + $Img.Name + " to " + $NewFileName) 
    } 
    catch { 
        [string]$ErrorMessage = ( 
                        (Get-Date).ToString('yyyyMMdd HH:mm:ss') + "`tERROR`tDid not change name for " + $Img.Name + ". Reason: " + $Error
        ) 
        $Script:ErrorLogMsg += $ErrorMessage + "`r`n"
        Write-Host -ForegroundColor Red -Object $ErrorMessage
  
        # Clears any previous error messages 
        $Error.Clear() 
  
        # No reason to continue. Move on to the next file 
        continue
    } 
                  
    # Collect data to be added to the backup file 
    $BUData = New-Object -TypeName System.Object 
    $BUData | Add-Member -MemberType NoteProperty -Name "OldName" -Value $Img.Name 
    $BUData | Add-Member -MemberType NoteProperty -Name "NewName" -Value $NewFileName
  
    # Add data to backup collection 
    $BackupData += $BUData
  
    try { 
        $BackupData | Export-Csv -NoTypeInformation -Path "$Path\\$BackupFileName"
    } 
    catch [System.Exception] { 
        [string]$ErrorMessage = "((Get-Date).ToString('yyyyMMdd HH:mm:ss'))`tERROR`tCould not create $Path $BackupFileName Reason: " + $Error
        $Script:ErrorLogMsg += $ErrorMessage + "`r`n"
  
        # Clears any error messages 
        $Error.Clear() 
    } 
       
}
# If there was a problem during the run: 
# Print to file, and let user know 
if ($Script:ErrorLogMsg -ne $Null) { 
    $ErrorLogMsg | Export-Csv -NoTypeInformation -Path "$Path\\$ErrorFileName"
    Write-Host -ForegroundColor Red -Object ( 
        "Errors were found. Please check " + $Path + "_errors.log"
    ) 
}

GitHub: https://gist.github.com/dkittell/746e69967a7f4d0f0c52

Reference: https://gallery.technet.microsoft.com/Rename-picture-files-with-97738191 (Magnus Ringkjøb)

Originally Posted on November 20, 2015
Last Updated on December 17, 2023
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code PowerShell

Post navigation

Previous post
Next post

Related Posts

Ektron Content Folder Names

Posted on February 4, 2014October 26, 2015

SELECT c.[content_id] ,c.[content_title] ,c.[content_html] ,c.[content_status] ,CASE WHEN c.[content_status] = ‘A’ THEN ‘Approved’ WHEN c.[content_status] = ‘O’ THEN ‘Checked Out’ WHEN c.[content_status] = ‘I’ THEN ‘Checked In’ WHEN c.[content_status] = ‘S’ THEN ‘Submitted for Approval’ WHEN c.[content_status] = ‘M’ THEN ‘Marked for Deletion’ WHEN c.[content_status] = ‘P’ THEN ‘Pending Go Live…

Read More

C# ASPX Email File

Posted on April 4, 2014October 26, 2015

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <asp:label id="lblUploadStatus" runat="server"></asp:label><br /> <asp:label id="lblEmailStatus" runat="server"></asp:label><br /> <form id="form1" runat="server"> <div> From: <asp:textbox id="txtFromEmail" runat="server" /><br /> <asp:fileupload id="FileUpload1" runat="server" /><br /> <asp:button id="btnUpload" runat="server" text="Submit" onclick="btnUpload_Click"…

Read More

Mac Terminal – Random Readable Password

Posted on February 1, 2017

I recently was challenged to create a random readable password for Mac OS. While I designed this for Mac OS it’s likely it will work with little to no changes on any UNIX system. Password format was two digit number then a word followed by another word with special characters…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • PowerShell - IIS Remove Site
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • PowerShell - IIS Remove Site
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories
  • Raspberry Pi - Remove Default Apps
  • PowerShell - Change Windows CD/DVD Drive Letter
©2025 David Kittell | WordPress Theme by SuperbThemes