How to add users from person or group field in a sharepoint list to sharepoint group

Hi,
How to add users(single or multiple) from person or group field in a sharepoint list to sharepoint group programmatically?
Any suggestions would be appreciated.
Thank you,
AA.

Hello,
Use SPGroup.AddUser() method to add user in group. I have just written sample code in notepad so it is not tested:
SPSecurity.RunWithElevatedPrivileges(delegate()
using(SPSite Site = new SPSite(SPContext.Current.Site.Url))
Using(SPWeb Web = Site.OpenWeb())
SPList list = web.Lists["ListName"];
SPQuery query=new SPQuery ();
query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>Test</Value></Eq></Where>";
SPListItemCollection items = list.GetItems(query);
if(items.Count > 0)
foreach(SPListItem item in items)
//Get USers from person or group column
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
SPGroup spGroup = spSite.RootWeb.Groups[groupName];//group name
if (users.Count != 0)
bool isUserInGroup = false;
foreach (SPFieldUserValue user in users)
foreach (SPUser item in spGroup.Users)
string itemUserName = item.LoginName;
string UserName = user.User.LoginName;
if (itemUserName == UserName)
isUserInGroup = true;
break;
if (!isUserInGroup)
spGroup.AddUser(user.User);
The above code will query list item and then get users from "Users" column. Now it will check whetehr user is already in group not, if not then add user in group.
http://rajanijilla.blogspot.sg/2012/09/add-users-to-group-programmatically.html
Hope it could help
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help

Similar Messages

  • How to add user from domain A to a group in domain B

    How would you acheive adding a user from domain A to a group that is in domain B via powershell without the Quest cmdlets? I've been trying to figure this out for about a week now. Please let me know if the scripting guy has seen this issue before.
    LittleTech

    Hello jrv,
    Here's what i was trying to do. The two domains im working with have a trust between them.
    1. Create a user in External.Domain.Com
    2. Add the user in External.Domain.Com to GroupOne in ExternalDomain2.Domain.com
    3. The only knowledge that ExternalDomain2.Domain.Com would have about the account in External.Domain.Com is whatever is in the Global Catalog. Here is what im trying, but it isn't working.
    #Connecting to domain PSDrive
    New-PSDrive
    -Name
    ExternalDomain
    -PSProvider
    ActiveDirectory
    -Root
    -Server
    DC01.Domain.com
    cd
    ExternalDomain:
    #Create user
    #Add to ExternalDomain Groups
    $UserDN=Get-ADUser-LDAPFilter"(sAMAccountName=$UserID)"
    #Connecting to domain2 PSDrive 
    cd
    AD:
    $GroupDN="CN=Wireless
    Device Users,OU=Wireless,OU=Systems and Technology,DC=External,DC=Domain2,DC=Com"
    Add-ADGroupMember-Identity$GroupDN-Members(Get-ADObject-Identity$UserDN.DistinguishedName
    -Server"DC01.Domain.com:3268")
    Connecting via port 3268 allows me to talk to the global catalog instead of LDAP.
    I receive the following message: A Referral was returned from the server
    I know that if i connect using [ADSI] i am able to specify that the connection follows referrals, the AD cmdlets seem to not have that function. The Quest AD cmdlets do... I just dont want to have to use third party cmdlets to do what the AD cmdlets should
    be able to do in the first place.
    THanks,
    LittleTech

  • How to add users to group which is present in another AD domain?

    Hi,
    Using JNDI how to add user as a member of group which is present in another AD domain?
    For example: In AD forest test.com their are two domain a.test.com and b.test.com. Group is present in a.test.com and I want to add user present in b.test.com as a member of the group.
    Any pointer around this would be great help.

    See the below link to get an idea on group types.
    http://technet.microsoft.com/en-us/library/cc755692(v=ws.10).aspx
    If the group is a universal group, you can just add members similar to local group even if user and group are in different domains. That is by setting the member attribute of the group.

  • How to add a search help for a field in Screen Personas?

       I just started learning to use a Screen Personas, and I want to know how to add a search help for a field.
       I found a property in the help document named "IsLookupSupported". Is it the key?  But I saw it was gray in the field I created, and its value is "false". I could not change it.

    Hi, Tamas,
    I found the reason. The function Z_WEBRFC_READ_DATA_SH had a string concatenation error.
    CONCATENATE '{"results":[{"key": "shlpname", "value": "' l_shlp '"},"key": "fieldname", "value": "' l_field '"}]}' INTO htmldoc-line.
    The correct code is like:
    CONCATENATE '{"results":[{"key": "shlpname", "value": "' l_shlp '"},{"key": "fieldname", "value": "' l_field '"}]}' INTO htmldoc-line.
    Another question is, I can't get any words in Chinese from WebRFC. It returns error when I try it. How can I configure it?
    Xin

  • How to prevent users from creating new folders in share folder directory?

    Hello guys
    I'd like to know How to prevent users from creating new folders in share folder directory but still keep their power of creating new folders in their personal 'my folder'?
    I tried changing the 'manage privilage ---- create folder' to deny certain user accounts, but by doing so, it also stops the user from creating new folders in their 'my folder', which is not good..
    I also tried going into these share folders and tried different access types such as 'change/delete', 'read', 'traverse folder' etc, but none of it work ideally. The 'change/delete' access still allows them to create new folders, 'read' access prevents creating new folders but also take away their power of saving reports..
    Any thoughts on how to take away their ability to ONLY create new folders in share folder areas without affecting their other privileges?
    Please advise
    Thank you

    Easy, on the shared folders root folder only give them 'read' or 'traverse folder' but on the the folder inside the shared folders root folder give them 'change/delete'. That means they can change anything inside those folders but not create any folders at the shared folders root level.

  • How to block user create personal view and select ALL VIEW?

    How to block user create personal view and select ALL VIEW?

    Hello,
    >create personal view
    To restrict creating personal view, you need to modify your existing permission level or create new one. Login with admin account to your site and open role.aspx page (http://siteurl/_layouts/role.aspx). Then click on existing permission or add new permission
    level-->and move to "Personal Permissions" section-->uncheck "Manage Personal Views - Create, change, and delete personal views of lists" option. Later you can assign this permission to all users, whom you don't want
    to allow to create.
    >and select ALL VIEW
    Since SP does not supports view level permission directly so you have to use custom solution or use below designer solution to restrict user to open any view.
    http://www.codeproject.com/Articles/433486/How-to-set-view-level-permissions-out-of-the-box-i
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Org Tech Admin can add user from other org?

    We are currently on a trial run with CIAC, and I am testing User Management with a Organization Tech Admin account (OTA).
    To my suprise, when adding user and select "existing user", I can see every account currently on Cloud Portal, and even successfully add user from other organization to my orgnization.
    Is there anyway so that OTA can see only the users in their own organization?

    I've been able to remove the admin role from a site administrator with an OTA.
    I know there are issues when you log with an user then logout and relog with another user, CIAC considers that you are still the previous user (I've encountered the issue several times in portlets in the nsapi requests). I don't know if/how those issues are related, but I'd say that logout/login issue were an user has the same rights than the previous users should be fixed.
    Changing OTA rights will not change that particular issue.
    For the moment, what we've done is create our own servlet for requests to the sql DB, and our own roles for most services.
    Let's see what v4 has in store for us.

  • Add users from several Active Directories in SAP BPC

    Hello everybody,
    Does anybody know if you can add users from several Active Directories in SAP BPC??
    In affirmative case, how can you add several Active Directories in SAP BPC??
    Thank you very much.
    Best regards,
    Fernando

    Hi,
    We almost have same issue to add users from several Active Directories.
    BPC server is in Domain A. We perform to add users from Domain B. Our trusted relation between AD is Domain B approve Domain A (unidirectional).
    We cannot get one user which is able to browse both AD. So we install BPC with a user which has rights to browse Domain A  and we use another user in COM+ component (OsoftUSerManage) which has right to browse Domain B.
    But it is not working : we encounter an issue (access denied) in web administration by adding users from Domain B.
    Any idea ?
    Env. : BPC 5.1 SP6

  • How to Block user from Sending IM or Hide Presence of there user who is not in his department

    Hi All,
    How to Block user from Sending IM or Hide Presence of there user who is not in his department.
    Thank you

    Hi Jp,
    Method 1:
    You can use the Enhanced Privacy Mode in Lync 2013
    <section class="ocpSection">
    Enable Privacy Mode
    By default, everyone except Blocked Contacts can see your presence status. To modify the privacy settings, you can do the following:
    In the Lync main window, click the Options button.
    In the Lync - Options dialog box, click Status, and then do one of the following:
    Click I want everyone to be able to see my presence regardless of system settings (override default settings).
    Click I want the system administrator to decide - currently everyone can see my presence but this could change in the future.
    </section>
    About Enhanced Privacy Mode
    If your organization has enabled Enhanced Privacy Mode in Lync, you can choose whether to limit visibility of your presence information to only those people you’ve added to your Contacts list. You do that by selecting one of the following on the
    Options->Status window:
    I want everyone to be able to see my presence
    I only want people in my Contacts list to see my presence
    Method 2:
    Using Privacy Relationship, you can block a particular user by adding him to blocked contacts
    Anil Kumar (MCITP)
    Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

  • How to restrict users from printing documents and exporting to local file

    Hi SAP gurus,
    I have two questions.
    1. How can I restrict users from printing a document? i.e. billdoc? I would like to know if I could block it though authorization. If yes, what auth obj to use?
    2. How to restrict certain users from exporting to local file? the System> List>Save-->Local File. I have tried restricting it using auth object S_GUI but it seems it is only applicable to older versions of SAP. im on ecc6.
    Thank you in advance.

    Hi,
    Check this:
    Create your own gui status and attach it to the list in the event START-OF-SELECTION.
    In the menu painter extra -> adjust template.
    Make it a list status and you will see all the standard list options appear including list->download
    Deactivate the ones you don't want. 
    If you just want to prevent users from downloading the list you can achieve this with authorization object S_GUI, activity 61. Menu option will still be there though.
    Please note that if you remove authorisation for S_GUI activity 61 then all downloads will not be possible. 
    If you just want to disable downloads only for a particular report, you can try this test program:
    Code:
    REPORT ztest. 
      DATA: PROGNAME LIKE SY-CPROG value 'Z_CHECK_AUTH', 
            FORMNAME LIKE SY-XFORM value 'F_CHECK_AUTH'.
    START-OF-SELECTION. 
        CALL FUNCTION 'SET_DOWNLOAD_AUTHORITY' 
             EXPORTING 
                  FORM    = FORMNAME 
                  PROG    = PROGNAME 
             EXCEPTIONS 
                  OTHERS  = 1.
      WRITE: / 'TEST'.
    You also need this:
    Code:
    PROGRAM z_check_auth.
    FORM f_check_auth USING pe_result TYPE i. 
      pe_result = 5. 
    ENDFORM.
    Also have a look at the exit SGRPDL00.
    Hope this helps you.
    Rgds,
    Raghu

  • How to add user defined tab in the Header level of T-Code O4NM?

    How to add user defined tab in the Header level of  T-Code O4NM?
    I tried with BADI but I cant able to find any BADI for it and also searched for screen exit too..

    Can you check the user exits,
    OIJNOM_N and OIJTKT_N
    Cheers,
    Balaji

  • How to redirect user from login page to "Set Challenge question" page

    How to redirect user from login page to "Set Challenge question" page (NOT custom page) after 3 un successful password attempts?
    Meaning when user types wrong password 3 times they will be redirected to set Challenge question page. If user answers the challenge question then password reset page should be appeared other wise (after remaining 3 un successeful challenge question answers) account should be locked out.
    thanks for your help.

    hi sandeep
    Thanks for your answer. Let me ellaborate more on the requirement here.
    - Password Policy and Lost Password management are set up in the identity system
    - Configure login tries allowed= 5. Verify accout is lock out after 5 unsucessful login.
    This is what need to achieve.
    1) If a user attempts to login 3(not 5) times using an incorrect login credential he/she should be redirected to set challenge question (security question) page.
    2) Then if the user attempts (remaining) 2 times incorrect challenge answer then his/her account should be locked out.
    3) If he/she answers the challenge answer correctly then he/she should be redirected to password reset page.
    Is this possible?

  • How to add users to OSM using UserAdmin.xsd

    Hi,
    Can you please explain me how to add users to OSM using UserAdmin.xsd i.e xml import/export tool. I need the steps how to do that..
    Thanks in Advance,
    Menaka

    Hi Razvi444,
    You need to use submit data to web service in Submit button rule,where you can use above web service.
    Refer http://office.microsoft.com/en-in/infopath-help/submit-form-data-to-a-web-service-HA010107048.aspx more details
    Thanks

  • YouTube - How to add videos from youtube on jsf-adf

    YouTube - How to add videos from youtube on jsf-adf.
    when i using iframe i can't send data from beans.

    you can use a <f:verbatim> tag in your page and in it just write the HTML code for embedding a video.
    and can i send data from beans class in html components?
    i wrote this
    <af:iterator id="i2" var="row"
    value="#{MyBean.src_items}"
    varStatus="st">
    <af:showDetail disclosed="false" id="sd1"
    styleClass="AFStretchWidth"
    disclosedText="#{row}">
    <f:verbatim>
    <iframe id="ifv" src="#{row}"/>
    </f:verbatim>
    </af:showDetail>
    </af:iterator>
    but that were not worked .
    Edited by: Vakhushti on May 9, 2011 12:40 PM

  • SharePoint 2010 Central Admin to add users from AD from specific Department

    Dear All,
    I am working on SharePoint Foundation 2010. I have to add users from specific department to a particular site collection.
    Please let me know if there is a way to import users from Active Directory based on the 'Department' filed in
    SPCA.
    Thanks.

    Is that okay if I share the PowerShell code? Do you have access to Active Directory and can you query information?
    Refer this Link
    Code
    # set site collection owner for all sites...
    # 1-2012
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    # $AccountList is an array of Windows Identities in the format of $AccountList = @("DOMAIN\USERID" , "DOMAIN\USERID2")
    $accountList = @(Get-ADUser -Filter {(Department -like '*Ur Needs*')})
    #$AccountList = @("LAB\Jack", "Lab\tom", "Lab\dick", "lab\harry")
    #this gets an array of objects representing the sites at the IIS level:
    $IISSites = Get-SPWebApplication
    Foreach($oneIISSite in $IISSites)
    #using .Sites, we can get a list of the site collections
    foreach ($SharepointSiteCollection in $oneIISSite.Sites)
    write-host $SharepointSiteCollection.url -ForegroundColor Cyan
    $spweb = Get-SPWeb $SharepointSiteCollection.url
    #now we have the website, so lets look at each account in our array
    foreach ($Account in $AccountList.samaccountname)
    #lets see if the user already exists
    Write-host "Looking to see if User " $account " is a member on " $SharepointSiteCollection.url -foregroundcolor Blue
    $user = Get-SPUSER -identity $Account -web $SharepointSiteCollection.url -ErrorAction SilentlyContinue #This will throw an error if the user does not exist
    if ($user -eq $null)
    #if the user did NOT exist, then we will add them here.
    $SPWeb.ALLUsers.ADD($Account, "", "", "Added by AdminScript")
    $user = Get-SPUSER -identity $Account -web $SharepointSiteCollection.url
    Write-host "Added user $Account to URL $SPWeb.URL" -Foregroundcolor Magenta
    else
    Write-host "user $Account was already in URL " $SPWeb.URL -Foregroundcolor DarkGreen
    if ($user.IsSiteAdmin -ne $true)
    $user.IsSiteAdmin = $true
    $user.Update()
    Write-host "$account has been made an admin on $SPWeb.URL" -Foregroundcolor Magenta
    else
    Write-host "$account was already an admin on $SPWeb.URL" -Foregroundcolor DarkGreen
    $SharePointSiteCollection.Dispose()
    Note:
    First uncomment the second $accountlist add the user manually to test
    If you have AD module installed in your SP server you can use
    $accountList = @(Get-ADUser -Filter {(Department -like '*Ur Needs*')})
    Regards Chen V [MCTS SharePoint 2010]

Maybe you are looking for