本节书摘来自异步社区出版社《PowerShell V3—SQL Server 2012数据库自动化运维权威指南》一书中的第2章,第2.5节,作者:【加拿大】Donabel Santos,更多章节内容可以访问云栖社区“异步社区”公众号查看。
本方案讲述如何使用PowerShell列出SQL Server可配置和不可配置的实例设置。
2.5.1 如何做…1.通过“Start | Accessories | Windows PowerShell | Windows PowerShell ISE”打开PowerShell ISE。
2.导入SQLPS模块,创建一个新的SMO服务器对象。
#import SQL Server module Import-Module SQLPS –DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName为了浏览在SMO服务器下的成员和方法,在PowerShell V3中使用如下代码片段。
#Explore: get all properties available for a server object #http://msdn.microsoft.com/en-us/library/ms212724.aspx $server | Get-Member | Where MemberType -eq "Property"在PowerShell V2中,你需要稍微修改下语法。
$server | Get-Member | Where {$_.MemberType -eq "Property"} #The Information class lists nonconfigrable instance settings, #like BuildNumber, OSVersion, ProductLevel etc #Also includes settings specified during install $server.Information.Properties | Select Name, Value | Format-Table –AutoSize3.接下来,让我们看看Settings类。
#The Settings lists some instance level configurable settings, #like LoginMode, BackupDirectory etc $server.Settings.Properties | Select Name, Value | Format-Table –AutoSize4.UserOption类列出用户特定选项。
#The UserOptions include options that can be set for user #connections, for example #AnsiPadding, AnsiNulls, NoCount, QuotedIdentifier $server.UserOptions.Properties | Select Name, Value | Format-Table –AutoSize5.Configuration类包含实例的特定设置,类似于你运行sp_configure所看到的。
#The Configuration class contains instance specific settings, #like AgentXPs, clr enabled, xp_cmdshell #You will normally see this when you run #the stored procedure sp_configure $server.Configuration.Properties | Select DisplayName, Description, RunValue, ConfigValue | Format-Table –AutoSize大多数SQL Server设置和配置都可以通过SMO或WMI来展示,可以通过编程方式来获得这些值。
访问配置详细信息的核心是SMO服务器类。这个类展示了SQL Server实例的属性,一些是可配置的,而一些不可配置。
为了创建SMO服务器类,你需要知道你的实例名,并传递给以下变量。
#replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo. Server -ArgumentList $instanceName以下是四个主要的属性,用于存储在本方案中所看到的设置或配置。
查看MSDN关于SMO类的完整文档。
http://msdn.microsoft.com/en-us/library/ms212724.aspx 相关资源:PowerShell连接SQL SERVER数据库进行操作的实现代码