是否可以在Powershell中使用服务器凭据创建Microsoft SMO SQL连接?

时间:2018-11-09 09:25:26

标签: sql-server powershell

所以我有以下代码,相信可以使用Windows凭据在我的计算机上创建到本地SQL Server的连接。

$ServerObj = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"

是否可以指定我要使用服务器凭据进行连接?

即使用服务器用户名和密码而不是Windows凭据进行连接

3 个答案:

答案 0 :(得分:1)

您可以这样-

$srv = new-Object Microsoft.SqlServer.Management.Smo.Server(SourceServerName);  #New SMO Object
$db = New-Object Microsoft.SqlServer.Management.Smo.Database;   #New Database Connection Object
$db = $srv.Databases.Item(SourceDatabaseName);  #Database Information stored in $db

如果您具有凭据,则可以按如下所示构建连接字符串-

$ConnectionString = server=*serverName*;database=*databaseName*;user id=*userName*;password=*passWord*;  #For SQL Credentials
$Connection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)

$ConnectionString = "server=*serverName*;database=*databaseName*;user id=*domain\username*;password=*passWord*;trusted_connection=true;"   #For Domain credentials
$Connection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)

但是上述方法很容易受到SQL注入的影响。如果您很少/根本不关心安全性,那么可以尝试上述方法。

您还可以查看其他解决方案,特别是PowerShell模块dbatools here。希望这会有所帮助!

答案 1 :(得分:1)

您可以使用以下内容:

$server = new-object Microsoft.SqlServer.Management.Smo.Server(DATA_SOURCE)
$conContext = $server.ConnectionContext
$conContext.LoginSecure = $false
$conContext.Login = LOGIN_NAME
$conContext.Password = LOGIN_PASSWORD
$db = $server.Databases.Item(DATABASE_NAME)

答案 2 :(得分:1)

我一直喜欢这种方法,因此不必在脚本中编写密码。

# Get Credentials
$credential = Get-Credential -username MyAdminAccount -Message "Account credentials"
$username  = $credential.UserName
$password  = $credential.Password
$password.MakeReadOnly()
$creds = New-Object System.Data.SqlClient.SqlCredential($username, $password)

# Create Connection
$SqlConnection.ConnectionString = "Server=$srv; Database=master; Integrated Security=false"
$SqlConnection.Credential = $creds
$SqlConnection.Open()

# SQL Statement 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandTimeout = 0
$SqlCmd.CommandText = 'Select * from yourTable' 
$SqlCmd.Connection = $SqlConnection