Fonction

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)

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"

Catégories : Powershell

0 commentaire

Laisser un commentaire

Emplacement de l’avatar

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.