使用Powershell创建SQL Server用户

时间:2013-10-04 10:12:33

标签: sql sql-server powershell

我编写了一个PowerShell脚本,用于创建新的sql server数据库和登录,然后将数据库所有者设置为新创建的用户。这很成功。但是,尝试在同一脚本中登录时,我收到登录失败的异常。如果我使用SQL Server Management Studio,则登录工作正常。

这是脚本:

$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($server, 'TestDB')
$db.Create()

$login = new-object Microsoft.SqlServer.Management.Smo.Login("(local)", 'TestUser')
$login.LoginType = 'SqlLogin'
$login.PasswordPolicyEnforced = $false
$login.PasswordExpirationEnabled = $false
$login.Create('Password1')

$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $server.Databases.Item('TestDB')
$db.SetOwner('TestUser', $TRUE)
$db.Alter()
Invoke-Sqlcmd -ServerInstance localhost -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"

我尝试添加Start-Sleep(最多5分钟)无济于事,我尝试了Restart-Service mssqlserver -Force,也无济于事。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这不是我遇到的问题的答案,只是一个解决方法。该脚本作为自动部署的一部分运行,整个脚本在“NT AUTHORITY \ SYSTEM”用户名下运行,因此为了解决我的登录问题,我只是使用Integrated Security=true

答案 1 :(得分:0)

我认为你的最后一行应该是:

Invoke-Sqlcmd -ServerInstance '(local)' -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"

请注意使用'(本地)而不是'localhost'

答案 2 :(得分:0)

遵循以下代码

$SqlServer = "servar.site.com Or server ip with port"
$SqlDBName = "dbName"
$sqlConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$sqlConnection.ServerInstance=$SqlServer
$sqlConnection.LoginSecure = $false
$sqlConnection.Login = "userid if you have"
$sqlConnection.Password = "password if is needed to connect to sql server"

Add-Type -Path "C:\Program Files\Microsoft SQL 
Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"

$server = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlConnection)

 # get all of the current logins and their types

 $server.Logins |
 Select-Object Name, LoginType, Parent

 # create a new login by prompting for new credentials
$NewLoginCredentials = Get-Credential -Message "Enter credentials for the new login"
$NewLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($server, 
$NewLoginCredentials.UserName)
$NewLogin.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$NewLogin.Create($NewLoginCredentials.Password)

# create a new database user for the newly created login
$NewUser = New-Object 
Microsoft.SqlServer.Management.Smo.User($server.Databases[$SqlDBName], 
$NewLoginCredentials.UserName)
$NewUser.Login = $NewLoginCredentials.UserName
$NewUser.Create()
$NewUser.AddToRole("db_datareader")