PoshCode Archive  Artifact [6e0fdecd2c]

Artifact 6e0fdecd2c82e1edb97e14141cb3b1ebef61c6600cb31014c6115f3e3c8d0d48:

  • File Add-SQL-Account-to-Serve.ps1 — part of check-in [0e72990b8e] at 2018-06-10 13:41:32 on branch trunk — ############################################################################################# (user: SQLDBAwithabeard size: 2342)

# encoding: ascii
# api: powershell
# title: Add SQL Account to Serve
# description: #############################################################################################
# version: 0.1
# type: function
# author: SQLDBAwithabeard
# license: CC0
# function: Add-SQLAccountToSQLRole
# x-poshcode-id: 4475
# x-archived: 2014-08-18T21:33:48
# x-published: 2014-09-17T18:45:00
#
# #
# NAME: Add-SQLAccountToSQLRole.ps1
# AUTHOR: Rob Sewell http://sqldbawithabeard.com
# DATE:11/09/2013
# #
# COMMENTS: Load function to create a SQL user and add them to a server role
#
#############################################################################################
#
# NAME: Add-SQLAccountToSQLRole.ps1
# AUTHOR: Rob Sewell http://sqldbawithabeard.com
# DATE:11/09/2013
#
# COMMENTS: Load function to create a sql user and add them to a server role
#
# USAGE: Add-SQLAccountToSQLRole FADE2BLACK Test Password01 dbcreator
#        Add-SQLAccountToSQLRole FADE2BLACK Test Password01 public

Function Add-SQLAccountToSQLRole ([String]$Server, [String] $User, [String]$Password, [String]$Role)
{

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

# Check if Role entered Correctly
$SVRRole = $svr.Roles[$Role]
    if($SVRRole -eq $null)
        {
        Write-Host " $Role is not a valid Role on $Server"
        }

    else
        {
#Check if User already exists
    		if($svr.Logins.Contains($User))
			    {
                $SqlUser = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login $Server, $User
                $LoginName = $SQLUser.Name
                if($Role -notcontains "public")
                    {
                    
                    $SVRRole.AddMember($LoginName)
                    }
                }

            else
                {
                $SqlUser = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login $Server, $User
                $SqlUser.LoginType = 'SqlLogin'
                $SqlUser.PasswordExpirationEnabled = $false
                $SqlUser.Create($Password)
                $LoginName = $SQLUser.Name
                if($Role -notcontains "public")
                    {
                    $SVRRole.AddMember($LoginName)
                    }
                }
        }

}