Search code examples
sql-serverpowershellsmo

What is the equivalent of the 'GO' statement when using SMO with Powershell?


This is a snippet from my powershell module which creates a login and user in a database:

# code omitted which sets default db, language, etc.
$login.Create()

$user = New-Object ("Microsoft.SqlServer.Management.Smo.User") $db, $username
$user.Login = $login.Name
$user.Create()

An exception is being thrown on the call to $user.Create() with the following message:

Windows NT user or group '[domain\user]' not found. Check the name again.

However $login.Create() executes without a problem and I can see in SSMS that the login exists.

The only thing that comes to mind why this error is being thrown is if I was doing this through T-SQL I'd write the following:

CREATE USER [domain\user] FROM WINDOWS;
GO
CREATE USER [user] FOR [domain\user];
GO

Question regarding issuing a GO statement after CREATE LOGIN

How is this achieved in PowerShell? Or am I doing this wrong?


Solution

  • I'm not sure what I changed, but the script seems to be working now. I'll post the full script anyway, and maybe someone can tell me. -shrug-

    Function Add-DatabaseUser
    {
    Param(
        [Parameter(Mandatory=$true, HelpMessage="The domain account to create the account for.", Position = 0)]
        [string] $loginname
       ,[Parameter(Mandatory=$true, HelpMessage="The user name for the new account.", Position = 1)]
        [string] $username
       ,[Parameter(HelpMessage="Make this user an database administrator?")]
        [switch] $dbadmin
    )
    
    $srv = Get-Server
    $db = Get-Database
    
    $login = $null;
    $user = $null;
    
    Try
    {
        $login = New-Object ("Microsoft.SqlServer.Management.Smo.Login") $srv, $loginname
        $login.DefaultDatabase = "MyDatabase"
        $login.Language = "British English"
        $login.LoginType = "WindowsUser"
        $login.Create()
    }
    Catch
    {
        $exception = $_.Exception
        while($exception.InnerException -ne $null)
        {
            $exception = $exception.InnerException
        }
    
        Write-Error $exception.Message
    
        return
    }
    
    Try
    {
        $user = New-Object ("Microsoft.SqlServer.Management.Smo.User") $db, $username
        $user.Login = $login.Name
        $user.Create()
    
        if ($administrator)
        {
            $user.AddToRole("db_datareader")
            $user.AddToRole("db_datawriter")
            $user.Alter()
        }
    }
    Catch
    {
        $exception = $_.Exception
        while($exception.InnerException -ne $null)
        {
            $exception = $exception.InnerException
        }
    
        Write-Error $exception.Message
    
        return
    }
    
    Write-Host "User was successfully created."
    return
    }