Powershell - SQL Database show users permission - sql-server

I'm writing, because I've been stuck. I'm new in SQL+ Powershell. I have SQL Server with 10 DBs.
I need to check
check if user's accounts exists in SQL (Get-SQLLogin - that's clear)
check what kind of permissions the user has on each database
after AD.2 prints on screen a list of permissions for each database
I've stuck here:
foreach($item in $dt){
$server = $item.server
$user = "domain\$($item.user)"
$database = $item.db
Get-SqlLogin -ServerInstance $server -LoginName $user
}
Thank you so much in advance!
Cheers

Perhaps https://docs.dbatools.io/#Get-DbaUserPermission will do what you need.
There are a few other cmdlets for permissions at https://dbatools.io/commands/#Security

Related

Microsoft.SqlServer.Smo.DatabaseRole.EnumObjectPermissions method doesn't appear to work

I'm trying to use SQL Server SMO in PowerShell to get a list of objects permissioned to a database role but the following code doesn't seem to work:
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$instanceName = 'DEVECPVM010346\DMGBVSQL01'
$SMOserver = New-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $instanceName
$SMOserver.Databases['SomeDatabase'].Roles['WebAppPoolRole'].EnumObjectPermissions()
A bit of searching turns up posts from SQL Server 2005 days stating that EnumObjectPermissions() doesn't work but that MS has said it'd be fixed in SQL Server 2008. Well I'm using SQL Server 2017 and it still doesn't work.
Unless I'm doing something wrong?
I was hoping to avoid having to use T-SQL to get the list of objects permissioned to the db role.
I've even tried the SQL Server PS module (which I guess uses SMO?) and even the following doesn't work:
$db = Get-SqlDatabase -ServerInstance 'DEVECPVM009562\DMGBVSQL01' -Name 'SomeDb' $db.Roles['WebAppPoolRole'].EnumObjectPermissions()
From what I've been able to tell from working with SMO over the years, permissions belong to the securable, not to the grantee. So calling $role.EnumObjectPermissions() will get any explicit permissions for which the role is the explicit securable. For example, if I do this in my database:
create role Blah;
create user BlahUser without login;
grant select on dbo.myTable to Blah;
grant take ownership on role::Blah to BlahUser;
(so that I have permissions where Blah is both the securable and the grantee) and then run this powershell (though any method of working with SMO would be fine)
$db = Get-DbaDatabase -SqlInstance . -Database foobar;
$role = $db.Roles['Blah'];
$role.EnumObjectPermissions();
I get only the permission where Blah is the securable.
That said, all may not be lost! Just messing around, it seems that if you ask for permissions at the database level, you can get what you're looking for.
$db.EnumObjectPermissions('Blah');

How to add an AAD group with datawrite and dataread permissions to an Azure DB through PowerShell

I have an Azure SQL Server with an SQL database. I would like to add an AAD Group with datawrite and dataread permissions to this database through PowerShell.
I have no idea how to do this. Can anyone help?
Adding a user to a role is usually accomplished with SQL Statements. This is how this would be done with SQL.
CREATE USER [group name]
FROM external provider
DEFAULT_SCHEMA dbo
Once the user has been added, you can then add them to a group by issuing the following statements;
ALTER ROLE db_datareader ADD MEMBER [group_name]
ALTER ROLE db_datawriter ADD MEMBER [group_name]
Note, within SSMS, you must be in the context of the database you want to add the user to. Azure SQL does not support USE statements, so ensure you selected the correct database.
To do it through powershell, you would probably want to use the following CmdLet, Add-RoleMember, but I have not used these CmdLets with Azure SQL Server before.
This is one way to add users to a SQL database via Powershell;
$Instance = $ENV:AzureSQLServer + ".database.windows.net"
$Query = "CREATE USER [$ENV:AdUser] FROM EXTERNAL PROVIDER"
$ConnString = "Server=" + $Instance + ";Database=master;Authentication=Active Directory Password;UID=" + $Env:SqlAdminUser + ";Password=" + $Env:SqlAdminPass + ";Trusted_Connection=false;Encrypt=True;Connection Timeout=30;"
Invoke-SQlCmd -ConnectionString $ConnString -Query $Query
We use this script in a PowerShell task in Jenkins to add users to databases. The Statements could be modified to also add the users to the appropriate roles as well.
I assume that you want to set AAD Group as AAD admin for your SQL database.
With this scenario, you can use Set-AzureRmSqlServerActiveDirectoryAdministrator:
Set-AzureRmSqlServerActiveDirectoryAdministrator -ResourceGroupName "ResourceGroup01" -ServerName "Server01" -DisplayName "DBAs" -ObjectId "40b79501-b343-44ed-9ce7-da4c8cc7353b"
Result:
ResourceGroupName ServerName DisplayName ObjectId
----------------- ---------- ----------- --------
ResourceGroup01 Server01 DBAs 40b79501-b343-44ed-9ce7-da4c8cc7353b
NOTE:
You can only set the AAD Group with securtiy enabled.
Please let me know if this helps!
You first have to create an ADD group using e. g. the New-AzureADGroup cmdlet that is part of the AzureAD module.
Then you have to assign the desired role to your desired resource (e. g. the SQL DB Contributor role to your DB Server) using the New-AzureRmRoleAssignment cmdlet.
Further reading: Manage role-based access control with Azure PowerShell

Add user to server role in SQL Server

I am trying to add a user to a SQL Server role using PowerShell.
I have a script which reads the server, user and role information and puts it in a text file. I am able to connect to the server and check for the user availability in that server, however I am not able to add the server role to the user. Please assist with the correct script to add the role. My script is long and not able to put it here. Is there a way I can attach it as a text file?
The Add-UserToRole function takes four parameters Server, Database, User and Role and does a series of error checks.
suppose you have the following files with user information
and use them with the Add-SQLAccountToSQLRole and Add-UserToRole functions to create the users. try this
Powershell result will be as follows
Check Here for more details and complete code
I found a very simple listing here.
This uses a Windows domain user, but there is no reason it shouldn't work for SQL Server users as well. Anyway, here goes:
$sqlSrv = New-Object 'Microsoft.SqlServer.Management.Smo.Server' "SQLServer\Instance"
$login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $sqlSrv, "DOMAIN\username"
$login.LoginType = "WindowsUser"
$login.AddToRole("MyServerRole")
$login.Alter()
If you also need to create the login in the same script (I don't think that's the OP's case), you'll just add $login.Create() before the AddToRole call.

Can we import users to Azure AD from sql server user table

We have .net applications and each have its own user tables (some of them AspNetUsers table). Now we think about using Azure Active Directory as a central place to do authentication&authorization. Is there a way to import users to Azure AD from our existing sql server user tables? I don't seem to find such a way, all I see is something like important from local AD.
Using the AAD Graph API or AAD PowerShell you can programmatically create new Users in your Tenant.
For the AAD Graph API:
POST https://graph.windows.net/myorganization/users
Body:
{
"accountEnabled": true,
"displayName": "Alex Wu",
"mailNickname": "AlexW",
"passwordProfile": {
"password": "Test1234",
"forceChangePasswordNextLogin": true
},
"userPrincipalName": "Alex#a830edad9050849NDA1.onmicrosoft.com"
}
You can find samples to access the AAD Graph API across a number of languages on GitHub.
For AAD PowerShell:
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "Password"
$PasswordProfile.ForceChangePasswordNextLogin = $true
New-AzureADUser -DisplayName "New User" -PasswordProfile $PasswordProfile -UserPrincipalName "NewUser#contoso.com" -AccountEnabled $true -MailNickName "Newuser"
Let me know if this helps.
If you haven't done this already, The query results in SQL can be saved to a CSV. Then use PowerShell to import into Azure. The caveat being you would need an AAD account that can do the import portion. Since PowerShell modules for Azure AD are finicky, it seems, you should update your PowerShell by doing the following.
PS C:\> Install-Module -Name AzureADPreview -RequiredVersion 2.0.2.5 -Verbose -Force
Go to this page to get the latest version info. (Downloading from this site did not work for me, however, running the above script did.
https://www.powershellgallery.com/packages/AzureADPreview/2.0.0.17
Once updated, use the following script to import the file.
$Credential = Get-Credential
Connect-AzureRmAccount -Credential $Credential -Tenant "xxxx-xxxx-xxxx-xxxx" -ServicePrincipal
Account: AzureUser#contosso.onmicrosoft.com
Environment: AzureCloud #usually the region your AAD is located, such as CentralUS.
Subscription: yyyy-yyyy-yyyy-yyyy
Tenant: xxxx-xxxx-xxxx-xxxx
$SecureStringPassword = ConvertTo-SecureString -String "ComplexPasswordString" -AsPlainText -Force
$Users = Import-Csv 'C:\Path to CSV file\SQL_USER_FILE.csv'
$Users | ForEach-Object {
New-AzureRmADUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -Password $SecureStringPassword -MailNickname $_.MailNickName -Verbose
}
And if that doesn't work due to login, the more simplified version will work, but will require you to login with your AAD account.
Connect-AzureRMAccount
$SecureStringPassword = ConvertTo-SecureString -String "ComplexPasswordString" -AsPlainText -Force
$Users = Import-Csv 'C:\Path to CSV file\SQL_USER_FILE.csv'
$Users | ForEach-Object {
New-AzureRmADUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -Password $SecureStringPassword -MailNickname $_.MailNickName -Verbose
}
I User -Verbose to give me a running status of the import. Without it, the execution is silent. Oh, it took about 15 minutes to do 1500 users on a gigabit connection. Tp give you an idea how long it takes.
The particulars to automating login can be found here.
https://learn.microsoft.com/en-us/powershell/module/azurerm.profile/connect-azurermaccount?view=azurermps-6.12.0
Caveat
The CSV must have the required fields shown above. So you might need to do a little finagling to get them to match. Just know that the only real important field is going to be the -UserPrincipalName = user#contosso.onmicrosoft.com.

How do I create a new Login using SQL Server PowerShell Provider and/or SMO?

I have a PowerShell script which creates a new SQL Server database. This is going to be a content database for a SharePoint 2010 implementation.
Once created I need to set the DBO to be my SharePoint farm account and I need to assign permissions to some other service accounts.
Does anyone have an idea of how to do this using SMO and the PowerShell Provider for SQL Server?
Setting the db owner is simply enough:
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db = get-item .
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.SetOwner('sa')
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.alter()
#These two steps aren't necessary, but if you want to see the change
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.Refresh()
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.Owner
Assigning permissions is little tricky and of course there are multiple ways to assign a permissions. It would help if you described what permissions you want to assign (database, object, built-in role, server-level, schema, etc.). Here's how you create a database user and assign object permissions:
$user = new-object ('Microsoft.SqlServer.Management.Smo.User') 'MyDatabase', 'MyUser'
$user.Login = 'MyUser'
$user.DefaultSchema = 'dbo'
$user.Create()
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase\tables> $tbl = get-childitem | where {$_.name -eq 'mytable'}
$tbl.Grant('SELECT','myUser')

Resources