Saltar al contenido principal

Lab 8.3: Administración de Sistemas con PowerShell

Objetivos de Aprendizaje​

Al final de este laboratorio, usted será capaz de:

  • Crear scripts de administración de sistemas
  • Automatizar tareas de mantenimiento
  • Generar informes del sistema
  • Gestionar usuarios y permisos

Duración Estimada​

50 minutos

Prerrequisitos​

  • VM Windows 10/11
  • Derechos de administrador
  • Conocimientos básicos de PowerShell

Contexto Profesional​

Los scripts de administración se utilizan para:

  • Automatizar tareas repetitivas
  • Mantener la coherencia de las configuraciones
  • Generar informes de cumplimiento
  • Gestionar cuentas de usuario

Parte 1: Informe Completo del Sistema​

Paso 1.1: Script de informe​

Cree un script Get-SystemReport.ps1:

<#
.SYNOPSIS
Genere un rapport complet du systeme
.DESCRIPTION
Collecte les informations systeme, reseau, stockage et securite
.EXAMPLE
.\Get-SystemReport.ps1
#>

param(
[string]$OutputPath = "$env:USERPROFILE\Desktop\SystemReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
)

Write-Host "Generation du rapport systeme..." -ForegroundColor Cyan

# CSS pour le rapport HTML
$css = @"
<style>
body { font-family: 'Segoe UI', Arial; margin: 20px; background: #f5f5f5; }
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
h2 { color: #34495e; margin-top: 30px; }
table { border-collapse: collapse; width: 100%; margin: 10px 0; background: white; }
th { background: #3498db; color: white; padding: 12px; text-align: left; }
td { padding: 10px; border: 1px solid #ddd; }
tr:nth-child(even) { background: #f9f9f9; }
.warning { color: #e74c3c; font-weight: bold; }
.ok { color: #27ae60; font-weight: bold; }
.section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
</style>
"@

# Collecter les informations
$computerInfo = Get-CimInstance Win32_ComputerSystem
$osInfo = Get-CimInstance Win32_OperatingSystem
$cpuInfo = Get-CimInstance Win32_Processor
$diskInfo = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"
$networkInfo = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
$services = Get-Service | Where-Object {$_.Status -eq "Running"}
$processes = Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10

# Generer le HTML
$html = @"
<!DOCTYPE html>
<html>
<head>
<title>Rapport Systeme - $($computerInfo.Name)</title>
$css
</head>
<body>
<h1>Rapport Systeme - $($computerInfo.Name)</h1>
<p>Genere le: $(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')</p>

<div class="section">
<h2>Informations Generales</h2>
<table>
<tr><th>Propriete</th><th>Valeur</th></tr>
<tr><td>Nom de l'ordinateur</td><td>$($computerInfo.Name)</td></tr>
<tr><td>Domaine</td><td>$($computerInfo.Domain)</td></tr>
<tr><td>Fabricant</td><td>$($computerInfo.Manufacturer)</td></tr>
<tr><td>Modele</td><td>$($computerInfo.Model)</td></tr>
<tr><td>Systeme d'exploitation</td><td>$($osInfo.Caption)</td></tr>
<tr><td>Version</td><td>$($osInfo.Version)</td></tr>
<tr><td>Architecture</td><td>$($osInfo.OSArchitecture)</td></tr>
<tr><td>Dernier demarrage</td><td>$($osInfo.LastBootUpTime)</td></tr>
</table>
</div>

<div class="section">
<h2>Processeur</h2>
<table>
<tr><th>Propriete</th><th>Valeur</th></tr>
<tr><td>Nom</td><td>$($cpuInfo.Name)</td></tr>
<tr><td>Coeurs</td><td>$($cpuInfo.NumberOfCores)</td></tr>
<tr><td>Threads</td><td>$($cpuInfo.NumberOfLogicalProcessors)</td></tr>
<tr><td>Utilisation</td><td>$($cpuInfo.LoadPercentage)%</td></tr>
</table>
</div>

<div class="section">
<h2>Memoire</h2>
<table>
<tr><th>Propriete</th><th>Valeur</th></tr>
<tr><td>RAM Totale</td><td>$([math]::Round($computerInfo.TotalPhysicalMemory/1GB, 2)) Go</td></tr>
<tr><td>RAM Disponible</td><td>$([math]::Round($osInfo.FreePhysicalMemory/1MB, 2)) Go</td></tr>
<tr><td>Utilisation</td><td>$([math]::Round((1 - $osInfo.FreePhysicalMemory*1KB/$computerInfo.TotalPhysicalMemory)*100, 1))%</td></tr>
</table>
</div>

<div class="section">
<h2>Stockage</h2>
<table>
<tr><th>Disque</th><th>Taille</th><th>Libre</th><th>Utilisation</th></tr>
"@

foreach ($disk in $diskInfo) {
$percentUsed = [math]::Round((1 - $disk.FreeSpace/$disk.Size)*100, 1)
$statusClass = if ($percentUsed -gt 90) { "warning" } else { "ok" }
$html += @"
<tr>
<td>$($disk.DeviceID)</td>
<td>$([math]::Round($disk.Size/1GB, 2)) Go</td>
<td>$([math]::Round($disk.FreeSpace/1GB, 2)) Go</td>
<td class="$statusClass">$percentUsed%</td>
</tr>
"@
}

$html += @"
</table>
</div>

<div class="section">
<h2>Reseau</h2>
<table>
<tr><th>Adaptateur</th><th>Status</th><th>Vitesse</th></tr>
"@

foreach ($adapter in $networkInfo) {
$html += @"
<tr>
<td>$($adapter.Name)</td>
<td class="ok">$($adapter.Status)</td>
<td>$([math]::Round($adapter.LinkSpeed/1000000, 0)) Mbps</td>
</tr>
"@
}

$html += @"
</table>
</div>

<div class="section">
<h2>Top 10 Processus (Memoire)</h2>
<table>
<tr><th>Processus</th><th>PID</th><th>Memoire</th><th>CPU (s)</th></tr>
"@

foreach ($proc in $processes) {
$html += @"
<tr>
<td>$($proc.Name)</td>
<td>$($proc.Id)</td>
<td>$([math]::Round($proc.WorkingSet64/1MB, 2)) Mo</td>
<td>$([math]::Round($proc.CPU, 2))</td>
</tr>
"@
}

$html += @"
</table>
</div>

<div class="section">
<h2>Services en cours ($($services.Count))</h2>
<p>Total des services en execution: $($services.Count)</p>
</div>

</body>
</html>
"@

# Sauvegarder
$html | Out-File $OutputPath -Encoding UTF8
Write-Host "Rapport sauvegarde: $OutputPath" -ForegroundColor Green

# Ouvrir le rapport
Start-Process $OutputPath

Paso 1.2: Ejecutar el script​

.\Get-SystemReport.ps1

Pregunta 1: ¿Qué información le resulta más útil en este informe?


Parte 2: Gestión de Usuarios​

Paso 2.1: Script de gestión de usuarios​

# Script de gestion des utilisateurs locaux

function Get-LocalUserReport {
Write-Host "=== RAPPORT UTILISATEURS LOCAUX ===" -ForegroundColor Cyan

Get-LocalUser | ForEach-Object {
$user = $_
$groups = Get-LocalGroup | Where-Object {
(Get-LocalGroupMember $_.Name -ErrorAction SilentlyContinue).Name -contains "$env:COMPUTERNAME\$($user.Name)"
}

[PSCustomObject]@{
Nom = $user.Name
Actif = $user.Enabled
DernierLogin = $user.LastLogon
PasswordExpire = $user.PasswordExpires
Groupes = ($groups.Name -join ", ")
}
} | Format-Table -AutoSize
}

function New-StandardUser {
param(
[Parameter(Mandatory)]
[string]$Username,
[Parameter(Mandatory)]
[SecureString]$Password,
[string]$Description = "Utilisateur standard"
)

try {
New-LocalUser -Name $Username -Password $Password -Description $Description -ErrorAction Stop
Add-LocalGroupMember -Group "Utilisateurs" -Member $Username
Write-Host "[OK] Utilisateur $Username cree" -ForegroundColor Green
} catch {
Write-Host "[ERREUR] $($_.Exception.Message)" -ForegroundColor Red
}
}

function Remove-UserCompletely {
param(
[Parameter(Mandatory)]
[string]$Username
)

$confirm = Read-Host "Supprimer l'utilisateur $Username et son profil? (O/N)"
if ($confirm -eq "O") {
try {
# Supprimer l'utilisateur
Remove-LocalUser -Name $Username -ErrorAction Stop

# Supprimer le profil
$profilePath = "C:\Users\$Username"
if (Test-Path $profilePath) {
Remove-Item $profilePath -Recurse -Force
}

Write-Host "[OK] Utilisateur et profil supprimes" -ForegroundColor Green
} catch {
Write-Host "[ERREUR] $($_.Exception.Message)" -ForegroundColor Red
}
}
}

# Menu
Write-Host @"

GESTION DES UTILISATEURS
========================
1. Afficher le rapport des utilisateurs
2. Creer un utilisateur standard
3. Supprimer un utilisateur
4. Quitter

"@

$choice = Read-Host "Choix"
switch ($choice) {
"1" { Get-LocalUserReport }
"2" {
$name = Read-Host "Nom d'utilisateur"
$pass = Read-Host "Mot de passe" -AsSecureString
New-StandardUser -Username $name -Password $pass
}
"3" {
$name = Read-Host "Nom d'utilisateur a supprimer"
Remove-UserCompletely -Username $name
}
}

Parte 3: Script de Mantenimiento​

Paso 3.1: Mantenimiento automatizado​

<#
.SYNOPSIS
Script de maintenance systeme automatisee
#>

param(
[switch]$CleanTemp,
[switch]$CheckDisk,
[switch]$UpdateHelp,
[switch]$All
)

$ErrorActionPreference = "SilentlyContinue"

function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"INFO" { "White" }
"SUCCESS" { "Green" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
}
Write-Host "[$timestamp] [$Level] $Message" -ForegroundColor $color
}

function Clear-TempFiles {
Write-Log "Nettoyage des fichiers temporaires..." "INFO"

$paths = @(
$env:TEMP,
"C:\Windows\Temp",
"C:\Windows\Prefetch"
)

$totalSize = 0
$totalFiles = 0

foreach ($path in $paths) {
if (Test-Path $path) {
$files = Get-ChildItem $path -Recurse -Force -ErrorAction SilentlyContinue
$size = ($files | Measure-Object -Property Length -Sum).Sum
$count = $files.Count

Remove-Item "$path\*" -Recurse -Force -ErrorAction SilentlyContinue

$totalSize += $size
$totalFiles += $count
}
}

Write-Log "Nettoye: $totalFiles fichiers, $([math]::Round($totalSize/1MB, 2)) Mo" "SUCCESS"
}

function Test-DiskHealth {
Write-Log "Verification de l'etat des disques..." "INFO"

Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
$disk = $_
$percentFree = [math]::Round($disk.FreeSpace / $disk.Size * 100, 1)

if ($percentFree -lt 10) {
Write-Log "ALERTE: Disque $($disk.DeviceID) - Seulement $percentFree% libre!" "ERROR"
} elseif ($percentFree -lt 20) {
Write-Log "Attention: Disque $($disk.DeviceID) - $percentFree% libre" "WARNING"
} else {
Write-Log "Disque $($disk.DeviceID) - $percentFree% libre" "SUCCESS"
}
}
}

function Update-PSHelp {
Write-Log "Mise a jour de l'aide PowerShell..." "INFO"
try {
Update-Help -Force -ErrorAction Stop
Write-Log "Aide mise a jour" "SUCCESS"
} catch {
Write-Log "Echec mise a jour aide: $($_.Exception.Message)" "WARNING"
}
}

function Get-SystemHealth {
Write-Log "Verification de la sante systeme..." "INFO"

# CPU
$cpu = (Get-CimInstance Win32_Processor).LoadPercentage
if ($cpu -gt 90) {
Write-Log "CPU: $cpu% (CRITIQUE)" "ERROR"
} elseif ($cpu -gt 70) {
Write-Log "CPU: $cpu% (Eleve)" "WARNING"
} else {
Write-Log "CPU: $cpu% (Normal)" "SUCCESS"
}

# RAM
$os = Get-CimInstance Win32_OperatingSystem
$ramUsed = [math]::Round((1 - $os.FreePhysicalMemory*1KB / (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory) * 100, 1)
if ($ramUsed -gt 90) {
Write-Log "RAM: $ramUsed% utilise (CRITIQUE)" "ERROR"
} elseif ($ramUsed -gt 80) {
Write-Log "RAM: $ramUsed% utilise (Eleve)" "WARNING"
} else {
Write-Log "RAM: $ramUsed% utilise (Normal)" "SUCCESS"
}

# Services critiques
$criticalServices = @("wuauserv", "EventLog", "Dnscache")
foreach ($svc in $criticalServices) {
$service = Get-Service $svc -ErrorAction SilentlyContinue
if ($service.Status -ne "Running") {
Write-Log "Service $svc n'est pas en cours d'execution!" "WARNING"
}
}
}

# Execution
Write-Host @"
===============================================
SCRIPT DE MAINTENANCE SYSTEME
$(Get-Date -Format "dd/MM/yyyy HH:mm")
===============================================
"@ -ForegroundColor Cyan

Get-SystemHealth

if ($All -or $CleanTemp) { Clear-TempFiles }
if ($All -or $CheckDisk) { Test-DiskHealth }
if ($All -or $UpdateHelp) { Update-PSHelp }

Write-Host "`n===============================================" -ForegroundColor Cyan
Write-Log "Maintenance terminee" "SUCCESS"

Paso 3.2: Ejecutar el mantenimiento​

# Todas las tareas
.\Maintenance.ps1 -All

# O selectivamente
.\Maintenance.ps1 -CleanTemp -CheckDisk

Parte 4: Auditoría de Seguridad​

Paso 4.1: Script de auditoría​

# Audit de securite basique
Write-Host "=== AUDIT DE SECURITE ===" -ForegroundColor Cyan

$findings = @()

# 1. Verifier Windows Defender
$defender = Get-MpComputerStatus -ErrorAction SilentlyContinue
if ($defender) {
if (-not $defender.RealTimeProtectionEnabled) {
$findings += "[CRITIQUE] Protection en temps reel desactivee"
}
if (-not $defender.AntivirusEnabled) {
$findings += "[CRITIQUE] Antivirus desactive"
}
}

# 2. Verifier le pare-feu
$firewall = Get-NetFirewallProfile
foreach ($profile in $firewall) {
if (-not $profile.Enabled) {
$findings += "[CRITIQUE] Pare-feu $($profile.Name) desactive"
}
}

# 3. Verifier les mises a jour
$lastUpdate = (Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1).InstalledOn
$daysSinceUpdate = (New-TimeSpan -Start $lastUpdate -End (Get-Date)).Days
if ($daysSinceUpdate -gt 30) {
$findings += "[WARNING] Pas de mise a jour depuis $daysSinceUpdate jours"
}

# 4. Verifier les comptes admin
$admins = Get-LocalGroupMember -Group "Administrateurs"
if ($admins.Count -gt 3) {
$findings += "[WARNING] $($admins.Count) comptes dans le groupe Administrateurs"
}

# 5. Verifier les partages
$shares = Get-SmbShare | Where-Object {$_.Name -notmatch '^\$'}
if ($shares) {
$findings += "[INFO] $($shares.Count) partages actifs: $($shares.Name -join ', ')"
}

# Rapport
Write-Host "`n=== RESULTATS ===" -ForegroundColor Yellow
if ($findings.Count -eq 0) {
Write-Host "[OK] Aucun probleme detecte" -ForegroundColor Green
} else {
foreach ($finding in $findings) {
if ($finding -match "CRITIQUE") {
Write-Host $finding -ForegroundColor Red
} elseif ($finding -match "WARNING") {
Write-Host $finding -ForegroundColor Yellow
} else {
Write-Host $finding -ForegroundColor Cyan
}
}
}

Entregables​

  1. Scripts creados:

    • Get-SystemReport.ps1
    • Script de gestión de usuarios
    • Script de mantenimiento
    • Script de auditoría
  2. Capturas de pantalla:

    • Informe HTML generado
    • Ejecución del mantenimiento
    • Resultado de la auditoría
  3. Respuesta a la pregunta 1


Criterios de Evaluación​

CriterioPuntos
Script de informe30%
Gestión de usuarios20%
Script de mantenimiento30%
Script de auditoría20%

Laboratorio desarrollado en el marco del curso Sistemas Operativos - MÓDULO 8