⚠️ 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 8
El objetivo es comparar los archivos de una carpeta contra una lista oficial de empleados activos. Si el nombre base del archivo coincide con un Employee_ID activo, se marca como autorizado. Si no aparece en la lista, se marca para revisión.
Topic 8 Objective
The goal is to compare files in a folder against an official active employee list. If the file base name matches an active Employee_ID, it is marked as authorized. If it does not appear in the list, it is marked for review.
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 8"
Qué vamos a aprender
- Crear una lista oficial de empleados activos.
- Comparar archivos contra una fuente autorizada.
- Usar -contains para validar IDs.
- Clasificar archivos como autorizados o no autorizados.
- Generar un reporte de gobernanza para revisión.
What you will learn
- Create an official active employee list.
- Compare files against an authorized source.
- Use -contains to validate IDs.
- Classify files as authorized or unauthorized.
- Generate a governance report for review.
Script 1 — Crear data sintética y lista de empleados activos
Este script crea una carpeta de fotos, una carpeta de reportes y un CSV con empleados activos. También crea archivos válidos y archivos que deben caer en revisión.
Script 1 — Create synthetic data and active employee list
This script creates a photos folder, a reports folder, and a CSV with active employees. It also creates valid files and files that should be flagged for review.
# ======================================================
# Topic 8 - Script 1
# Create synthetic files and active employee list
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 8"
$PhotosPath = Join-Path $BasePath "Photos"
$ReportsPath = Join-Path $BasePath "Reports"
$CsvPath = Join-Path $BasePath "ActiveEmployees.csv"
New-Item -Path $PhotosPath, $ReportsPath -ItemType Directory -Force | Out-Null
# Official list of active employees
$ActiveEmployees = @(
[PSCustomObject]@{ Employee_ID = "10001"; Employee_Name = "John Smith"; Status = "Active" },
[PSCustomObject]@{ Employee_ID = "10002"; Employee_Name = "Maria Garcia"; Status = "Active" },
[PSCustomObject]@{ Employee_ID = "10003"; Employee_Name = "Carlos Rivera"; Status = "Active" },
[PSCustomObject]@{ Employee_ID = "10004"; Employee_Name = "Ana Lopez"; Status = "Active" },
[PSCustomObject]@{ Employee_ID = "10005"; Employee_Name = "Robert Lee"; Status = "Active" }
)
$ActiveEmployees | Export-Csv -Path $CsvPath -NoTypeInformation
# Files named by Employee ID
$Files = @(
"10001.jpg",
"10002.jpg",
"10003.jpg",
"10004.jpg",
"10005.jpg",
"20001.jpg",
"99999.jpg",
"Temp_Upload_8001.jpg"
)
foreach ($File in $Files) {
"Synthetic file content for $File" | Set-Content -Path (Join-Path $PhotosPath $File)
}
Write-Host "Synthetic data created in:" $BasePath
Get-ChildItem $PhotosPath -File | Select-Object Name
Script 2 — Validar archivos contra empleados activos
Este script importa la lista oficial, toma el nombre base de cada archivo y valida si ese ID existe en la lista de empleados activos.
Script 2 — Validate files against active employees
This script imports the official list, takes the base name of each file, and validates whether that ID exists in the active employee list.
# ======================================================
# Topic 8 - Script 2
# Validate files against active employees
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 8"
$PhotosPath = Join-Path $BasePath "Photos"
$CsvPath = Join-Path $BasePath "ActiveEmployees.csv"
$Active = Import-Csv $CsvPath
Get-ChildItem $PhotosPath -File | ForEach-Object {
$fileId = $_.BaseName
$match = $Active | Where-Object { $_.Employee_ID -eq $fileId }
if ($match) {
[PSCustomObject]@{
File_Name = $_.Name
Employee_ID = $fileId
Employee_Name = $match.Employee_Name
Validation_Result = "Authorized - Active employee"
}
}
else {
[PSCustomObject]@{
File_Name = $_.Name
Employee_ID = $fileId
Employee_Name = ""
Validation_Result = "Needs review - Not in active employee list"
}
}
}
Script 3 — Exportar reporte de validación
Este script genera un CSV con todos los archivos revisados y su resultado: autorizado o necesita revisión.
Script 3 — Export validation report
This script generates a CSV with all reviewed files and their result: authorized or needs review.
# ======================================================
# Topic 8 - Script 3
# Export validation report
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 8"
$PhotosPath = Join-Path $BasePath "Photos"
$CsvPath = Join-Path $BasePath "ActiveEmployees.csv"
$ReportPath = Join-Path $BasePath "Reports\Active_Employee_File_Validation_Report.csv"
$Active = Import-Csv $CsvPath
$Report = Get-ChildItem $PhotosPath -File | ForEach-Object {
$fileId = $_.BaseName
$match = $Active | Where-Object { $_.Employee_ID -eq $fileId }
[PSCustomObject]@{
File_Name = $_.Name
File_Path = $_.FullName
Employee_ID_From_File = $fileId
Employee_Name = if ($match) { $match.Employee_Name } else { "" }
Is_Active_Employee = if ($match) { "Yes" } else { "No" }
Validation_Result = if ($match) { "Authorized - Active employee" } else { "Needs review - Not in active employee list" }
LastWriteTime = $_.LastWriteTime
}
}
$Report | Export-Csv -Path $ReportPath -NoTypeInformation
Write-Host "Validation report created:"
Write-Host $ReportPath
$Report | Format-Table File_Name, Employee_ID_From_File, Is_Active_Employee, Validation_Result -AutoSize
Explicación simple del script
- Import-Csv carga la lista oficial de empleados activos.
- $_.BaseName toma el nombre del archivo sin extensión.
- Where-Object busca el ID del archivo en la lista activa.
- if ($match) marca el archivo como autorizado.
- else lo marca como necesita revisión.
- Export-Csv guarda la evidencia del control.
Simple script explanation
- Import-Csv loads the official active employee list.
- $_.BaseName takes the file name without extension.
- Where-Object searches the file ID in the active list.
- if ($match) marks the file as authorized.
- else marks it as needing review.
- Export-Csv saves the control evidence.
Ejemplo esperado
| Archivo | Resultado |
|---|---|
| 10001.jpg | Authorized - Active employee |
| 10003.jpg | Authorized - Active employee |
| 20001.jpg | Needs review - Not in active employee list |
| Temp_Upload_8001.jpg | Needs review - Not in active employee list |
Expected example
| File | Result |
|---|---|
| 10001.jpg | Authorized - Active employee |
| 10003.jpg | Authorized - Active employee |
| 20001.jpg | Needs review - Not in active employee list |
| Temp_Upload_8001.jpg | Needs review - Not in active employee list |
Conclusión
Este topic enseña cómo aplicar gobernanza a una carpeta de archivos. Un archivo puede estar técnicamente presente, pero eso no significa que deba ser procesado, publicado o cargado a otro sistema. Validarlo contra una lista oficial reduce errores, riesgos y uso de información no autorizada.
Conclusion
This topic teaches how to apply governance to a folder of files. A file may technically exist, but that does not mean it should be processed, published, or loaded into another system. Validating it against an official list reduces errors, risks, and unauthorized information use.