I want to connect to a SQL database with powershell using a credential file.
To create my credential file, I simply used :
$Credential = Get-Credential
$Credential | Export-CliXml -Path "mypath\sql.cred"
Then I run :
$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()
I got the following error :
Exception setting "Credential": "Cannot convert the "System.Management.Automation.PSCredential" value of type "System.Management.Automation.PSCredential" to type "System.Data.SqlClient.SqlCredential"."
How to create a Sql credential file (that I can save locally on my computer) so that my scrip can work ?
$cred.Password.MakeReadOnly(); $conn.Credential = [System.Data.SqlClient.SqlCredential]::new($cred.UserName, $cred.Password). Also, what iRon said. Importing the clixml will only work if you are using the same windows account that you created it with on the same computer.PSCredentialobjects are literally encrypted with your current username+password, so if you change your password, then you will not be able to import the credentials anymore. These days, a better option is usually through theCredentialManagermodule