Fonction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | function Write-Ini { [ CmdletBinding ()] param ( [ Parameter ( Mandatory = $true )] [string] $FilePath , [ Parameter ( Mandatory = $true )] [string] $Section , [ Parameter ( Mandatory = $true )] [string] $Key , [ Parameter ( Mandatory = $true )] [string] $Value ) # Vérifier si le fichier existe if ( -Not ( Test-Path $FilePath )) { Write-Host "Erreur : Le fichier $FilePath n'existe pas." return } $iniContent = Get-Content -Path $FilePath $sectionFound = $false $keyFound = $false $newContent = @() # Parcourir chaque ligne du fichier INI foreach ( $line in $iniContent ) { if ( $line -eq "[$Section]" ) { $sectionFound = $true } if ( $sectionFound -and $line -match "^$Key=" ) { $line = "$Key=$Value" $keyFound = $true } $newContent += $line } # Ajouter la section et la clé-value si elles n'existent pas if ( -not $sectionFound ) { $newContent += "[$Section]" } if ( -not $keyFound ) { $newContent += "$Key=$Value" } # Écrire le contenu mis à jour dans le fichier Set-Content -Path $FilePath -Value $newContent } # Exemple d'utilisation Write-Ini -FilePath "C:\path\to\your.ini" -Section "Settings" -Key "username" -Value "JohnDoe" |
Fonction compatible Powershell 1 (Winpe)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | function Write-Ini ( $FilePath , $Section , $Key , $Value ) { # Vérifier si le fichier existe if ( -not ( Test-Path $FilePath )) { Write-Host "Erreur : Le fichier $FilePath n'existe pas." return } $iniContent = Get-Content $FilePath $sectionFound = $false $keyFound = $false $newContent = @() # Parcourir chaque ligne du fichier INI foreach ( $line in $iniContent ) { if ( $line -eq "[$Section]" ) { $sectionFound = $true } if ( $sectionFound -and $line -match "^$Key=" ) { $line = "$Key=$Value" $keyFound = $true } $newContent += $line } # Ajouter la clé-value si elle n'existe pas if ( -not $keyFound ) { if ( -not $sectionFound ) { $newContent += "[$Section]" } $newContent += "$Key=$Value" } # Écrire le contenu mis à jour dans le fichier Set-Content -Path $FilePath -Value $newContent } # Exemple d'utilisation Write-Ini -FilePath "C:\temp\file.ini" -Section "Settings" -Key "username" -Value "JohnDoe" |
0 Comments