Search code examples
powershellinikernel32

Deleting INI section using Powershell and kernel32.dll


I am having trouble deleting a INI file section using Powershell. I am calling WritePrivateProfileString in kernel32.dll with empty strings for the key and value. Here's an example of the "before" ini:

[Section1]
Setting1=Value1
[Section2]
Setting2=Value2

Now I call WritePrivateProfileString, using an imported kernel32.dll (full code below):

$Kernel32::WritePrivateProfileString("Section2", "", "", "MyIniFile.ini")

I would expect this to delete Section2, but instead I get this:

[Section1]
Setting1=Value1
[Section2]
Setting2=Value2
=

So apparently the empty strings are not getting recognized as such by the underlying code. Possibly a difference in the definition of an empty string? Any help would be appreciated. Here's the code that defines $Kernel32:

$Signature = @’ 
[DllImport("kernel32.dll")] 
public static extern bool WritePrivateProfileString(
    string lpAppName, 
    string lpKeyName, 
    string lpString, 
    string lpFileName); 
‘@ 

$Kernel32 = Add-Type -MemberDefinition $Signature -Name Win32Utils -Namespace WritePrivateProfileString -Using System.Text -PassThru 
$Kernel32::WritePrivateProfileString($Section, $Key, $Value, $File)

Solution

  • Use [NullString]::Value. Source: Possible to pass null from Powershell to a .Net API that expects a string?

    Example:

    $Kernel32::WritePrivateProfileString("Section2", [NullString]::Value, [NullString]::Value, "MyIniFile.ini")