PowerShell本地保存SqlCredential文件实现SQL连接问题咨询
错误根因
你遇到的类型转换报错,本质是System.Data.SqlClient.SqlConnection的Credential属性仅支持SqlCredential类型对象,而你通过Import-CliXml导入的是PowerShell原生的PSCredential类型,二者无法直接兼容。
报错原文:Exception setting "Credential": "Cannot convert the "System.Management.Automation.PSCredential" value of type "System.Management.Automation.PSCredential" to type "System.Data.SqlClient.SqlCredential"."
修正后的完整操作流程
1. 生成加密凭据文件
你原有的凭据导出逻辑无需修改,Export-CliXml会自动基于当前Windows用户和当前设备上下文加密凭据,仅本人在当前设备上可解密,安全性符合本地存储要求:
$Credential = Get-Credential $Credential | Export-CliXml -Path "mypath\sql.cred"
2. 连接SQL时增加类型转换
导入PSCredential对象后,只需增加一行类型转换代码,即可适配SqlConnection的要求:
$ServerInstance = 'myserverinstance.net' $Database = 'myDB' # 导入本地保存的PSCredential凭据 $psCred = Import-CliXml -Path "mypath\sql.cred" # 转换为SqlConnection支持的SqlCredential类型 $sqlCred = New-Object System.Data.SqlClient.SqlCredential($psCred.UserName, $psCred.Password) $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Server=$ServerInstance; Database=$Database;" # 赋值转换后的凭据对象 $conn.Credential = $sqlCred $conn.Open()
注意事项
- 生成的凭据文件和当前Windows用户、当前设备绑定,无法拷贝到其他设备或使用其他账号解密
- 如果你使用Windows集成身份验证连接SQL,无需单独存储凭据,直接在连接字符串中添加
Integrated Security=True即可,不需要做上述类型转换
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

