I am fairly new to powershell and I am trying to create a script that creates a sql database, creates a user with password, and then adds that user to be the owner of the newly created database. The script will create the database but when I go into the users I do not see 'TestUser' there.
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for backup
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$server = New-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($server, 'TestDB2')
$db.Create()
$login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login($server, 'TestUser')
$login.LoginType = 'SqlLogin'
$login.PasswordExpirationEnabled = $false
$login.Create('PasswordGoesHere')
$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()
