SMO server based connection vs. “classic” — Take two.

It was pointed out to me today by the lead dev at work, that I can remove two more lines from the script.

I have to confess that I am rather new to object-oriented types of programming. PowerShell is really my first venture into the OO world via .NET. DataSet/Adapters are still a bit of a stumbling block for me, but I think I’ve made it over a hurdle today. I must thank my developer at work again for his help and information.

Since in my scripts, I’m returning only one dataset for a query, I don’t need to name the table, and can go to it directly as such..

# Read table from db.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
$SrvName = "YourServerName"
$DBName = "master"

$SrvObj = New-Object ("Microsoft.SqlServer.Management.SMO.Server") $SrvName
$DBObj = $SrvObj.Databases[$DBName]

$Query = "SELECT name FROM dbo.sysdatabases"

# Execute $Query and return a dataset
$Results = $DBObj.ExecuteWithResults($Query)

foreach ($Row IN $Results.Tables[0].Rows)
{ Write-Host $Row.Name }

Isn’t that nice? :)

Explore posts in the same categories: Powershell, SMO, SQL

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: