## =====================================================================
## Title : Get-MSSQL-DB-UsingSMO
## Description : Show all databases using SMO for a given server instance
## Author : Idera
## Date : 1/28/2008
## Input : -serverInstance <server\instance>
## -verbose
## -debug
## Output : Database IDs and Names
## Usage : PS> .\Get-MSSQL-DB-UsingSMO -serverInstance MyServer -verbose -debug
## Notes : Adapted from Jakob Bindslet script
## Tag : SQL Server, SMO, List databases
## Change log :
## 4/1/2009 - Added input prompts and write-verbose statements
## 4/1/2009 - Revised SMO Assemblies
## =====================================================================
param
(
[string]$serverInstance = "$(Read-Host 'Server Instance' [e.g. (local)])",
[switch]$verbose = $true,
[switch]$debug = $false
)
function main()
{
if ($verbose) {$VerbosePreference = "Continue"}
if ($debug) {$DebugPreference = "Continue"}
Write-Verbose "Show all databases using SMO for a given server instance..."
Get-MSSQL-DB-UsingSMO $serverInstance
}
function Get-MSSQL-DB-UsingSMO($ServerInstance)
{
#Load SMO assemblies
[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.Management.Common" );
[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.SmoEnum" );
[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.Smo" );
[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.SmoExtended " );
$smoServer = new-object( 'Microsoft.SqlServer.Management.Smo.Server' ) ($serverInstance)
foreach ($database in $smoServer.databases)
{
$dbID = $database.ID
$dbName = $database.Name
Write-Output "$dbID : $dbName"
}
}
main
本脚本是通过SMO方式获取显示指定SQLServer实例上的所有数据库。脚本加载的依旧是.net程序集,通过操作新生成的.net对象来进行数据库读取的。没有新的PowerShell原生Cmdlets学习。