Export-DbaLogin, dbatools

After running this script also check for Orphan users once.
<#
This will script out all the login(server principals and user permissions(database principals)
to the below mentioned file in temp folder of C drive. After run this script in respective destination server
also please check orphan users once.
#>
Export-DbaLogin `
-SQLInstance RAMESH\PROD `
-OutFile 'C:\temp\RAMESHPROD_LOGIN_USER_Permissions_08082022.txt' `
-Verbose
The below piece of code will automatically generate the time stamp with server database details.
 $servername = "myServerNameHere"
 $dbName = "dbNameHere"
 $date = Get-Date
 Export-DbaLogin `
 -SqlInstance $servername `
 -Database $dbName `
 -Verbose `
 -FilePath "C:\AzureBackpack\$($servername)_$($dbName)_$($date.ToString("yyyyMMdd_HHmmss")).txt"
The below command will script out individual login level permissions.
 $instance="MAPS"
 $date = Get-Date -Format "yyyy-MM-dd"
 $reqlogins = Get-DbaLogin `
 -SqlInstance $instance `
 -Verbose
 foreach($reqlogin in $reqlogins){
 Export-DbaLogin -SqlInstance $instance -Verbose -FilePath "D:\InstanceBackup\$($reqlogin.Name)_Permissions_$($date).txt" -Login $reqlogin.Name
 }



The below command will split the account name and shows only account name if the account name is "DomainName\AccountName". Split is handled here. Here I found the WindowsLogin accounts who are having db_executor and sp_exec permissions and exported their permissions only and the file will be created with an individual names.
$serverName = "ServerNameHere"
 $db = "DBNameHere"
 $date = Get-Date -Format "yyyy-MM-dd"
 $logins = Get-dbadbUser `
 -SqlInstance $serverName `
 -Database $db `
 -ExcludeSystemUser `
 -Verbose|Where-Object {$_.LoginType -eq "Windowsuser"}
 $exportLogins = Get-DbaDbRoleMember `
 -SqlInstance $serverName `
 -Database $db `
 -Verbose | Where-Object {($_.Login -in ($logins.login))-and($_.Role -in ("db_executor","db_spexec"))}
 foreach($exportLogin in $exportLogins){
 $account = $exportLogin.Login
 $UserName = $account -split '\\'|Select-Object -Last 1
 $UserName
 Export-DbaLogin -SqlInstance $serverName -Login $exportLogin.Login -Database $db `
 -FilePath "C:\AzureBackpack\Logins\$($serverName)_$($db)_$($UserName)_$($date).txt" -Verbose
 }

Comments

Popular posts from this blog

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Pre login Handshake or Connection Timeout Period

Transparent Data Encryption(TDE) with Master Key and Certificate in SQL Server