Pastebin
Retrouvez, créez et partagez vos snippets en temps réel.
Rechercher un Pastebin
Aucun paste trouvé.
Créer un paste
Pastebin
Blog
GenData
<# .SYNOPSIS Génère massivement des fichiers de test pour partage SMB .DESCRIPTION Crée une arborescence de répertoires avec fichiers aléatoires Paramètres : poids total, taille min/max fichiers, profondeur .PARAMETER TargetPath Chemin cible (UNC ou local) - DOIT être un dossier de test vide . PARAMETER TotalSizeGB Taille totale cumulée en Go (ex: 50) .PARAMETER MinFileSizeMB Taille minimale par fichier en Mo (ex: 1) .PARAMETER MaxFileSizeMB Taille maximale par fichier en Mo (ex: 500) .PARAMETER MaxDepth Profondeur maximale de l'arborescence (ex: 5) .PARAMETER FolderPerLevel Nombre de sous-dossiers par niveau (défaut: 3) .EXAMPLE .\Generate-SMBTestData.ps1 -TargetPath "\\srv01\test\data" -TotalSizeGB 100 -MinFileSizeMB 10 -MaxFileSizeMB 200 -MaxDepth 4 #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] param( [Parameter(Mandatory=$true)] [ValidateScript({ if (Test-Path $_ -PathType Container) { $true } else { throw "Le chemin '$_' n'existe pas ou n'est pas un dossier" } })] [string]$TargetPath, [Parameter(Mandatory=$true)] [ValidateRange(1, 10000)] [int]$TotalSizeGB, [Parameter(Mandatory=$true)] [ValidateRange(0. 1, 10000)] [double]$MinFileSizeMB, [Parameter(Mandatory=$true)] [ValidateRange(0.1, 10000)] [double]$MaxFileSizeMB, [Parameter(Mandatory=$true)] [ValidateRange(1, 20)] [int]$MaxDepth, [Parameter(Mandatory=$false)] [ValidateRange(1, 50)] [int]$FolderPerLevel = 3 ) # ============================================ # CONFIGURATION ET VALIDATIONS # ============================================ $ErrorActionPreference = "Stop" $StartTime = Get-Date # Conversion en bytes $TotalSizeBytes = [int64]$TotalSizeGB * 1GB $MinFileSizeBytes = [int64]($MinFileSizeMB * 1MB) $MaxFileSizeBytes = [int64]($MaxFileSizeMB * 1MB) # Validation cohérence if ($MinFileSizeBytes -gt $MaxFileSizeBytes) { throw "❌ Erreur : Taille minimale ($MinFileSizeMB MB) > Taille maximale ($MaxFileSizeMB MB)" } # Vérification espace disque disponible $Volume = Get-PSDrive -PSProvider FileSystem | Where-Object { $TargetPath -like "$($_.Root)*" } if ($Volume.Free -lt ($TotalSizeBytes * 1. 1)) { Write-Warning "⚠️ Espace libre insuffisant : $([math]::Round($Volume.Free/1GB, 2)) GB disponible pour $TotalSizeGB GB demandés (+10% marge)" if (-not $PSCmdlet.ShouldContinue("Continuer malgré tout ?", "Espace disque")) { exit 1 } } # ============================================ # CONFIRMATION UTILISATEUR # ============================================ Write-Host "`n╔═══════════════════════════════════════════════════════════╗" -ForegroundColor Cyan Write-Host "║ GÉNÉRATION DE DONNÉES DE TEST SMB ║" -ForegroundColor Cyan Write-Host "╚═══════════════════════════════════════════════════════════╝" -ForegroundColor Cyan Write-Host "`n📂 Chemin cible : " -NoNewline; Write-Host $TargetPath -ForegroundColor Yellow Write-Host "💾 Volume total : " -NoNewline; Write-Host "$TotalSizeGB GB ($TotalSizeBytes bytes)" -ForegroundColor Yellow Write-Host "📄 Taille fichiers : " -NoNewline; Write-Host "$MinFileSizeMB MB - $MaxFileSizeMB MB" -ForegroundColor Yellow Write-Host "📁 Profondeur max : " -NoNewline; Write-Host "$MaxDepth niveaux" -ForegroundColor Yellow Write-Host "🌳 Dossiers/niveau : " -NoNewline; Write-Host "$FolderPerLevel" -ForegroundColor Yellow # Estimation $EstimatedFiles = [math]:: Ceiling($TotalSizeBytes / (($MinFileSizeBytes + $MaxFileSizeBytes) / 2)) Write-Host "`n⏱️ Fichiers estimés : " -NoNewline; Write-Host "~$EstimatedFiles" -ForegroundColor Magenta if (-not $PSCmdlet.ShouldProcess($TargetPath, "Générer $TotalSizeGB GB de données de test")) { Write-Host "`n❌ Opération annulée par l'utilisateur" -ForegroundColor Red exit 0 } # ============================================ # FONCTIONS AUXILIAIRES # ============================================ function New-RandomFile { param( [string]$Path, [int64]$SizeBytes ) # Génération efficace par blocs de 64 KB $BufferSize = 64KB $Buffer = New-Object byte[] $BufferSize $RNG = [System.Security.Cryptography.RNGCryptoServiceProvider]::new() try { $Stream = [System.IO.File]::Create($Path) $Remaining = $SizeBytes while ($Remaining -gt 0) { $ChunkSize = [math]::Min($BufferSize, $Remaining) $RNG.GetBytes($Buffer) $Stream.Write($Buffer, 0, $ChunkSize) $Remaining -= $ChunkSize } $Stream.Close() return $true } catch { Write-Error "Échec création fichier ${Path}: $_" return $false } finally { if ($Stream) { $Stream.Dispose() } $RNG.Dispose() } } function New-RandomFolderStructure { param( [string]$BasePath, [int]$CurrentDepth, [int]$MaxDepth, [int]$FoldersPerLevel ) $Folders = @($BasePath) if ($CurrentDepth -lt $MaxDepth) { for ($i = 0; $i -lt $FoldersPerLevel; $i++) { $FolderName = "Folder_L$CurrentDepth`_$([Guid]::NewGuid().ToString().Substring(0,8))" $NewPath = Join-Path $BasePath $FolderName try { New-Item -Path $NewPath -ItemType Directory -Force | Out-Null $Folders += New-RandomFolderStructure -BasePath $NewPath -CurrentDepth ($CurrentDepth + 1) -MaxDepth $MaxDepth -FoldersPerLevel $FoldersPerLevel } catch { Write-Warning "⚠️ Impossible de créer $NewPath : $_" } } } return $Folders } # ============================================ # GÉNÉRATION ARBORESCENCE # ============================================ Write-Host "`n[1/3] 🌳 Création de l'arborescence de dossiers..." -ForegroundColor Green $AllFolders = New-RandomFolderStructure -BasePath $TargetPath -CurrentDepth 0 -MaxDepth $MaxDepth -FoldersPerLevel $FolderPerLevel Write-Host " ✓ $($AllFolders.Count) dossiers créés" -ForegroundColor Green # ============================================ # GÉNÉRATION FICHIERS # ============================================ Write-Host "`n[2/3] 📄 Génération des fichiers..." -ForegroundColor Green $TotalGenerated = 0 $FileCount = 0 $ProgressCounter = 0 while ($TotalGenerated -lt $TotalSizeBytes) { # Sélection aléatoire d'un dossier $TargetFolder = $AllFolders | Get-Random # Calcul taille fichier aléatoire $Remaining = $TotalSizeBytes - $TotalGenerated $MaxPossible = [math]::Min($MaxFileSizeBytes, $Remaining) $FileSize = Get-Random -Minimum $MinFileSizeBytes -Maximum $MaxPossible # Nom de fichier $FileName = "TestFile_$([Guid]::NewGuid().ToString()).bin" $FilePath = Join-Path $TargetFolder $FileName # Création if (New-RandomFile -Path $FilePath -SizeBytes $FileSize) { $TotalGenerated += $FileSize $FileCount++ # Affichage progression tous les 10 fichiers $ProgressCounter++ if ($ProgressCounter % 10 -eq 0) { $PercentComplete = [math]::Round(($TotalGenerated / $TotalSizeBytes) * 100, 2) Write-Progress -Activity "Génération fichiers" -Status "$FileCount fichiers | $([math]::Round($TotalGenerated/1GB, 2)) GB / $TotalSizeGB GB" -PercentComplete $PercentComplete } } } Write-Progress -Activity "Génération fichiers" -Completed Write-Host " ✓ $FileCount fichiers générés ($([math]::Round($TotalGenerated/1GB, 2)) GB)" -ForegroundColor Green # ============================================ # RAPPORT FINAL # ============================================ Write-Host "`n[3/3] 📊 Génération du rapport..." -ForegroundColor Green $EndTime = Get-Date $Duration = $EndTime - $StartTime $Report = @{ CheminCible = $TargetPath TailleGeneree = "$([math]::Round($TotalGenerated/1GB, 2)) GB" NombreFichiers = $FileCount NombreDossiers = $AllFolders.Count ProfondeurMax = $MaxDepth Duree = $Duration. ToString("hh\:mm\:ss") DateGeneration = $EndTime.ToString("yyyy-MM-dd HH:mm:ss") TailleMoyenne = "$([math]::Round(($TotalGenerated/$FileCount)/1MB, 2)) MB" } Write-Host "`n╔═══════════════════════════════════════════════════════════╗" -ForegroundColor Green Write-Host "║ ✅ GÉNÉRATION TERMINÉE AVEC SUCCÈS ║" -ForegroundColor Green Write-Host "╚═══════════════════════════════════════════════════════════╝" -ForegroundColor Green $Report. GetEnumerator() | Sort-Object Name | ForEach-Object { Write-Host ("{0,-20} : {1}" -f $_.Key, $_.Value) -ForegroundColor Cyan } # Export rapport JSON $ReportPath = Join-Path $TargetPath "_GenerationReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').json" $Report | ConvertTo-Json | Out-File -FilePath $ReportPath -Encoding UTF8 Write-Host "`n📄 Rapport sauvegardé : $ReportPath" -ForegroundColor Yellow Write-Host "`n✅ Opération terminée`n" -ForegroundColor Green
Créé il y a 1 mois.