Last active
March 13, 2023 15:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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