MOSS MVP

I've moved my blog to http://blog.falchionconsulting.com!. Please update your links. This blog is no longer in use--you can find all posts and comments at my new blog; I will no longer be posting to this site and comments have been disabled.

Monday, December 3, 2007

Add User 2

This is one of those commands that I really shouldn't have had to create. All I wanted to do was use stsadm to add an AD group to a site collection. Unfortunately the built-in adduser command requires email address and display name. The display name wasn't a huge deal but requiring an email just messed me up. So I created my own adduser command which allowed the email to be optional so that AD groups could be added via stsadm: gl-adduser2. I grabbed most of the code from my addsiteadmin command which I'd previously created and just pulled out the pieces that I didn't need (note that I didn't recreate the adduser command completely (I didn't implement the siteadmin parameter) - if you are adding a user then either mine or the built-in should work fine but I'd recommend just using mine when adding an AD group):

   1: public override int Run(string command, StringDictionary keyValues, out string output)
   2: {
   3:  output = string.Empty;
   4:  
   5:  InitParameters(keyValues);
   6:  
   7:  if (Params["role"].UserTypedIn && Params["group"].UserTypedIn)
   8:   throw new SPException(SPResource.GetString("ExclusiveArgs", new object[] { "role, group" }));
   9:  
  10:  string url = Params["url"].Value.TrimEnd('/');
  11:  string login = Params["userlogin"].Value;
  12:  string email = Params["useremail"].Value;
  13:  string username = Params["username"].Value;
  14:  
  15:  using (SPSite site = new SPSite(url))
  16:  using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
  17:  {
  18:   
  19:   login = Utilities.TryGetNT4StyleAccountName(login, web.Site.WebApplication);
  20:   // First lets see if our user already exists.
  21:   SPUser user = null;
  22:   try
  23:   {
  24:    user = web.AllUsers[login];
  25:   }
  26:   catch (SPException) { }
  27:  
  28:   if (user == null)
  29:   {
  30:    web.SiteUsers.Add(login, email, username, string.Empty);
  31:    user = web.AllUsers[login];
  32:   }
  33:  
  34:   if (Params["role"].UserTypedIn)
  35:   {
  36:    SPRoleDefinition roleDefinition = null;
  37:    try
  38:    {
  39:     roleDefinition = web.RoleDefinitions[Params["role"].Value];
  40:    }
  41:    catch (ArgumentException) {}
  42:  
  43:    if (roleDefinition == null)
  44:     throw new SPException("The specified role does not exist.");
  45:  
  46:    SPRoleDefinitionBindingCollection roleDefinitionBindings = new SPRoleDefinitionBindingCollection();
  47:    roleDefinitionBindings.Add(roleDefinition);
  48:    SPRoleAssignment roleAssignment = new SPRoleAssignment(user);
  49:    roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindings);
  50:    web.RoleAssignments.Add(roleAssignment);
  51:   }
  52:   else if (Params["group"].UserTypedIn)
  53:   {
  54:    SPGroup group = null;
  55:    try
  56:    {
  57:     group = web.SiteGroups[Params["group"].Value];
  58:    }
  59:    catch (ArgumentException) {}
  60:  
  61:    if (group == null)
  62:     throw new SPException("The specified group does not exist.");
  63:  
  64:    group.AddUser(user);
  65:   }
  66:  }
  67:  
  68:  return 1;
  69: }

The syntax of the command can be seen below:

C:\>stsadm -help gl-adduser2

stsadm -o gl-adduser2

Adds a user to a site (allows for useremail and username to be optional).

Parameters:
        -url <web url>
        -userlogin <DOMAIN\user>
        [-useremail <someone@example.com>]
        [-username <display name>]
        [-role <role name> / -group <group name>]
Here's an example of how to add the built in "nt authority\authenticated users" group to a site:
stsadm -o gl-adduser2 -url "http://intranet" -userlogin "nt authority\authenticated users" -group "Viewers"

30 comments:

David Tappan said...

Could this command be updated so you could also use it to set permissions on a list or library? I can't find any stsadm command to do this.

Gary Lapointe said...

I have two new commands that I will be documenting soon - you can download an early version of the commands now (gl-exportlistsecurtiy and gl-importlistsecurity). The import command just takes in an xml file which is generated by the export command but it would be easy to manually create an xml file to pass into it. Note that the current published version is still a work in progress and I have some unpublished updates for it but I'm not able to release it yet as there are other, more significant changes that I'm not ready to go live yet.

David Tappan said...

Thanks, I'm glad I asked! I'm going to try to use gl-importlistsecurity in its current version to do some permissioning of lists. Can you tell me about any issues I might encounter and if there are workarounds?

Gary Lapointe said...

Um - Unfortunately I can't remember what I've changed - I suppose I could do a diff on the files - I'm real close to pushing out the latest build - probably tuesday night.

David Tappan said...

That's fine, I'll wait. Will it be done and released at that point do you think?

Gary Lapointe said...

David - I just pushed the latest build out - note that all of my commands are now prefixed with "gl-".

Pepijn said...

Hello Gary,

Is it also possible to write this but then for removing a user or group?

I am having the problem that the MySites are accessible to "nt authority\authenticated users" which I want to remove for all the MySites.

Gary Lapointe said...

Pepijn - did you try the built-in stsadm deletegroup command?:

C:\>stsadm -help deletegroup

stsadm.exe -o deletegroup
-url <url>
-name <group name>

Marshal Nagpal said...

Hello,
I want to add members(users) of a particular AD group into sharepoint group. Is there any such command avlbl?

Gary Lapointe said...

So you want something that iterates the members of an AD group and adds the members to a sharepoint group? If so, then no - there's nothing available that I'm aware of that does that.

Marshal Nagpal said...

Yes, your understanding is correct. Good news, I have created one by extending stsadm. I will post on blog very soon!

Ryan said...

Hey Gary,

This set of tools seems to be extremely useful, however, I am unable to get them, well at least the gl-addusers2 to work. I downloaded the STSADM extensions(MOSS - WSP only) and installed it...correctly, I think...The "Lapointe.SharePoint.STSADM.Commands" Shows up in the GAC, and STSADM shows these commands in the list...but I keep getting "Missing operation name or the operation is invalid" Or the entire STSADM commands will dump on the screen. I am trying to do exactly like you did in your example since a user deleted that group from their site...

The command I'm using is:

stsadm -o gl-addusers2 -url http://source/departments/CI -userlogin nt authority\authenticated users -group Visitors

but it just does the STSADM commands dump on me. I even tried the:

stsadm -help gl-adduers2

To see if I get the same screen you did, but I don't. Just another STSADM commands dump

Any thoughts? Do I need to install it again? What's the best way of installing these tools?

Gary Lapointe said...

Looks like you're using "gl-addusers2" but the command is "gl-adduser2" (no "s" before the 2).

Ryan said...

It was that easy!! Thanks!!

Eric Silver said...

I am trying to add an existing users from my domain. I have multiple extended web site and multiple site collection.

The default adduser always recreates a new user and does not seem to allow me to have an existing users able to be involved in multiple site collection.

I am using this command and it does not work.

stsadm -o gl-adduser2 -url "http://sample.aztecsystemsweb.com" -userlogin aztecweb\esilver -group "Project Tracking Owners"
When it runs I get a Cannot complete this action.

Where can i find the error info?

Gary Lapointe said...

Eric - sorry but I'm not sure I'm following what your issue is. Are you able to add the user via the browser? I've never not been able to add a user to multiple site collections.

Anonymous said...

Hi,

Is there a way to add users to Visitor/Members/Owners groups by auto populating site group names? What I mean that Visitor group is usuall names "site name Visitors" and when you have large farm it is difficult to get site name at a time. Thanks!

Gary Lapointe said...

Use powershell to get the webs you want and then call my stsadm command and build the group name dynamically.

k said...

Can you use the add user command to add an AD security group? I'm trying to do this but the security group does not have a login, password or email.

k said...

Is it possible to use the add user command to add an AD security group? I'm having difficulty as the group does not have a login, password or email.
Thanks.

Gary Lapointe said...

You just use the NT domain name of the group - so if your domain is "company" and the group is "My Group" then add as:
-userlogin "company\my group"
A password isn't necessary for this command.

Anne said...

Is there a way to addusers in bulk to a Sharepoint group?

I have a list of AD account names, and I would like to have that list of accounts imported to a Sharepoint group.

Thanks!

Roger

Gary Lapointe said...

PowerShell would be the way to go there - you could use PS and the OM directly or use PS and my stsadm command - either will do the trick.

roberto.labarca said...

stsadm -o gl-adduser2 -url "http://localhost:11112" -userlogin %spadmin -group "Farm Administrators" -username spadmin

error in .net

Gary Lapointe said...

Not sure what you mean by error in .net but your variable is wrong - should be %spadmin% (unless you're not trying to use a variable in which case get rid of the % and add the domain)

roberto.labarca said...

==================================
error

Mon 09/21/2009 15:18:46.67: Creating the My Sites web application

Method not found: 'Void Microsoft.SharePoint.Administration.SPWebApplication.Pro
visionGlobally()'.

===================================
code
stsadm -o gl-createwebapp -url http://virtual2003:11112/ -directory "c:\MOSS\Webs\MySites" -sethostheader -ownerlogin "%DOMAIN%\spadmin" -owneremail "spadmin@local" -description "SharePoint My Sites (11112)" -apidname "SharePoint_MySites_AppPool" -apidtype configurableid -apidlogin "%DOMAIN%\spadmin" -apidpwd "ok" -databasename "SharePoint_MySites" -donotcreatesite -timezone 12

Gary Lapointe said...

Not sure why you're posting an issue with gl-createwebapp under gl-adduser2 - anyways, you need SP2 to get rid of this error.

john.thompson said...

Gary Please Help,
This is John T in Portland.
I need to interate through about 900 site collections and delete all users from a MOSS 2007 implementation and re-add them (they are all actually AD Groups).
I am using some of the code from your AddUser2.CS.
When the code hits this line:

SecurityIdentifier identifier = (SecurityIdentifier)new NTAccount(input).Translate(typeof(SecurityIdentifier));

I always get the following error:


System.Security.Principal.IdentityNotMappedException was caught
Message="Some or all identity references could not be translated."
Source="mscorlib"
StackTrace:
at System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess)
at System.Security.Principal.NTAccount.Translate(Type targetType)
at POP.OnePort.PropertyAgreements.FixUsers.FixUsersTryGetNT4StyleAccountName(String input, SPWebApplication webApp) in E:\VSProjects\POPSVN\PropertyAgreements\FixUsers\FixUsers.cs:line 428

The code seems fine and I have been pulling my hair out for some time to no avail.
Note: when I run your STSADM command "gl-adduser2" the user is added fine...

Anonymous said...

Hi Guys,

Great Post, I need help on running the code.

Mr Lapointe, please advise how I could run this code, I am kind of new to scripting.

Look forward to your response

Aj

Gary Lapointe said...

Go to the downloads page and download the WSP package appropriate to your environment. Then follow the install instructions for the applicable WSP.