PowerShell 7.1中如何正确引用[Windows.Security.Credentials.PasswordCredential]类型
问题原因
vaultcli.dll是原生Win32二进制文件,不是.NET托管程序集,Add-Type -Path仅支持加载.NET程序集或编译C#/VB源码,因此加载时会抛出IL格式错误,该操作本身不符合Add-Type的使用规范。Windows.Security.Credentials命名空间下的类型属于Windows Runtime(WinRT)API,PowerShell 5.1基于.NET Framework,原生支持WinRT元数据加载,而PowerShell 7.x基于.NET Core/.NET 5+,加载WinRT类型的逻辑存在差异,因此无法直接调用。
注意:该API为Windows平台专属,仅能在Windows系统下的PowerShell 7中使用,跨平台环境不支持
解决步骤
适配PowerShell 7.2及以上版本(基于.NET 6+)
直接加载对应的WinRT元数据文件即可:
Add-Type -LiteralPath "C:\Windows\System32\WinMetadata\Windows.Security.winmd" -WinMD
适配PowerShell 7.1版本(基于.NET 5)
需要先加载Windows SDK契约包再引用类型:
# 注册NuGet源(如果未注册) if (-not (Get-PackageSource -Name nuget.org -ErrorAction SilentlyContinue)) { Register-PackageSource -Name nuget.org -Location https://www.nuget.org/api/v2/ -ProviderName NuGet -Force } # 安装Windows SDK契约包 Install-Package Microsoft.Windows.SDK.Contracts -ProviderName NuGet -Scope CurrentUser -Force # 加载对应程序集 $sdkRoot = (Get-Package Microsoft.Windows.SDK.Contracts).Source | Split-Path -Parent Add-Type -Path (Join-Path $sdkRoot "lib\net5.0\Windows.Security.dll")
验证可用
加载完成后执行以下命令验证类型是否正常:
# 创建PasswordVault对象测试 $vault = [Windows.Security.Credentials.PasswordVault]::new() $vault.GetType().FullName # 输出为Windows.Security.Credentials.PasswordVault即代表加载成功
内容的提问来源于stack exchange,提问作者GuidoT
相关产品推荐
相关产品推荐

