You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 7.1中如何正确引用[Windows.Security.Credentials.PasswordCredential]类型

问题原因

  1. vaultcli.dll 是原生Win32二进制文件,不是.NET托管程序集,Add-Type -Path 仅支持加载.NET程序集或编译C#/VB源码,因此加载时会抛出IL格式错误,该操作本身不符合Add-Type的使用规范。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:36:01