从 Powershell 调用非托管代码 - 处理枚举类型

问题描述 投票:0回答:1

我正在使用 Powershell 从 userenv.dll 调用组策略更新 API(请参阅此处 此处)。这很好用:

$sig =@'
[DllImport("userenv.dll", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RefreshPolicy([MarshalAs(UnmanagedType.Bool)] bool bMachine);
'@
$mytype = add-type -memberdefinition $sig -Name "Win32RefreshGP" -Namespace Win32Functions -PassThru
$mytype::RefreshPolicy($false) # Refresh the user policy

当我导入此类型时,如下所示:

$sigEx =@'
public enum RefreshPolicyOption:uint
{ 
    RP_FORCE = 1,
    RP_SYNC = 2 
}

[DllImport("userenv.dll", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RefreshPolicyEx([MarshalAs(UnmanagedType.Bool)] bool bMachine, RefreshPolicyOption dwOptions = 0);
'@
$mytypeEx = add-type -memberdefinition $sigEx -Name "Win32RefreshGP" -Namespace Win32Functions -PassThru
$mytypeEx::RefreshPolicyEx($false) # Refresh the user policy

以下提出呼吁

$mytypeEx::RefreshPolicyEx($false)

Method invocation failed because [System.Object[]] does not contain a method named 'RefreshPolicyEx'.
At line:1 char:1
+ $mytypeEx::RefreshPolicyEx($false) # Refresh the user policy
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

这似乎是因为尝试在类型定义中使用枚举。有什么想法吗?

我尝试过使用单/双引号。我希望类型定义能够像在 C# 中一样工作。

powershell pinvoke
1个回答
0
投票

问题相当简单,当您使用

-PassThru
时,
Add-Type
将为 C# 内联代码中定义的每个类型输出一个类型实例,在这种情况下
$mytypeEx
将有 2 种类型,因此您得到的错误:

PS /> $mytypeEx

   Namespace: Win32Functions

Access        Modifiers           Name
------        ---------           ----
public        class               Win32RefreshGP : object
public        enum                Win32RefreshGP.RefreshPolicyOption : uint

PS /> $mytypeEx.Count
2

解决方案就像索引

Win32RefreshGP
类型一样简单,然后调用其静态成员:

PS /> $mytypeEx[0]::RefreshPolicyEx($false)

或者您可以删除

-PassThru
,然后从类型本身调用静态成员:

PS /> [Win32Functions.Win32RefreshGP]::RefreshPolicyEx($false)
© www.soinside.com 2019 - 2024. All rights reserved.