Powershell – Retrieve SQL Server Info for all my Servers

Learning Powershell – Day 2

My aim in implementing powershell has always been for monitoring purposes.. to easily be able to retrieve a snapshot of my SQL Server estate by simply running a powershell script. Regardless of the SQL Query running in the powershell script, i wanted to achieve the following things:

  • Read a list of SQL Servers from a file
      • For each entry – Make a connection to SQL Server in Powershell (Discussed in more detail here)
      • For each entry – Run the same T-SQL query
      • For each entry – Do some error trapping around connectivity
      • Collate all the results into 1 table
      • Do some formatting
      • Either print the results to the screen or to a file

    The idea was that if i can incorporate these things into 1 script, then it would be easily transferrable to other more complex scripts. In essence, the aim was to create a template for future use.

    For the database connection, i am using smo and the get-credential cmdlet. I am feeding in a preset sql authenticated username and asking the user to provide the password.
    Patch_levels.ps1
    #Declare and set the file variables $filelocation = "\\shared\home\Mohsin.AliPatel0 - DBA8 - Powershell\Powershell_training" $instanceNameList = Get-Content "$filelocation\ServerList.txt" $inputfile = "$filelocation\ServerProperties.sql" $outputfile = "$filelocation\serveroutput.log" #Reset the arrays $results = @() $resultsout = @() #Preset the default database for invoke-sqlcmd $db = "master" #Supply the username and password (SQL Authentication popup) $server = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server $server.ConnectionContext.LoginSecure=$false; $credential = Get-Credential -credential "DBA_Monitor" $userName = $credential.UserName -replace("\\","") $pass = $credential.GetNetworkCredential().password #Run the query for each server foreach($instanceName in $instanceNameList) { $results += Invoke-Sqlcmd -Database $db -ServerInstance $instanceName -U $username -P $pass -InputFile $inputfile #handle login failures trap { "Oops! $_ on server $instancename"; continue } } # print results $results | format-table -property Host, Instance, Version, Edition, 'Patch Level', SP, ServerType -Autosize #Uncomment below to send to file #$resultsout = $results | format-table -property Server, Instance, Edition, Version, SP -Autosize #$resultsout | out-file -filepath $outputfile

    The script uses the following serverproperties.sql file
    SELECT 
            SERVERPROPERTY('MachineName') as Host,
            SERVERPROPERTY('InstanceName') as Instance,
            SUBSTRING(@@VERSION, 1,25) as Version,
            SERVERPROPERTY('Edition') as Edition, /*shows 32 bit or 64 bit*/
            SERVERPROPERTY('ProductVersion') AS 'Patch Level', 
            SERVERPROPERTY('ProductLevel') as SP, /* RTM or SP1 etc*/
            Case SERVERPROPERTY('IsClustered') 
            when 1     then 'CLUSTERED' else
                      'STANDALONE' end as ServerType

When run using the Windows Powershell ISE, the following happens:

1. Prompted for password

image

As the screenshot below shows, the login is disabled in 1 of the servers in the list, which creates an error trap. The other 2 servers work successfully and return the data

image

The formatting is done via the format-table cmdlet. I specify the columns to ensure a table is built, but also to make it easier to add and remove columns from the end result.

Although commented out in the script, there is an option to send the results to file. This is done via the out-file cmdlet.

Advertisements

Connecting to SQL Server through Powershell

Being a newbie to powershell, ive been researching and testing different connection options for powershell scripts. Ive come across the following ways:

      • Invoke-sqlcmd Windows Authentication
      • Invoke-Sqlcmd SQL Authentication
      • Invoke-Sqlcmd with Authentication Prompt
      • SQLConnection.connectionstring property (.NET)
      • SMO Connection with Authentication prompt
      • SMO Connection with hardcoded details

Invoke-sqlcmd Windows Authentication

Takes current windows connection details to try to do pass through authentication onto SQL Server

#Uses windows Authentication to traverse through instance list and return db count $filelocation = "\\shared\home\Mohsin.AliPatel0 - DBA8 - Powershell\Powershell_training" $instanceNameList = Get-Content "$filelocation\ServerList.txt" $results = @() foreach($instanceName in $instanceNameList) { $results += Invoke-Sqlcmd ` -Query "select SERVERPROPERTY('ServerName') as Server, count(*) as 'DB Count' from sys.databases" ` -ServerInstance $instanceName } # print results $results | Format-Table -autosize

Invoke-Sqlcmd SQL Authentication

#Uses sql Authentication to traverse through instance list and return db count $filelocation = "\\shared\home\Mohsin.AliPatel0 - DBA8 - Powershell\Powershell_training" $instanceNameList = Get-Content "$filelocation\ServerList.txt" $results = @() foreach($instanceName in $instanceNameList) { $results += Invoke-Sqlcmd ` -Query "select SERVERPROPERTY('ServerName') as Server, count(*) as 'DB Count' from sys.databases" ` -ServerInstance $instanceName ` -U "MyUsername" -P "password" } # print results $results | Format-Table -autosize

Invoke-Sqlcmd with Authentication prompt

This option uses the get-credentials cmdlet to bring up a prompt whereby connection details can be entered. These are then passed through to a connection method.

$filelocation = "\\shared\home\Mohsin.AliPatel0 - DBA8 - Powershell\Powershell_training" $instanceNameList = Get-Content "$filelocation\ServerList.txt" #resets the variable $results = @() # login using SQL authentication, which means we supply the username # and password $server.ConnectionContext.LoginSecure=$false; $credential = Get-Credential #the backslash is regular expression to remove \ (prompt will give it as default for domain) $userName = $credential.UserName -replace("\\","") #getnetworkcredential gives the passport unencrypted $pass = $credential.GetNetworkCredential().password $db = "master" foreach($instanceName in $instanceNameList) { $results += Invoke-Sqlcmd -U $userName -P $pass -Database $db -ServerInstance $instancename ` -Query "select SERVERPROPERTY('ServerName') as Server, count(*) as 'DB Count' from sys.databases" } # print results $results | format-table -Autosize

When the script is run, a popup is presented to the user:

image

If the credentials are correct, then the script returns how many databases are in each server in the instancelist.

SQLConnection.ConnectionString Property

The connection string and the query are fed into a SQLClient.SQLDataAdapter and the output formatted

foreach ($svr in get-content "\\shared\home\Mohsin.AliPatel0 - DBA8 - Powershell\Powershell_training\serverlist.txt") { $con = "server=$svr;database=master;Integrated Security=sspi" $cmd = "SELECT SERVERPROPERTY('ServerName') AS Instance, SERVERPROPERTY('ProductVersion') AS Version, SERVERPROPERTY('ProductLevel') as SP" $da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con) $dt = new-object System.Data.DataTable $da.fill($dt) | out-null $dt | Format-Table -autosize }

SMO Connection with Authentication Prompt

# load assemblies [Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, ` Version=9.0.242.0, Culture=neutral, ` PublicKeyToken=89845dcd8080cc91") [Reflection.Assembly]::Load("Microsoft.SqlServer.SqlEnum, ` Version=9.0.242.0, Culture=neutral, ` PublicKeyToken=89845dcd8080cc91") [Reflection.Assembly]::Load("Microsoft.SqlServer.SmoEnum, ` Version=9.0.242.0, Culture=neutral, ` PublicKeyToken=89845dcd8080cc91") [Reflection.Assembly]::Load("Microsoft.SqlServer.ConnectionInfo, ` Version=9.0.242.0, Culture=neutral, `PublicKeyToken=89845dcd8080cc91") # connect to SQL Server named instance # use server\instancename $serverName = "Server\INSTANCE" $server = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server -argumentList "$serverName" # login using SQL authentication, which means we supply the username # and password $server.ConnectionContext.LoginSecure=$false; $credential = Get-Credential $userName = $credential.UserName -replace("\\","") $server.ConnectionContext.set_Login($userName) $server.ConnectionContext.set_SecurePassword($credential.Password) # clear the screen cls # list connection string Write-Host "--------------------------------------------------------" Write-Host "Connection String : " Write-Host $server.ConnectionContext.ConnectionString Write-Host "--------------------------------------------------------"