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');
Related
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
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
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.
I need a working example on how to assign a fixed server role to a user in Azure SQL database. It seems I can't even access Roles collection:
$DBServerBulkRole = $DBServer.Roles | where {$_.Name -eq 'bulkadmin'};
$DBServerBulkRole.AddMember($DBLoginName);
This generates
The following exception occurred while trying to enumerate the collection: "Operation not supported on version 12.0.600 SqlAzureDatabase."
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-addrolemember-transact-sql
This states: "This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER ROLE instead."
I recommend you basically rewrite a function in powershell to perform the same call but utlizing the alter role command. This should resolve your problem. Azure's implementation of SQL is slightly different and there are certain commands that are not available. Also, as seen in the documentation I believe this is now a deprecated procedure.
-- Syntax for SQL Server (starting with 2012) and Azure SQL Database
ALTER ROLE role_name
{
ADD MEMBER database_principal
| DROP MEMBER database_principal
| WITH NAME = new_name
}
[;]
From:
https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql
Hope this helps!
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')