4

A little stuck on how I use a secure string within a Powershell command to run a remote SQL Query.

The following command run's fine in a powershell, as this is running under my own account - it also returns results when providing the values for username and password.

 "SELECT COUNT(E.intEmployeeID) AS Count FROM Employees E WITH(NOLOCK)" -       ServerInstance "SERVERA\INSTANCEA" -Database "DATABASEA" -u USER1 -p SomePassword

I want to automate/schedule this script and as I don't want the password in clear txt in my script, I was looking at ways of making this a secure/encrypted string. So I have created an encrypted password using the below. The problem is I'm not sure how to pass this password back into my Command..

This creates the encrypted string and stores in a file. This will be a file secured somewhere remotely.

$File = "C:\password.txt"
[Byte[]] $Key = (1..16)
$Password = "SomePassword" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $Key | Out-File $File

This then will read the encrypted file and store in secure string... But how do I get my Invoke SQL command to use this password.

$File = "C:\Cred.txt"
[Byte[]] $Key = (1..16)
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key

The value for $Password is System.Security.SecureString, if I use this variable in the original command, the command fails with 'Login Failed for User'

The account being used to perform the SQL query is a SQL Authenticated account, not a Domain account..

Any advice would be Welcome Thanks.

Boardman411
  • 521
  • 2
  • 7
  • 16

2 Answers2

6

Create a Credential object:

$cred = new-object -typeName System.Management.Automation.PSCredential -ArgumentList $user, $pass

Then, convert password to plain text:

[string]$pass = $cred.GetNetworkCredential().Password
invoke-sqlcmd -UserName $user -Password $pass -Query 'select @@servername'

Ivoke-SqlCmd can only use plain text passwords.

1

It is possible to use a secure string without storing the plain text in a variable. Here is an example.

$Server = Read-Host "Server"
$Database = Read-Host "Database"
$Username = Read-Host "User"
$Password = Read-Host "password for user $Username on $Server" -AsSecureString

Invoke-Sqlcmd -Database $Database -ServerInstance $Server -Verbose -Username $Username -Password (New-Object PSCredential "userDummy", $Password).GetNetworkCredential().Password -Query "SELECT table_catalog [database], table_schema [schema], table_name name, table_type type FROM INFORMATION_SCHEMA.TABLES GO"
pr0gg3r
  • 4,254
  • 1
  • 36
  • 27