Search code examples
powershellloopsforeachssms-2012

Use an array to add permission to a list of users in ssms


I run several classrooms and lab environments. The students in one of the classes have to log into the interface and connect with my server, which then creates their account in SSMS. Then I have to go in and manually add the permissions they need to do what they need to do for class. When my server "re-syncs" with the other online server, they lose their SSMS permissions. (I'm being purposefully vague, don't focus on why they lose perms. I'm not doing anything wrong).

I can create the list of users and save it to an array. I know the ssms commands I need to run. Where I'm drawing a blank is how do I get my PS1 into the SSMS command. I'm fairly sure I need to do a foreach loop and save it to a .sql file and run that, but my google skills are failing me. Any help would be appreciated! Also my first time posting on this website, so I'm sorry if this looks silly.

$Response = 'y'
$User = $Null
$UserList = @()

#Get a list of users#
Do
{
    $User = Read-Host -Prompt 'Input user name'
    $Response = Read-Host 'Would you like to add any 
additional users? y/n'
    if ($User -ne '') {$UserList += $User}
    }
Until ($Response -eq 'n')

#Loop through the list of users and add to a sql file#
foreach ($User in $UserList) {
    
    }

#The SQL command to add user perms in SQL#
#sqlcmd
#use <db>
#exec sp_addrolemember 'group1','$User'
#exec sp_addrolemember 'group2','$User'
#go

Solution

  • You could do something like the following to create file.sql that you can run with Invoke-SqlCmd or from TSQL.

    $template = { @"
    exec sp_addrolemember 'group1','$user'
    exec sp_addrolemember 'group2','$user'
    "@
    }
    
    'use <db>' | Set-Content file.sql
    $SqlCommands = foreach ($user in $userlist) {
        & $template
    }
    
    $SqlCommands | Add-Content file.sql
    'go' | Add-Content file.sql
    

    Explanation:

    Using a script block ({} surrounding code), you can specify variables that are only evaluated when the script block is called. You can simply call a script block in a child scope using & operator.

    @""@ denotes a here-string.