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? :)