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.
Related
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');
I log in to SSMS with one set of credentials, no problem. Then I want to access several databases in a script but one of the databases requires different credentials. Is there a way to specify different credentials within the script when accessing a database?
Yes, there is a way.
Try with EXECUTE AS, see the snippet below.
EXECUTE AS LOGIN = 'your login name';
EXECUTE AS USER = 'your user name';
See more on
EXECUTE AS (Transact-SQL)
I'm trying to find a way to do the equivalent of an "execute as user" command from within a SQL connection string. I have a query coming from an external source that I can't modify and a database that already has security setup using execute as user. The only thing I can really modify is the connection string. I've been looking all over and am having trouble finding anything related in my searches.
Can something similar to "execute as user" be done within a connection string?
If yes, how?
Using SQL Server 2016 - SP1
Edit:
Users in a table have a number of roles associated with them. Each unique combination of roles has a user created (that can't login so you can't connect as that user and get access). That user has a schema that applies row level security so based on the user's role they can only see the data they are allowed. Using "execute as user = [auto generated user]" they impersonate the appropriate user with the unique permissions schema and thus only get back the data they are allowed to see. I will make a connection with a user and then need to do the equivalent of the execute as statement, but I can't modify the actual query so it needs to be done in the connection string.
You cannot do this via the connection string since you must already be connected in order to impersonate a user.
A connection string allows a user to connect (i.e., login) to a SQL Instance and therefore cannot be used by users that cannot login. Instead you'll have to connect as a user with login rights and then impersonate the user via EXECUTE AS USER.
I am looking for an easy way to create logins and associated users into SQL Azure.
The thing is that, with Azure, one first needs to create a login in the master database.
Based on that login I need a user to be created in a specific database (DATABASE1)
After that roles need to be assigned:
CREATE LOGIN login1 WITH password='<ProvidePassword>';
CREATE USER login1User FROM LOGIN login1;
EXEC sp_addrolemember 'dbmanager', 'login1User';
EXEC sp_addrolemember 'somerole';
The thing is, since one cannot use the USE command to switch databases, this seems to become quite a tedious task. More so because the number of accounts per database can range from ten to a few hundred, databases and users are being added all the time.
So I need a solution that can be easily reused.
I would like to have a script of some sorts (powershell?) that will read a file (containing username, password and databasename) and then create the appropriate logins, users and rights.....
Icing on the cake would be some sort of job that would regularly check whether there are (new) files present in a certain folder and if so, read those files and create new accounts where needed.
I must admit that I do have TSQL knowledge, basic programming knowledge but no Powershell experience at all. How would you advise that I go about? Is powershell the way to go? Or are there any other mechanisms I could use?
Greetings, Henro
As described here you sure can use Powershell from your desktop machine to connect to SQL Database to manage SQL Database account in similar way you would connect to other SQL Server.
PowerShell scripts can run on an on-premise computer and connect to SQL Database using System Management Objects or Data-tier Applications Framework object.
The very first step in this direction is to get your Powershell commands connecting to SQL Database and you can use this article to get upto here.
After that you just need to use the Powershell script to create users login and searching quickly I found this article and this one promising which includes a few more functionalities along with your objective. You may need to tweak script to make it working with SQL database.
Finally you can search internet to read data form a file (or XML to be better) and feed user info to your SQL Database script. If you have any issue in between step, open specific question and you will be helped.
I am creating an Access project linked to a SQL Server. Instead of using Windows authentication for the SQL Server I want to use an application specific username/password and authenticate users myself using a login form. The reason is that other applications may connect to this database from a context where Windows authentication is not an option (FileMaker Server for instance).
I have found myriad discussions that cover this issue from one angle or another, but none that have actually enabled me to implement a solution. I do not have a lot of VBA or LDAP experience but I know this must be possible.
So, what I want to do is:
Ask the user for a username and password when they open the database.
Use that username and password to authenticate them
against our LDAP server.
Proceed if it passes, fail if it does not.
Can someone sketch out how this works or point me to a resource that describes this?
One way to accomplish this is to create a VBA procedure which loops through all of your linked tables and alters the connection string to embed the username and password from a login form.
You can get the syntax for the existing ODBC linked tables by going to the debug window and typing this:
? CurrentDb().TableDefs("My Table Name").Connect
Which should give you something similar to:
ODBC;DRIVER=SQL Server;SERVER=MYSQLSERVER001;UID=JPARKER;PWD=Pizza123;APP=2007 Microsoft Office system;DATABASE=MyDatabaseName
So your login form would capture the user name and password from the user, then store those as variables and use to build a new connection string. Then iterate through the tabledefs collection updating the connect property. Happens pretty quickly.