1

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)

1 Answer 1

4

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.