我正在尝试通过 PInvoke 从 Powershell 使用 GetFileSecurity。该调用本身有效,但 System.Runtime.InteropServices.Marshal.GetLastWin32Error 和 GetLastError(我为测试而导入)都返回错误的错误代码。似乎SetLastError = true
在 PInvoke 签名中根本没有任何效果,因为在启动新的 Powershell 实例后第一次运行脚本时,都返回 203(ERROR_ENVVAR_NOT_FOUND),但如果我再次调用相同的脚本,都返回 0 .
作为快速测试,我编写了一个等效的 C 程序,GetLastError 在那里返回预期值 (122 == ERROR_INSUFFICIENT_BUFFER)。
请注意,我通常是 Powershell 和 .NET 的新手,所以请原谅任何明显的失礼。
$signature = @'
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetFileSecurity(
string lpFileName,
int RequestedInformation,
byte [] pSecurityDescriptor,
uint nLength,
out int lpnLengthNeeded
);
[DllImport("Kernel32.dll")]
public static extern uint GetLastError();
'@
$enum = @'
namespace Win32 {
public enum SECURITY_INFORMATION : uint
{
OWNER_SECURITY_INFORMATION = 0x00000001,
GROUP_SECURITY_INFORMATION = 0x00000002,
DACL_SECURITY_INFORMATION = 0x00000004,
SACL_SECURITY_INFORMATION = 0x00000008,
UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
}
}
'@
Add-Type -TypeDefinition $enum
Add-Type -MemberDefinition $signature -Name API -Namespace Win32
$len = 0
$sec = New-Object byte[] 0
$info = new-object Win32.SECURITY_INFORMATION
$info = [Win32.SECURITY_INFORMATION]::OWNER_SECURITY_INFORMATION -bor
[Win32.SECURITY_INFORMATION]::GROUP_SECURITY_INFORMATION -bor
[Win32.SECURITY_INFORMATION]::DACL_SECURITY_INFORMATION
[Win32.API]::GetFileSecurity("c:\temp", $info, $sec, $sec.Length, [ref] $len)
[System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
[Win32.API]::GetLastError()