Hi guys,
Now, I’m currently using Powershell to write to a database regularly, and like most, I can’t be storing my passwords in scripts! Now, I use DPAPI to encrypt my password which I use to connect to MSOnline in my scripts, and I’m trying to apply this to an SQL Connection string, however this is not working, I get this error:
Exception calling "Open" with "0" argument(s): "Login failed for user '[USERNAME]'."
At line:20 char:9
-
$SQLConnection.Open() -
~~~~~~~~~~~~~~~~~~~~~- CategoryInfo : NotSpecified: (
, MethodInvocationException - FullyQualifiedErrorId : SqlException
- CategoryInfo : NotSpecified: (
I have also tried using $SQLUsername and $SQLPassword in the connection string, but still nothing!
I’m assuming this is because im trying to use a powershell method in an SQL string… Is there any way I can make this work??
Many Thanks.
$DPAPI = "C:\DPAPI"
If (!(Test-Path $DPAPI)) {
md $DPAPI
Write-host "Creating DPAPI Directory..." -foregroundcolor yellow
}
else {
Write-Host "DPAPI Directory Already Exists." -foregroundcolor green
}
$SQLUserName = "[DATABASE USERNAME]"
$key = "$DPAPI\SQLkey.txt"
if (!(Test-Path -Path $key)) {
$SQLDPAPICreds = Get-Credential -Message "Azure SQL Database Credentials" -UserName $SQLUserName
$SQLDPAPICreds.Password | ConvertFrom-SecureString | Out-File $key
}
Get-Content $Key
$SQLPassword = Get-Content $key | ConvertTo-SecureString
$SQLCred =New-object -TypeName System.Management.Automation.PSCredential -ArgumentList $SQLUserName, $SQLPassword
$SQLConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$SQLConnection.ConnectionString = "Server=[SERVER NAME];Database=[DB NAME];User ID=$SQLCred.Username; Password=$SQLCred.Password;"
$SQLConnection.Open()