使用 powershell 在本地保存 SqlCredential 文件 - SQL 连接
Locally save SqlCredential file with powershell - SQL connection
我想使用 凭据文件通过 powershell 连接到 SQL 数据库。
为了创建我的凭证文件,我简单地使用了:
$Credential = Get-Credential
$Credential | Export-CliXml -Path "mypath\sql.cred"
然后我运行:
$ServerInstance = 'myserverinstance.net'
$Database = 'myDB'
$cred = Import-CliXml -Path "mypath\sql.cred"
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=$ServerInstance; Database=$Database;"
$conn.Credential = $cred
$conn.Open()
我收到以下错误:
Exception setting "Credential": "Cannot convert the
"System.Management.Automation.PSCredential" value of type
"System.Management.Automation.PSCredential" to type
"System.Data.SqlClient.SqlCredential"."
如何创建 Sql 凭据文件(我可以将其保存在本地计算机上)以便我的凭据可以工作?
System.Data.SqlClient.SqlConnection.Credential
不直接取 System.Management.Automation.PSCredential
。您需要根据 PSCredential 的值创建一个 SqlCredential 对象。
$cred.Password.MakeReadOnly()
$conn.Credential = [System.Data.SqlClient.SqlCredential]::new($cred.UserName, $cred.Password)
我想使用 凭据文件通过 powershell 连接到 SQL 数据库。
为了创建我的凭证文件,我简单地使用了:
$Credential = Get-Credential
$Credential | Export-CliXml -Path "mypath\sql.cred"
然后我运行:
$ServerInstance = 'myserverinstance.net'
$Database = 'myDB'
$cred = Import-CliXml -Path "mypath\sql.cred"
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=$ServerInstance; Database=$Database;"
$conn.Credential = $cred
$conn.Open()
我收到以下错误:
Exception setting "Credential": "Cannot convert the "System.Management.Automation.PSCredential" value of type "System.Management.Automation.PSCredential" to type "System.Data.SqlClient.SqlCredential"."
如何创建 Sql 凭据文件(我可以将其保存在本地计算机上)以便我的凭据可以工作?
System.Data.SqlClient.SqlConnection.Credential
不直接取 System.Management.Automation.PSCredential
。您需要根据 PSCredential 的值创建一个 SqlCredential 对象。
$cred.Password.MakeReadOnly()
$conn.Credential = [System.Data.SqlClient.SqlCredential]::new($cred.UserName, $cred.Password)