PowerShell Training · Topic 9

Normalizar extensiones de archivos

Un ejercicio práctico para convertir extensiones como .JPG, .jpeg o .JPEG a un formato estándar.

Normalize file extensions

A hands-on exercise to convert extensions like .JPG, .jpeg, or .JPEG into one standard format.

⚠️ Advertencia crítica antes de correr cualquier script

No ejecutes este tipo de script en un ambiente de producción, carpeta real, servidor compartido, unidad de red o sistema institucional sin autorización formal.

PowerShell es una herramienta poderosa: un comando de renombrado masivo puede modificar cientos o miles de archivos en segundos. En una carpeta equivocada, eso puede causar pérdida de trazabilidad, fallos en procesos automáticos, interrupciones operativas o incidentes de ciberseguridad.

Regla obligatoria del training: primero se trabaja con data sintética, luego se valida con una muestra pequeña, después se prueba con -WhatIf cuando aplique, y solo entonces se considera ejecutar en datos reales siguiendo los protocolos de la organización.

  • Permisos: usa solamente carpetas donde tengas autorización explícita.
  • Backups: confirma que exista copia de seguridad o posibilidad real de recuperación.
  • Cybersecurity: cumple las políticas internas, controles de acceso, change management y principios de menor privilegio.
  • Producción: nunca ejecutes scripts masivos directamente sobre producción sin revisión, aprobación y plan de reversa.

⚠️ Critical warning before running any script

Do not run this type of script in a production environment, real folder, shared server, network drive, or institutional system without formal authorization.

PowerShell is a powerful tool: a bulk command can modify hundreds or thousands of files in seconds. In the wrong folder, it can break traceability, disrupt automated processes, create operational issues, or trigger cybersecurity incidents.

Mandatory training rule: start with synthetic data, validate with a small sample, test with -WhatIf when applicable, and only then consider real data while following your organization’s protocols.

  • Permissions: use only folders where you have explicit authorization.
  • Backups: confirm that a backup or real recovery option exists.
  • Cybersecurity: follow internal policies, access controls, change management, and least-privilege principles.
  • Production: never run bulk scripts directly on production without review, approval, and rollback planning.

Objetivo del Topic 9

El objetivo es estandarizar extensiones de archivos de imagen para que todas terminen en .jpg. Esto evita problemas cuando otros sistemas esperan un formato consistente.

01 · Crear extensiones mixtas
02 · Normalizar a .jpg
03 · Verificar resultado
Idea central: no estamos cambiando el contenido del archivo; estamos normalizando la extensión para mejorar consistencia, carga y control.

Topic 9 Objective

The goal is to standardize image file extensions so they all end in .jpg. This prevents issues when other systems expect a consistent format.

01 · Create mixed extensions
02 · Normalize to .jpg
03 · Verify result
Core idea: we are not changing the file content; we are normalizing the extension to improve consistency, loading, and control.

Ruta de trabajo

Todo se ejecuta dentro de una carpeta controlada:

Working folder

Everything runs inside a controlled folder:

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 9"

Qué vamos a aprender

  • Crear archivos con extensiones inconsistentes.
  • Filtrar archivos por extensiones JPG/JPEG.
  • Usar $_.Extension y $_.BaseName.
  • Renombrar extensiones sin cambiar el nombre base.
  • Validar que todo quedó en formato .jpg.

What you will learn

  • Create files with inconsistent extensions.
  • Filter files by JPG/JPEG extensions.
  • Use $_.Extension and $_.BaseName.
  • Rename extensions without changing the base name.
  • Validate that everything ended in .jpg format.
01

Script 1 — Crear data sintética con extensiones mixtas

Este script crea archivos de práctica con diferentes variantes de extensión: .JPG, .jpeg, .JPEG y .jpg.

Script 1 — Create synthetic data with mixed extensions

This script creates practice files with different extension variants: .JPG, .jpeg, .JPEG, and .jpg.

# ======================================================
# Topic 9 - Script 1
# Create synthetic files with mixed extensions
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 9"
$PhotosPath = Join-Path $BasePath "Photos"

New-Item -Path $PhotosPath -ItemType Directory -Force | Out-Null

$Files = @(
    "10001.JPG",
    "10002.jpeg",
    "10003.JPEG",
    "10004.jpg",
    "Employee_10005.JPG",
    "Badge_10006.JpEg",
    "Profile_10007.JPEG",
    "Document_10008.pdf"
)

foreach ($File in $Files) {
    "Synthetic content for $File" | Set-Content -Path (Join-Path $PhotosPath $File)
}

Write-Host "Synthetic files created in:" $PhotosPath
Get-ChildItem $PhotosPath -File | Select-Object Name, Extension
02

Script 2 — Normalizar extensiones a .jpg

Este script busca archivos con extensiones JPG/JPEG en distintas combinaciones de mayúsculas y minúsculas, y los renombra para que terminen en .jpg.

Script 2 — Normalize extensions to .jpg

This script finds files with JPG/JPEG extensions in different upper/lowercase combinations and renames them so they end in .jpg.

# ======================================================
# Topic 9 - Script 2
# Normalize JPG/JPEG extensions to .jpg
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 9"
$PhotosPath = Join-Path $BasePath "Photos"

Get-ChildItem $PhotosPath -File |
Where-Object { $_.Extension -match "(?i)^\.jpe?g$" } |
ForEach-Object {

    $newName = $_.BaseName + ".jpg"

    if ($_.Name -ne $newName) {
        Rename-Item -Path $_.FullName -NewName $newName

        [PSCustomObject]@{
            Old_Name = $_.Name
            New_Name = $newName
            Status = "Normalized"
        }
    }
    else {
        [PSCustomObject]@{
            Old_Name = $_.Name
            New_Name = $_.Name
            Status = "Already standard"
        }
    }
}
Prueba segura: puedes agregar -WhatIf al final de Rename-Item para simular el cambio antes de renombrar.
Safe test: you can add -WhatIf at the end of Rename-Item to simulate the change before renaming.
03

Script 3 — Verificar extensiones finales

Este script lista los archivos después del cambio y resume cuántos archivos quedaron por cada extensión.

Script 3 — Verify final extensions

This script lists the files after the change and summarizes how many files remain by extension.

# ======================================================
# Topic 9 - Script 3
# Verify final file extensions
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 9"
$PhotosPath = Join-Path $BasePath "Photos"

Write-Host "Final files:"
Get-ChildItem $PhotosPath -File | Select-Object Name, Extension

Write-Host ""
Write-Host "Extension summary:"
Get-ChildItem $PhotosPath -File |
Group-Object Extension |
Select-Object Name, Count |
Sort-Object Name

Explicación simple del script

  • Get-ChildItem -File obtiene los archivos de la carpeta.
  • $_.Extension lee la extensión del archivo.
  • (?i) hace que la comparación no distinga mayúsculas/minúsculas.
  • \.jpe?g acepta tanto .jpg como .jpeg.
  • $_.BaseName + ".jpg" conserva el nombre base y cambia solo la extensión.

Simple script explanation

  • Get-ChildItem -File gets the files from the folder.
  • $_.Extension reads the file extension.
  • (?i) makes the comparison case-insensitive.
  • \.jpe?g accepts both .jpg and .jpeg.
  • $_.BaseName + ".jpg" keeps the base name and changes only the extension.

Ejemplo esperado

AntesDespués
10001.JPG10001.jpg
10002.jpeg10002.jpg
10003.JPEG10003.jpg
Badge_10006.JpEgBadge_10006.jpg

Expected example

BeforeAfter
10001.JPG10001.jpg
10002.jpeg10002.jpg
10003.JPEG10003.jpg
Badge_10006.JpEgBadge_10006.jpg

Conclusión

Este topic enseña cómo mejorar consistencia en carpetas de archivos. Aunque las extensiones parezcan un detalle pequeño, muchos sistemas de carga, reportes o integraciones dependen de nombres y formatos estandarizados.

Lección clave: normalizar extensiones reduce errores silenciosos y facilita que otros procesos automáticos trabajen con reglas claras.

Conclusion

This topic teaches how to improve consistency in file folders. Even though extensions may look like a small detail, many upload systems, reports, or integrations depend on standardized names and formats.

Key lesson: normalizing extensions reduces silent errors and helps other automated processes work with clear rules.