Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Import-Module dbatools
Import-Module sqlserver #used for Invoke-SqlCmd to run scripts w/ the "GO" batch separator
$CurrentDate = (Get-Date).ToString("yyyyMMdd_hhmmss")
$Servername = "localhost"
$databases = 'CSV_Set_Of_DB_Names'
#Get permissions for databases
# Export to a sql file in case needed
$permissions = Export-DbaUser -SqlInstance $Servername -Database $databases
if (!($null -eq $permissions)) {
get-content $permissions | out-file ("C:\SQLScripts\Permissions_" + $CurrentDate + ".sql")
#Reset permissions
# May need to use something else here. Maybe a foreach for $permissions and Invoke-SQLCmd because of the USE statements...
# Can still use the generated SQL file to get permissions, though.
foreach ($permission in $permissions) {
$query = get-content($permission).ToString() -Raw
Invoke-SqlCmd -ServerInstance $Servername -Query $query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment