Add User 2

Posted on Posted in SharePoint 2007, STSADM Commands

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"

31 thoughts on “Add User 2

  1. 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.

  2. 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.

  3. 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?

  4. 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.

  5. 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.

  6. 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.

  7. 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?

  8. 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?

  9. 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.

  10. 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!

  11. 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.

  12. 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.

  13. 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.

  14. 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

  15. ==================================
    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

  16. 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…

  17. 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

  18. Hi Gary,
    I am trying to call the: stsadm -o gl-adduser2 -url “http://localhost:1001” -userlogin test\spadministrators -group “Farm Administrators” -username “SP Admins” and I get the error: 1388.
    Any ideas??

    Thanks,
    Dimitris

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA

*