Skip to content

Instantly share code, notes, and snippets.

@jatubio
Created April 17, 2015 11:16
Show Gist options
  • Save jatubio/90cda6b32c0b19543a74 to your computer and use it in GitHub Desktop.
Save jatubio/90cda6b32c0b19543a74 to your computer and use it in GitHub Desktop.
PowerShell. Ini Files. Replacing a value in a key inside a section sample 3.
# Ini files
# Replacing a value in a key inside a section sample
#
# Calling Windows API function WritePrivateProfileString
# And using some C# code
#
# http://stackoverflow.com/questions/29688299/powershell-and-regex-how-to-replace-a-ini-name-value-pair-inside-a-named-sectio/29688435#29688435
$source = @"
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
public static class IniFile
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WritePrivateProfileString(string lpAppName,
string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern uint GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
uint nSize,
string lpFileName);
public static void WriteValue(string filePath, string section, string key, string value)
{
string fullPath = Path.GetFullPath(filePath);
bool result = WritePrivateProfileString(section, key, value, fullPath);
}
public static string GetValue(string filePath, string section, string key, string defaultValue)
{
string fullPath = Path.GetFullPath(filePath);
StringBuilder sb = new StringBuilder(500);
GetPrivateProfileString(section, key, defaultValue, sb, (uint)sb.Capacity, fullPath);
return sb.ToString();
}
}
"@
Add-Type -TypeDefinition $source
function Set-IniValue {
param (
[string]$path,
[string]$section,
[string]$key,
[string]$value
)
$fullPath = [System.IO.Path]::GetFullPath($path)
[IniFile]::WriteValue($fullPath, $section, $key, $value)
}
$Path="C:\Temp\prueba.ini"
@"
[Sky]
Size=Big
Color=White
[Home]
Color=Black
"@ | Set-content $Path
$Section="Sky"
$Name="Color"
$Value="Blue"
Set-IniValue -Path $Path -Section $Section -Key $Name -Value $Value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment