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

安装BetterCredentials模块后Get-Credential导出CliXml报错的解决方案咨询

解决BetterCredentials模块与原生Get-Credential冲突的问题

问题背景

我编写了一段将凭据持久化到CliXml文件的PowerShell脚本:

$pop = New-Object -ComObject wscript.shell
$credfile = "$PSScriptRoot\cred.xml"
If (Test-Path -Path  $credefile ) {
    Remove-Item  $credefile
}

$pop.popup("Credential Screen May not Be on Top, should just need password entered",2,"Credentials",4096)
$user = 'genericuser' #$env:UserName
$creds = Get-Credential -UserName $user -Message "Confirm User/Enter Password"
if ($creds -eq $null)
{
   $pop.popup("Cancel or closed chosen",2,"Terminate",4096)
   Exit
}

$creds | Export-CliXml -Path $credfile -ErrorAction Continue
$creds = Import-CliXml -Path $credfile
$user = $creds.UserName
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($creds.Password))
$pop.popup($password,2,"Password",4096)

[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($pop)
Exit

安装BetterCredentials模块后,运行脚本出现以下错误:

Exception calling "Load" with "1" argument(s): "Element not found"
At C:\Program Files\WindowsPowerShell\Modules\BetterCredentials\4.5\BetterCredentials.psm1:351 char:21
+ ...             $Credential = [CredentialManagement.Store]::Load($UserNam ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : Win32Exception

需要保留该模块,同时解决问题,尝试过设置ErrorAction参数无效,寻求无需卸载模块、修改psm1代码或直接忽略错误的可行方案。

可行解决方案

问题根源是BetterCredentials模块覆盖了原生的Get-Credential cmdlet,导致脚本调用的是模块版本而非系统原生版本,触发了加载凭据存储时的错误。以下是几种可行的绕过方案:

1. 明确调用原生Get-Credential

使用Microsoft.PowerShell.Security模块的限定名调用原生cmdlet,替换脚本中的Get-Credential行:

$creds = Microsoft.PowerShellSecurity\Get-Credential -UserName $user -Message "Confirm User/Enter Password"

PowerShell会自动识别简写的模块名(去掉点号的Microsoft.PowerShellSecurity),确保调用的是系统原生的cmdlet。

2. 临时移除BetterCredentials模块

在脚本最顶部添加代码,临时将模块从当前会话中移除,脚本执行完后可按需重新导入:

# 临时移除模块,确保使用原生Get-Credential
Remove-Module BetterCredentials -Force -ErrorAction SilentlyContinue

# 脚本核心逻辑...

# 若需要恢复模块,可在脚本末尾添加
# Import-Module BetterCredentials -ErrorAction SilentlyContinue

这种方式仅影响当前脚本会话,不会破坏其他场景对BetterCredentials的使用。

3. 使用cmdlet完整路径调用

直接指定原生Get-Credential脚本的完整路径,彻底绕过模块覆盖:

$creds = & "$PSHOME\Modules\Microsoft.PowerShell.Security\Get-Credential.ps1" -UserName $user -Message "Confirm User/Enter Password"

内容的提问来源于stack exchange,提问作者Stan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:43:11