2016-12-14 215 views
1

需要跨多臺計算機更新.INI文件並更改內容。我有以下的腳本作品:替換或添加.INI文件內容

(Get-Content SDA_Apps.ini) | Foreach-Object { 
$_ -replace "UserName=.+", "UserName=Test" ` 
    -replace "UserEmail=.+", "[email protected]" ` 
    -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" "[email protected]" 

回答

1

我改寫了你的函數,並給它改名以反映它actualy確實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" 
} 
+1

感謝Martin表示完美。 – Ankh2054