Skip to content

Instantly share code, notes, and snippets.

@jatubio
Last active March 13, 2023 15:33
Show Gist options
  • Save jatubio/428420b2aeca6a954bcc to your computer and use it in GitHub Desktop.
Save jatubio/428420b2aeca6a954bcc to your computer and use it in GitHub Desktop.
PowerShell. Ini Files. Replacing a value in a key inside a section sample 1
# Ini files
# Replacing a value in a key inside a section sample
#
# http://stackoverflow.com/questions/29688299/powershell-and-regex-how-to-replace-a-ini-name-value-pair-inside-a-named-sectio/29688435#29688435
#
$Path="c:\temp\test.ini"
@"
# This line have a white line after and before
[Sky]
Size=Big
Color=White
[Home]
Color=Black
# Last line
"@ | Set-content $Path
$Section="Sky"
$Name="Color"
$Value="Blue"
function Set-INIKey{
param(
[string]$path,
[string]$section,
[string]$key,
[string]$value
)
$edits = (Get-Content $path) -join "`r`n" -split '\s(?=\[.+?\])' | ForEach-Object{
If($_ -match "\[$section\]"){
$_ -replace "($key=)\w+", "`$1$value"
} Else {
$_
}
}
-join $edits | Set-Content $path
}
Set-INIKey $Path "Sky" "Color" "Blue"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment