本节书摘来自异步社区出版社《PowerShell V3—SQL Server 2012数据库自动化运维权威指南》一书中的第1章,第1.9节,作者:【加拿大】Donabel Santos,更多章节内容可以访问云栖社区“异步社区”公众号查看。
1.8 创建SQL Server实例对象
大多数在SQL Server中的操作都需要连接到实例。
1.8.1 准备
打开PowerShell控制台、PowerShell ISE或者你喜欢的PowerShell编辑器。
你需要注意你的实例名是什么。如果你有一个默认实例,你可以使用机器名。如果你有一个命名实例,这个格式将会是<机器名><实例名>。
1.8.2 如何做…
如果你使用Windows验证连接到实例,使用你当前的Windows登录,按如下步骤操作。
1.导入SQLPS模块。
#import SQLPS module
Import-Module SQLPS –DisableNameChecking
2.将实例名保存到变量。
#create a variable for your instance name
$instanceName = "KERRIGAN"
3.如果你使用Windows验证,使用你登录的帐号登录到实例。
#create your server instance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server
-ArgumentList $instanceName
如果你使用SQL验证连接,你需要知道用于验证的用户名和密码。在这里,你需要添加以下代码,设置连接为混合模式,并提示用户名和密码。
#set connection to mixed mode
$server.ConnectionContext.set_LoginSecure($false)
#set the login name
#of course we don't want to hardcode credentials here
#so we will prompt the user
#note password is passed as a SecureString type
$credentials = Get-Credential
#remove leading backslash in username
$login = $credentials.UserName -replace("\\", "")
$server.ConnectionContext.set_Login($login)
$server.ConnectionContext.set_SecurePassword($credentials.Password)
#check connection string
$server.ConnectionContext.ConnectionString
Write-Verbose "Connected to $($server.Name)"
Write-Verbose "Logged in as $($server.ConnectionContext.TrueLogin)"
1.8.3 如何实现…
在你用程序访问和操作SQL Server之前,通常需要创建对象的参照。最基本的是服务器。
服务器实例使用Microsoft.SqlServer.Management.Smo.Server类型。默认情况下,到服务器的连接使用信任连接,意思是它使用你登录到服务器时所使用的Windows帐号。因此在参数列表中只需要实例名。
#create your server instance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server-ArgumentList
$instanceName
而如果你需要使用SQL登录,你需要将SMO服务器类的ConnectionContext.LoginSecure属性设置为false。
#set connection to mixed mode
$server.ConnectionContext.set_LoginSecure($false)
你也需要明确设置用户名和密码。最好的方式是提示用户输入凭据。
#prompt
$credentials = Get-Credential
凭据窗口将捕获用户名和密码。如果没有使用域,Get-Credential返回带有前导反斜杠的用户名。在这里,我们想删除这个前导反斜杠。
#remove leading backslash in username
$login = $credentials.UserName -replace("\\","")
一旦获取到登录名,我们将它传给set_Login方法。密码已经是一个SecureString类型,也是set_SecurePassword要求的,因此我们乐意将它传给这个方法。
$server.ConnectionContext.set_Login($login)
$server.ConnectionContext.set_SecurePassword($credentials.Password)
你可能指定用户名,只提示输入密码,也可以这样:
$login="belle"
#prompt
$credentials = Get-Credential -Credential $login
在这个脚本中,你也注意到了,我们使用Write-Verbose替代Write-Host来显示结果。因为我们希望能控制输出而不用总是返回到我们的脚本,我们移除了所有的Write-Host命令。
默认情况下,脚本不会显示任何输出,也就是说,$VerbosePreference特殊变量设置为SilentlyContinue。如果你想在verbose模式运行脚本,你只需要将下面这行内容添加到你的脚本开头。
$VerbosePreference = "Continue"
当完成后,你只需要将该值修改为SilentlyContinue。
$VerbosePreference = "SilentlyContinue"
1.8.4 更多…
导入SMO程序集方法
使用SMO创建SQL Server实例方法