title: Create a SQL Server User using Powershell
body: <p>I've written a powershell script that creates a new sql server database and login, and then sets the database owner to the newly created user. This is successful. However, I get a login failed exception when attempting to login within the same script. If I use SQL Server Management Studio the login works.</p>
  
  <p>Here's the script:</p>
  
  <pre><code>$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"
  </code></pre>
  
  <p>I've tried adding a <code>Start-Sleep</code> (up to 5mins) to no avail, and I've tried <code>Restart-Service mssqlserver -Force</code>, also to no avail. </p>
  
  <p>Any ideas?</p>