Powershell and SQL Server 2014: Why Does It Hate sa?

Status
Not open for further replies.

StarKruzr

Ars Tribunus Angusticlavius
7,165
Subscriptor
So, I want to write a PS script to do what I thought was something fairly simple:

Code:
Foreach Thing in Things
 {
 Read about Thing from a table in a database
 Do some stuff with the info you read
 Write some results about Thing back to the database
 }

OK. So I have some preliminary code, right:

Code:
$con = New-Object System.Data.SqlClient.SqlConnection("Server=10.110.0.251;Database=BackupDB;User ID=sa;Password=P@ssword1!;connect Timeout=30")
$con.open()

$instance = "TEST001"
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = ("SELECT Retention FROM BackupMetadata WHERE InstanceName = '" + $instance + "'")
$cmd.Connection = $con
$retentiondata = 0
$retentiondata = $cmd.ExecuteReader
Write-Host "Retrieved: $retentiondata"

I'm not entirely sure whether anything after "$retentiondata" will work (heck, I'm not even sure if you can construct the query string that way), but I'm not getting that far.

It will not let me connect as the sa user. Tells me over and over login failed after I try $con.open(). I have confirmed the sa user's password twice.

Stuff in use: Windows Server 2008 R2 and a just-installed instance of SQL Server 2014. Now, when I installed it, it asked me if I wanted to use Windows Authentication only, to which I said, "sure!" Is my problem that answering that question in the positive has just... permanently fucked somehow any attempt to have local SQL logons? The sa account was still *there*, it was just disabled with no password, which I fixed. I confirmed sa has access to everything according to the "security" bit in SSMS -- and it's not saying access denied, but rather login failed.

What am I doing wrong here?
 

StarKruzr

Ars Tribunus Angusticlavius
7,165
Subscriptor
[url=http:/civis/viewtopic.php?p=28696379#p28696379:148s9ang said:
flyingember[/url]":148s9ang]I wouldn't consider using sa for any daily tasks, ever. do you really want THE account password in a script?

and my guess is you answered your own question as to why it's not working
1) That's not the plan for the end of this, I just want to get things working first.
2) Nope?
 

Cookie.Monster

Ars Scholae Palatinae
666
Side note!

Invoke-Sqlcmd2 is a nice drop-in replacement for Invoke-Sqlcmd, and abstracts out the .NET stuff you wrote up there. It takes in a PSCredential for SQL authentication (you should really look at using Windows logins), making it work with the many methods out there for encrypting and decrypting PSCredentials.

It also handles parameterized queries, and can output objects as PSObjects (avoid funky DBNull behavior).

To re-iterate, don't use SA. If you need sysadmin privileges, create yourself a Windows login and grant yourself these privileges.
 

StarKruzr

Ars Tribunus Angusticlavius
7,165
Subscriptor
[url=http:/civis/viewtopic.php?p=28697135#p28697135:3oxo72fo said:
Cookie.Monster[/url]":3oxo72fo]Side note!

Invoke-Sqlcmd2 is a nice drop-in replacement for Invoke-Sqlcmd, and abstracts out the .NET stuff you wrote up there. It takes in a PSCredential for SQL authentication (you should really look at using Windows logins), making it work with the many methods out there for encrypting and decrypting PSCredentials.

It also handles parameterized queries, and can output objects as PSObjects (avoid funky DBNull behavior).

To re-iterate, don't use SA. If you need sysadmin privileges, create yourself a Windows login and grant yourself these privileges.

So, a few things (and thanks for the helpful reply!):

I don't think I can use Windows logins with this for a few reasons, but I'm going to dive into this to see what I can see later tonight.

Really the thing that is frustrating me the most right now is that there doesn't seem to be a way to just tell it "Hello! Please give me the one fucking value I asked for, because I know I am only going to get one value, because the thing I am querying against is a list of unique names, and in this particular case I just need the number in the DB associated with this name! Thanks!" rather than being forced to deal with data table objects every time you query, which I don't know how to handle. A function that returned an int when I ran the query would be blissfully wonderful. Shit, a function that returned a STRING when I ran the query would be wonderful. Is this not possible?
 

Cookie.Monster

Ars Scholae Palatinae
666
Yep, that's where Invoke-Sqlcmd2 comes in. It abstracts out all the .NET stuff. You still need to know how to use PowerShell and write a query, but you don't need to worry about the implementation to execute that query.

So, for example:

Code:
#Download and unblock the file(s).
#Dot source the file(s) as appropriate.
    . "\\Path\To\Invoke-Sqlcmd2"

#Get help for the function
    Get-Help Invoke-Sqlcmd2 -Full
    
#Use the function
    Invoke-Sqlcmd2 -ServerInstance MyServer -As PSObject -Credential $cred -Query "
        SELECT ServerName, VCNumCPU FROM tblServerInfo"  |
        
        #We have the ServerName and VCNumCPU in the pipeline... filter it
        Where-Object {$_.VCNumCPU -gt 8} |

        #Now expand out a single property.
        #In this case, we get ServerName, which is a string
        Select-Object -ExpandProperty ServerName

If you omit the PSObject, you get DataRows back, which generally behave as you would expect. Personally, I prefer PSObjects, where we convert DBNull to Null to allow expected PowerShell comparisons.

This is one of the big draws to PowerShell. As you saw, you could have glued stuff together with a bunch of lines of code... or you can abstract it out into a task-based function (invoke a sql query). I like tasks, they're more like lego blocks, letting you focus on what you actually want to get done, not the underlying implementation details and syntax.

Good luck!
 

StarKruzr

Ars Tribunus Angusticlavius
7,165
Subscriptor
Invoke-Sqlcmd2
Do you have an example for the use of the -Credential parameter? What is $cred?

ETA: Nvm, figured that out. Set up my query and am getting this:


PS H:\ps> .\Data_Reader.ps1
WARNING: Some imported command names include unapproved verbs which might make them less discoverable. Use the Verbose
parameter for more detail or type Get-Verb to see the list of approved verbs.
Invoke-Sqlcmd2 : Exception calling "Fill" with "1" argument(s): "The data types text and varchar are incompatible in th
e equal to operator."
At H:\ps\Data_Reader.ps1:514 char:25
+ $result = Invoke-Sqlcmd2 <<<< -ServerInstance HQ04HQDBA002\ISInternal -Database Corporate_DB_Backup -Credential $myc
reds -query "SELECT Retention FROM BackupMetadata WHERE Instance = 'TEMP001'"
+ CategoryInfo : NotSpecified: :)) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-Sqlcmd2

I have "text" fields in my table but not varchar. What happened here?
 

Cookie.Monster

Ars Scholae Palatinae
666
Yep! Any T-SQL query; execute stored procedures, insert, update, drop, etc., but you can't use GO. If you have a query with GO in it, you can just run each section independently:

Code:
INSERT SOMETHING...
GO
UPDATE SOMETHING...

Would become

Code:
Invoke-Sqlcmd2 -Query "INSERT SOMETHING..."
Invoke-Sqlcmd2 -Query "UPDATE SOMETHING..."

Some queries are pages upon pages long and not worth the effort, in which case you can fall back to sqlcmd, invoke-sqlcmd, SSMS, or other means.

It's my go to T-SQL command now. Chad Miller (a MS SQL MVP back then) wrote it a long while back to address a number of bugs in Microsoft's Invoke-Sqlcmd. A number of folks added functionality like simplified handling for SQL parameters. I write a variety of functions that need to hit SQL; rather than writing that .NET stuff over and over, I just dot source Invoke-Sqlcmd2.

Cheers!
 

Cookie.Monster

Ars Scholae Palatinae
666
If the script needs to be network tolerant and is running locally, keeping it inline or dot sourcing a local copy may be helpful.

For less critical scripts, I dot source from a network share. Consider DFS - I personally keep a number of critical modules in sysvol, where everyone has access, and few can modify.

Here's an example. I want the script to stop if it fails, hence the try/catch:

Code:
#Add dependencies
Try
{
    Import-Module Some-Module-I-Want

    . "\\Path\To\Invoke-SqlCmd2.ps1"
}
Catch
{
    #Usually I would log an error here... here, just throw a terminating error
    throw "Something went wrong"
}

#I'm free to use Invoke-SqlCmd2 at this point
Invoke-Sqlcmd2 -ServerInstance SQL1 -Database DB -Query "SELECT * FROM TABLE"
 
Status
Not open for further replies.