使用 Powershell 和 kernel32.dll 删除 INI 部分

Deleting INI section using Powershell and kernel32.dll

我在使用 Powershell 删除 INI 文件部分时遇到问题。我在 kernel32.dll 中使用键和值的空字符串调用 WritePrivateProfileString。这是 "before" ini 的示例:

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

现在我调用 WritePrivateProfileString,使用导入的 kernel32.dll(下面的完整代码):

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

我希望这会删除第 2 节,但我得到的是:

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

很明显,空字符串没有被底层代码识别出来。空字符串的定义可能有所不同?任何帮助,将不胜感激。这是定义 $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)

使用[NullString]::Value。资料来源:Possible to pass null from Powershell to a .Net API that expects a string?

示例:

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