Monday, March 6, 2017

I want to conqure SQL using Powershell...so far I'm getting my butt kicked

For the past year I have been trying to find easy ways to get information from SQL.  In particular, I want to get a list of all instances and databases on all of our SQL servers.  This information will be valuable for those of us in the Infrastructure arena.  So far, I have used the following code to get specific bits and pieces of SQL information:

Listing computers with SQL in local network
This code will list all computers that have SQL installed, including SQL Server Management Studio, on a local subnet:

<#



.SYNOPSIS

Get-ISqlAvailableSQLServers

.DESCRIPTION

Get available SQL Server instances

.EXAMPLE

.\Get-ISqlAvailableSQLServers

.INPUTS



.OUTPUTS

Server names

.NOTES



.LINK



#>
 

begin {

[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")


}
process {

try {

Write-Verbose "Enumerating servers...please wait"

# Enumerate servers

$smoApp = [Microsoft.SqlServer.Management.Smo.SmoApplication]

$enumServers = $smoApp::EnumAvailableSqlServers($false) | Select Name

Write-Host -ForegroundColor green $enumServers.name

Write-Output $enumServers


}
catch [Exception] {

Write-Error $Error[0]

$err = $_.Exception

while ( $err.InnerException ) {

$err = $err.InnerException

Write-line $err.Message


}

}

}

This is a nice code snippet but it doesn't search any further then your local subnet.

Listing all databases on a SQL server
During my search for code that will list all SQL servers, instances, and databases, I found this snippet of code that lists all databases on a SQL server, including the database name, the status, the recovery model, and the compatibility level:

Add-Type -AssemblyName "Microsoft.SqlServer.Smo,Version=11.0.0.0,Culture=neutral,PublicKeyToken=89845dcd8080cc91"

$srv = New-Object Microsoft.SqlServer.Management.Smo.Server “<SQL server name>”

$srv.Databases | select name,status,recoverymodel,compatibilitylevel

This code produces the following output:


 
 
Again, this is very handy code but I have to manually enter the SQL server name to get the information.
 
 
So, this is a far as I have gotten.  My search for the "whole enchilada" continues.

No comments:

Post a Comment