替换或添加.INI文件内容

时间:2016-12-14 14:55:06

标签: powershell

需要跨多台计算机更新.INI文件并更改内容。我有以下脚本:

(Get-Content SDA_Apps.ini) | Foreach-Object {
$_ -replace "UserName=.+", "UserName=Test" `
   -replace "UserEmail=.+", "UserEmail=test@test.com" `
   -replace "UserNo=.+", "UserNo=1234" `
   -replace "UserKey=.+", "UserKey=^%&$*$778-" `
   -replace "KEM=.+", "KEM=H10" 
} | Set-Content SDA_Apps.ini

有时这些文字行不存在,我需要添加文本而不是替换它。

这是我尝试这样做 - 没有成功:

function setConfig( $file, $key1, $value1, $key2, $value2 ) {
    $content = Get-Content $file
    if ( $content -match "^$key\s*=" ) {
        $content $_ -replace "^$key1\s*=.*", "$key1=$value1" -replace "^$key2\s*=.*", "$key2=$value2"|
        Set-Content $file     
    } else {
        Add-Content $file "$key1 = $value1"
        Add-Content $file "$key2 = $value2"
    }
}

setConfig "SDA_Apps.ini" "UserName" "Test"  "UserEmail" "test@test.com"

1 个答案:

答案 0 :(得分:1)

我重写了你的功能并重命名它以反映它的实际功能Set-OrAddIniValue

function Set-OrAddIniValue
{
    Param(
        [string]$FilePath,
        [hashtable]$keyValueList
    )

    $content = Get-Content $FilePath

    $keyValueList.GetEnumerator() | ForEach-Object {
        if ($content -match "^$($_.Key)=")
        {
            $content= $content -replace "^$($_.Key)=(.*)", "$($_.Key)=$($_.Value)"
        }
        else
        {
            $content += "$($_.Key)=$($_.Value)"
        }
    }

    $content | Set-Content $FilePath
}

此功能的好处是您可以将键值列表作为哈希表传递给它。它只读取一次ini文件,更新内容并将其保存回来。这是一个用法示例:

Set-OrAddIniValue -FilePath "c:\yourinipath.ini"  -keyValueList @{
    UserName = "myName"
    UserEmail = "myEmail"
    UserNewField = "SeemsToWork"
}