⚠️ 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 3
El objetivo es usar una lista oficial como referencia. Cada archivo tiene un número alterno en el nombre, y el CSV nos dice cuál es el Employee ID correcto que debe usarse para renombrarlo.
Topic 3 Objective
The goal is to use an official list as the source of truth. Each file contains an alternate number in the name, and the CSV tells us which Employee ID should be used to rename it.
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 3"
Qué vamos a aprender
- Crear un CSV oficial de referencia.
- Leer una lista con Import-Csv.
- Extraer el Alt ID desde el nombre del archivo.
- Buscar el Employee ID correcto.
- Renombrar solamente cuando exista match válido.
What you will learn
- Create an official reference CSV.
- Read a list with Import-Csv.
- Extract the Alt ID from the file name.
- Look up the correct Employee ID.
- Rename only when a valid match exists.
Script 1 — Crear data sintética y lista oficial
Este script crea una carpeta de práctica, varios archivos JPG con Alt IDs en el nombre y un archivo Employees.csv con la relación oficial entre Alt_ID y Employee_ID.
Script 1 — Create synthetic data and official list
This script creates a practice folder, several JPG files with Alt IDs in the name, and an Employees.csv file with the official mapping between Alt_ID and Employee_ID.
# ======================================================
# Topic 3 - Script 1
# Create synthetic files and official CSV lookup list
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 3"
New-Item -Path $BasePath -ItemType Directory -Force | Out-Null
# Create the official lookup list
$Employees = @(
[PSCustomObject]@{ Alt_ID = "7001"; Employee_ID = "10001" },
[PSCustomObject]@{ Alt_ID = "7002"; Employee_ID = "10002" },
[PSCustomObject]@{ Alt_ID = "7003"; Employee_ID = "10003" },
[PSCustomObject]@{ Alt_ID = "7004"; Employee_ID = "10004" },
[PSCustomObject]@{ Alt_ID = "7005"; Employee_ID = "10005" },
[PSCustomObject]@{ Alt_ID = "7006"; Employee_ID = "10006" },
[PSCustomObject]@{ Alt_ID = "7007"; Employee_ID = "10007" },
[PSCustomObject]@{ Alt_ID = "7008"; Employee_ID = "10008" }
)
$Employees | Export-Csv -Path (Join-Path $BasePath "Employees.csv") -NoTypeInformation
# Create practice photo files using Alt IDs
$Files = @(
"Photo_7001.jpg",
"Badge-7002.jpg",
"Employee 7003 Profile.jpg",
"Scan_7004_old.jpg",
"P-7005.jpg",
"Temp 7006 upload.jpg",
"Image_7007_final.jpg",
"Archive-7008.jpg",
"NoMatch_9999.jpg"
)
foreach ($File in $Files) {
New-Item -Path (Join-Path $BasePath $File) -ItemType File -Force | Out-Null
}
Write-Host "Synthetic files and Employees.csv created in:" $BasePath
Get-ChildItem $BasePath | Select-Object Name
Script 2 — Buscar el Alt ID y renombrar con Employee ID
Este script importa el CSV, extrae el número desde el nombre del archivo, busca ese número como Alt_ID y renombra el archivo usando el Employee_ID correcto.
Script 2 — Look up the Alt ID and rename with Employee ID
This script imports the CSV, extracts the number from the file name, looks for that number as the Alt_ID, and renames the file using the correct Employee_ID.
# ======================================================
# Topic 3 - Script 2
# Rename files using the official CSV lookup list
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 3"
$CsvPath = Join-Path $BasePath "Employees.csv"
$Lookup = Import-Csv $CsvPath
Get-ChildItem $BasePath -Filter "*.jpg" | ForEach-Object {
# Extract the numeric Alt ID from the file name
$id = $_.BaseName -replace "\D", ""
# Find that Alt ID in the official CSV
$match = $Lookup | Where-Object { $_.Alt_ID -eq $id }
if ($match) {
$newName = "$($match.Employee_ID)$($_.Extension)"
$newPath = Join-Path $_.DirectoryName $newName
Rename-Item -Path $_.FullName -NewName $newName
[PSCustomObject]@{
Old_Name = $_.Name
Alt_ID = $id
Employee_ID = $match.Employee_ID
New_Name = $newName
Status = "Renamed"
}
}
else {
[PSCustomObject]@{
Old_Name = $_.Name
Alt_ID = $id
Employee_ID = ""
New_Name = ""
Status = "No match found"
}
}
}
Script 3 — Verificar archivos finales
Este script lista los archivos JPG finales y confirma cuáles quedaron renombrados con Employee ID y cuáles no tuvieron match.
Script 3 — Verify final files
This script lists the final JPG files and confirms which ones were renamed with Employee ID and which ones had no match.
# ======================================================
# Topic 3 - Script 3
# Verify final file names
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 3"
Get-ChildItem $BasePath -Filter "*.jpg" |
Select-Object Name |
Sort-Object Name
Explicación simple del script
- Import-Csv carga la lista oficial.
- $_.BaseName -replace "\D", "" extrae el número del nombre del archivo.
- Where-Object busca ese número en la columna Alt_ID.
- $match.Employee_ID devuelve el ID oficial correcto.
- Rename-Item cambia el nombre del archivo solo si existe match.
Simple script explanation
- Import-Csv loads the official list.
- $_.BaseName -replace "\D", "" extracts the number from the file name.
- Where-Object searches that number in the Alt_ID column.
- $match.Employee_ID returns the correct official ID.
- Rename-Item changes the file name only when a match exists.
Ejemplo esperado
| Archivo original | Alt ID | Nuevo nombre |
|---|---|---|
| Photo_7001.jpg | 7001 | 10001.jpg |
| Badge-7002.jpg | 7002 | 10002.jpg |
| Employee 7003 Profile.jpg | 7003 | 10003.jpg |
| NoMatch_9999.jpg | 9999 | No match found |
Expected example
| Original file | Alt ID | New name |
|---|---|---|
| Photo_7001.jpg | 7001 | 10001.jpg |
| Badge-7002.jpg | 7002 | 10002.jpg |
| Employee 7003 Profile.jpg | 7003 | 10003.jpg |
| NoMatch_9999.jpg | 9999 | No match found |
Conclusión
Este topic da un salto importante: ya no estamos limpiando nombres solamente, sino usando una lista oficial para tomar decisiones. Ese es el tipo de lógica que aparece en procesos reales: fotos de empleados, documentos, badges, expedientes o archivos que deben alinearse con una fuente confiable.
Conclusion
This topic is an important step forward: we are no longer just cleaning names, but using an official list to make decisions. This is the kind of logic used in real processes: employee photos, documents, badges, records, or files that must align with a trusted source.