Unable to remove user from SharePoint Group using PowerShell

I am trying to remove a user from a SharePoint Group using PowerShell.
I can see the user in the Site Collection as part of the SharePoint Group, however, when I attempt to run the script, I get an error message stating "Can not find the user with ID: 10"
Below is the PowerShell script that I am using:
$url = "https://sharepointdev.spfarm.spcorp.com/sites/desitecoll"
$userName = "spfarm\sp2013_svc"
#$userName = "spfarm\spprofileimport";
$site = New-Object Microsoft.SharePoint.SPSite($url)
$web = $site.OpenWeb()
$siteGroups = $web.SiteGroups;
Clear-Host
$mySiteGroups = @();
foreach($group in $siteGroups)
Write-Host $group
$mySiteGroups += $group;
}#foreach
$members = $web.SiteGroups[$mySiteGroups[0]];
$owners = $web.SiteGroups[$mySiteGroups[1]];
$visitors = $web.SiteGroups[$mySiteGroups[2]];
#Remove the user from the specified SharePoint Group
$spUser = Get-SPUser -Identity $userName -Web $url
Write-Host $spUser.ID
Remove-SPUser -Identity $spUser -Web $url -Group $owners
$web.Update();
$web.Dispose();
Write-Host "User " $userName "removed from " $owners
Please advise.

I had to update the code to the following because Get-SPUser was not working properly:
$url = "https://sharepointdev.spfarm.spcorp.com/sites/desitecoll"
$userName = "spfarm\spprofileimport";
$site = New-Object Microsoft.SharePoint.SPSite($url)
$web = $site.OpenWeb()
$siteGroups = $web.Groups;
Clear-Host
$mySiteGroups = @();
foreach($group in $siteGroups)
Write-Host $group
$mySiteGroups += $group;
}#foreach
$members = $web.Groups[$mySiteGroups[0]];
$owners = $web.Groups[$mySiteGroups[1]];
$visitors = $web.Groups[$mySiteGroups[2]];
#Convert the user name to an SPUser account
$spUser = $web.Site.RootWeb.EnsureUser($userName);
Write-Host $spUser.ID
Remove-SPUser -Identity $spUser -Web $url -Group $owners
$web.Update();
$web.Dispose();
Write-Host "User " $userName "removed from " $owners
Was I not using Get-SPUser correctly?

Similar Messages

  • Remove users from Sharepoint site security group

    I have to close a share point 2007 site for all users for an update. I don't have access to CA. the easiest approach is to remove the users from security group and add them back when the site modification is done. All users all under "NT/Aunthenticated
    users" and they are in Members group. I'm just wondering will it cause any issues when adding them back or it can be done in 1 click. Do i need any tweaks from CA side to add them back?
    Any response is appreciated.
     Thanks!

    Once you add the users back to the site, it should work as expected.
    >>Do i need any tweaks from CA side to add them back?
    No i believe, because you are changing the permissions at site level.
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful

  • Add user to sharepoint group using REST API

    I am trying to add a user to sharepoint group with following code
    serviceUrl= Appweb + "/_api/SP.AppContextSite(@target)/web/sitegroups("+GroupId+")/users?@target='host web'";
        $.ajax({
            url: serviceUrl,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            body: "{'__metadata': { 'type': 'SP.User' },'LoginName':'i:0#.f|membership|'+email }",
      headers: {"accept":"application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest":$("#__REQUESTDIGEST").val()
        async: false,
      success: function (data) {
               alert('success');
      error: function (data) {
                 alert('fail');
    The request goes to error function. Response of the request is Microsoft.SharePoint.Client.InvalidClientQueryException and message is A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was
    expected
    I tried the sample from following link but fail it
    https://msdn.microsoft.com/en-us/library/office/dn531432.aspx

    Hi,
    Per my understanding, you might want to add an user to a SharePoint group in host web from a SharePoint Hosted App using REST API.
    Here is a working demo for your reference:
    var hostweburl;
    var appweburl;
    $(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";
    // SP.RequestExecutor.js to make cross-domain requests
    $.getScript(scriptbase + "SP.RequestExecutor.js", loadPage);
    // Utilities
    // Retrieve a query string value.
    // For production purposes you may want to use a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve)
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1)
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve) return singleParam[1];
    function addUsersInGroup() {
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
    url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(8)/users?@target='" + hostweburl + "'",
    method: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    body: "{'__metadata': { 'type': 'SP.User' },'LoginName':'i:0#.f|membership|[email protected]'}",
    headers: {
    "Accept": "application/json; odata=verbose",
    "content-type": "application/json;odata=verbose",
    "X-RequestDigest":$("#__REQUESTDIGEST").val()
    success: addUsersInGroupSuccessHandler,
    error: addUsersInGroupErrorHandler
    function addUsersInGroupSuccessHandler(data)
    console.log(data);
    var jsonObject = JSON.parse(data.body);
    console.log(jsonObject);
    function addUsersInGroupErrorHandler(data)
    console.log(data);
    var jsonObject = JSON.parse(data.body);
    console.log(jsonObject);
    Thanks 
    Patrick Liang
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected].

  • Remove user from multiple groups

    Hello everyone, first time posting here with a question and I apologize if I'm asking in the wrong location.
    To give an idea of what I'm attempting to do, I've recently been developing a vbscript that will take a nightly csv export from my student information system and either create or deactivate student accounts based upon their enrollment status.  I have
    this function working great now, another function I've been developing is to have accounts moved between OU's based upon the school building code assigned to students which I have working as well.  The problem I'm running into right now is having students
    removed from existing active directory groups when they move between OU's.  Essentially what I would like to do is have the script load the users group membership into an array and then remove any groups that end with STUDENTS, below is the code I have
    been working on to accomplish this but have literally hit a brick wall.  If it helps all my student groups for each location runs in this fashion.
    ABCD_STUDENTS
    ABCE_STUDENTS
    Any suggestions would be greatly appreciated.
    ' Student changing OU then we need to update their account to reflect appropriate group memberships.
    Set UserObj = GetObject("WinNT://server.domain.net/" & ADusrname) 'This must be hardcoded to domain controller
    strUserDN = DN
    strUserCN = objuser.cn
    'Add user to the school group if not correct
    Set objGroup = GetObject(varSchoolGroup)
    strUserDN = DN ' Bind to the user object.
    strGroupDN = varSchoolGroup ' Specify group Distinguished Name and check for membership.
    Set objADObject = GetObject("LDAP://"& strUserDN)
    objmemberOf = objadobject.GetEx("memberOf")
    If Not (funIsMember (GetObject("LDAP://" & strUserDN),varSchoolGroup)) Then
    objmemberOf = objadobject.GetEx("memberOf")
    For Each objGroup in objmemberOf
    Set objGroupDelete = GetObject ("LDAP://" & objGroup)
    If Mid(objgroup,7,8) = "STUDENTS" Then
    msgbox "test remove"
    objGroupDelete.PutEx ADS_PROPERTY_DELETE,"member",Array(strUserDN)
    objGroupDelete.setinfo
    subUpdateLogFile studentcounter & " - Removed from student group " & objgroup,student_guid,student_username,student_fullname,"removed group"
    End If
    Next
    'Add user to school group
    Set objGroup = GetObject(varSchoolGroup)
    objGroup.PutEx ADS_PROPERTY_APPEND, "member", Array(struserdn)
    objGroup.SetInfo
    subUpdateLogFile studentcounter & " - Updated school group to " & student_schoolgroup_ldap,student_guid,student_username,student_fullname,"school group"
    objUser.SetInfo
    updated = "yes"
    End If
    Any suggestions would be greatly appreciated.

    With Bill.  This can be done with AD and PowerShell in a couple of lines for reach item.
    You are taking an incorrect approach which is making this much harder than it needs to be.  Your question is also hard to understand.
    Each AD usre object obtained via ADSI will have a list of groups the account is a member of.  You use this to remove the user from the group.  How you choose this is up to you.  You can use an array or a file.  You can also =just use
    OU associated groups.  A user then is added to all or some groups associated with the OU and removed from the groups associated with the OU by just returning the OU associated group list from the OUs.
    Designing AD systems is a specialty.  Once you fully understand the features and capabilities of AD these things are usually simple and painless.  If the design is not done well they are painful and faulty.
    We can answer specific questions.  Understaning the design and capabilities of AD is mostly up to you.
    Start with a tool that is designed to work well with AD like PowerShell. VBScritp is onluy useful to those who are skilled with AD and scripting in VBSdcript.  From your script we can see you are a beginner at both.  As Bill notes...do yourself
    a favor and switch to PowerShell.
    ¯\_(ツ)_/¯

  • Unable to edit document from SharePoint 2007 using Office 2013 and IE 11

    I am getting the following error when I try to edit a document from SharePoint 2007: "Edit document
    requires a Windows Sharepoint services-compatible application and Microsoft Internet Explorer 6.0 or greater". I am using Windows 7 with Office 2013 and Internet Explorer 11. Troubleshooting steps that I've tried so far (that haven't worked) are as follows:
    1) repaired Office; 2) switched from 64 bit version of IE to 32 bit version; 3) moved the owssupp.dll from C:\Program Files (x86)\Microsoft Office\Office14\ to C:\Program Files (x86)\Microsoft Office\Office15; 4) tried removing old versions of Office (but
    I still need to use Office Communicator 2007 r2 and couldn't figure out how to get rid of the Office14 files from Program Files); and 5) running SharePoint in IE compatibility mode. Please advise...thanks!

    Hi,
    It seems you installed mixed version Office2007/2010/2013 on your client machine?
    I would suggest you remove all Office 2007 and 2010 version, and reinstall Office 2013(include Office Tools->Microsoft SharePoint Foundation Support component) on your machine, and make sure "Open SharePointDocuments class" add-on is enabled
    from IE11, then check if it could fix the issue.
    If above works, please test again after installing the Office Communicator 2007 r2 on your machine.
    http://social.microsoft.com/Forums/en-US/3e8c0976-2794-49a2-92fe-6a254b3cc4ca/a-microsoft-sharepoint-foundation-compatible-application-could-not-be-found?forum=projserv2010setup
    http://blogs.technet.com/b/emeaoffice/archive/2013/04/29/you-get-an-error-message-when-you-open-an-office-file-from-sharepoint-on-a-computer-on-which-you-installed-more-than-one-version-of-office.aspx
    Thanks,
    Daniel Yang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Daniel Yang
    TechNet Community Support

  • Remove user from multiple Group

    Hi All,
    Can any one help me on this . 
    we have around 100 different  SSLVPN AD security groups. Need a script or command to remove 790 users
    from all these groups.
    we have list of user in excel sheet we want to remove from group only. 
    Regards, Triyambak

    Hi,
    Just checking in to see if the suggestion was helpful. Please let us know if you would like further assistance.
    TechNet Subscriber Support
    If you are
    TechNet Subscription
    user and have any feedback on our support quality, please send your feedback
    here.
    Regards, Yan Li

  • Download RSS feed as xml file from Sharepoint Online using PowerShell

    Hello
    Our company sharepoint (Office 365) contains also several RSS feeds.
    How it is possible to download xml file out of this feed (website) using PowerShell?
    I can authenticate with sharepoint using CSOM but do not what to do next.
    As service user is not administrator I cannot use "SPOService".
    This script works OK for standard website, but not for Sharepoint.
    $doc = New-Object System.Xml.XmlDocument
    $doc.Load("http://www.{CompanySite}.com/feed/")
    $doc.save("C:\temp\feed.xml")
    I am getting this error when using for company Sharepoint:
    "The remote server returned an error: (403) Forbidden."
    Thanks for your time considering this question.
    Jozin

    Hi Scott,
    thanks for advice.
    Combination of WebClient and Sharepoint Credentials is working OK:
    $client = New-Object System.Net.WebClient 
    $client.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User, $SecurePassword)
    $client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    $client.DownloadFile($SiteURL, $file)

  • Remove SP User from SharePoint subsite

    Hello All,
    I am trying to remove a user account form all sub sites except few.
    I am making use of following command.
    Remove-SPUser "Contoso\jdoe" -web http://webapp/sites/site1/web1/
     But this command is removing the user from all the sub sites including the site collection.
    Can anybody please help to delete the user from specific subsite only.
    Thanks & Regards
    MD Liakath Ali
    MD.Liakath ali

    Hi,
    You can try to delete user from specific SharePoint group at sub site level using Power shell script as below .
    #Remove
    user from SP Group
        $theGroup.RemoveUser($theUser);
    Fine
    more details on below blog
    http://markimarta.com/sharepoint/add-remove-user-to-sharepoint-groups-with-powershell/
    Regards
    Soni
    K

  • How to Remove User from Built in Administrators group With Group Policy Enabled

    Hi,
    I want to remove user from Administrator group which is in restricted group. So I cannot remove him through Active Directory what is the way to remove user from Administrator restricted group.
    Thanks
    Jibran Ishtiaq

    > Disable Group policy
    "Edit", not "Disable"
    > Under Domain click Delegation and went to the restricted group account.
    > Remove User from group.
    Why "Delegation"? Simply edit the GP object where the "Restricted
    Groups" setting is in place...
    > Also we have two DNS but one from where I remove account is the primary.
    How is DNS related to group policy?
    Martin
    Mal ein
    GUTES Buch über GPOs lesen?
    NO THEY ARE NOT EVIL, if you know what you are doing:
    Good or bad GPOs?
    And if IT bothers me - coke bottle design refreshment :))

  • Project Server 2013 - Remove user from resource pool via sync

    Hello everyone,
    has anyone managed to configure their Project Server 2013 box with a resource pool sync that will actually remove user from the resource pool (disable "User can be assigned as resource" or deactivate users) when the user is removed from the AD
    group(s)?
    Setup: Single box, SQL 2012 SP1, SharePoint/Project Server 2013 + PU March + CU April. 2 PWA instances, 1 in SharePoint and 1 in Project permission mode. Tried on 2 different machines (different setup, accounts, domains).
    Proceedings:
    Create AD user U, AD group G. Add U to G.
    Go to PWA, setup resource pool sync with G, sync.
    U is now in the resource pool, has no PWA permissions.
    Remove U from G. Resync resoure pool.
    U is still in resource pool, still a resource, still active, can still be assigned as resource.
    Adding U back to G an repeating the whole spiel with a resource pool and a PWA group sync of G will result in U being added and removed from the user list (as expected), and U being added but not removed from the resource pool.
    Having read
    http://technet.microsoft.com/en-us/library/gg982985.aspx and
    http://technet.microsoft.com/en-us/library/gg750243.aspx, there does not seem to be an omission on my part.
    The first article states:
    Note:
    The corresponding Project Server User Account is not deactivated based on this synchronization. If the same Active Directory user is configured to synchronize with a Project Server security group, the Project Server user account will be inactivated when
    that synchronization occurs. For more information, see
    Best practices to configure Active Directory groups for Enterprise Resource Pool synchronization in Project Server 2013.
    Unfortunately, this deactivation either does not seem to occur even with a PWA group sync or I misunderstood the article.
    So, did anyone manage to setup their resource pool sync in a way, that new resource will be added, but also be removed from the resource pool?
    Kind regards,
    Adrian

    Hi Adrian,
    you tried to sync the same AD group that you used for the resource pool sync also with a Project Server permission group?
    And on removal of the user of the AD group the project user/resource is not deactivated? Only removed from the group
    Regards
    Christoph
    Hi  Christoph,
    even though I might have tried that before, I tried it again in several constellations. It didn't change anything. The the user will be properly added to and removed from the PWA group whenever I remove them from the AD group, the use will also stay active
    (but cannot logon without permissions). However, the user will always remain in the resource pool, i.e. the "User can be assigned as resource." checkbox will remain unless it is cleared manually.
    Having re-read the technet articles, none of the scenarios actually seem to descibe or address the process that I require, or maybe I'm just misunderstanding. Let me just try to outline the core issue:
    Add user to AD group. Sync AD group with resource pool. User is now a PWA resource and PWA user.
    Remove user from AD group, but do not deactivate/delete user from AD.
    (Magic happens!)
    User cannot be assigned as ressource in PWA.
    So, is there anything to make this step 3 happen, or is it just not possible to sync users out of the resource pool anymore unless they are deleted/deactivated in AD?
    Kind regards,
    Adrian

  • Is it possible to add/remove a person from a group using workflow?

    Hi All,
    Is it possible to add/remove a person from a group using workflow?

    What version of SharePoint are you using?
    There is CodePlex project that adds additional work flow steps that would help you out. These include
    Create Site
    Create Group 
    Add users to group
    The link is http://ilovesharepoint.codeplex.com/releases/view/89201
    Steven Andrews
    SharePoint Business Analyst: LiveNation Entertainment
    Blog: baron72.wordpress.com
    Twitter: Follow @backpackerd00d
    My Wiki Articles:
    CodePlex Corner Series
    Please remember to mark your question as "answered" if this solves (or helps) your problem.

  • CSSImport Utility - Remove Users from Groups

    We have a security group that has a few hundred users assigned to the group. When there is a need to remove a user from the group it is difficult to find the user as I have comb through the list to find the user i am trying to remove. Two questions: is there a way to sort the users in the group in Share Services? The second question is can users be removed using the CSSImport utility by specifying the "delete" option in the importexport.properties? Does the "delete" option remove the user from the secuity group and or does it delete it completely from ShareServices? (we are using Hyperion v9.3.0.1.0 Build 5)

    Hi,
    I am not so sure about the sorting but removing users from groups can be done with the CSSImportExport utility, I see you are on 9.3.0, try and get hold of the 9.3.1 version as it is backward compatible to the 9.3.0 version and more stable.
    When removing users from groups, just set your import operation to update
    import.operation=update
    and in your import csv just put the group children elements and the users you want in the group.
    #group_children
    id,group_id,group_provider,user_id,user_provider
    TestGroup,,,UserToKeepInGroup,Native Directory
    This way it will keep the users in the import file and remove the users from the group that are not in the file, also it does not remove the user from shared services only from the group.
    Ok?
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • Remove user from group with MaxL

    hello,is it possible to remove a user from all groups he belongs to without knowing these groups?I want to execute a command such as "alter user my_user remove from ALL_GROUPS;"thanks for your help/

    Not sure if it's feesible, but you could use the 'drop user' command to remove the user from the system, which would of course remove them from all groups, then use the 'create user' command to recreate the user and reassign them to the proper groups.Good luck

  • Who removed user from AD Universal secuirty group

    Hello , i am trying to find who removed user from universal AD group , i checked audit management policy is enabled but some how event is not getting generated or unable to find those events so please help how to find who did that job - removed the user
    from universal security group.
    And suppose if anybody is deleting and the logs should be generated on one of the local site Domain controller is that correct ? so anywhere or it can be generated on the member server. Any free third party tool who can help here .
    Thanks

    Here is another informative technet blog resource that helps to track all the changes made in active directory : http://blogs.technet.com/b/askpfeplat/archive/2012/03/05/how-to-track-the-who-what-when-and-where-of-active-directory-attribute-changes-part-i-the-case-of-the-mysteriously-modified-upn.aspx
    If you wish to audit such changes automatically, you may also consider on this automated solution (http://www.activedirectoryaudit.com/) that would be a better approach to audit all the critical changes
    into real time and get instant notification for through customized email notification.

  • Getting error while removinf user from AD group

    Hi,
    In AD User process definition, there is a default taks called :Remove user from Group. This task runs after another task called Organization Name Update . Whenever, an user is moved from one org to another org, his organization gets updated in AD user form and this task"Remove user from Group" runs. The work of this task is to remove the user from old groups. BUt the task is getting rejected and i see the below error in log files.
    11/07/04 00:24:17 Data AccessException:
    11/07/04 00:24:17 com.thortech.xl.orb.dataaccess.tcDataAccessException: DB_READ_FAILEDDetail: SQL: select UD_ADUSRC_GROUPNAME from UD_ADUSRC where UD_ADUSRC_KEY = Description: ORA-00936: missing expression
    SQL State: 42000Vendor Code: 936Additional Debug Info:com.thortech.xl.orb.dataaccess.tcDataAccessException
    at com.thortech.xl.dataaccess.tcDataAccessExceptionUtil.createException(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataBase.createException(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataBase.readPartialStatement(Unknown Source)
    at com.thortech.xl.dataobj.tcDataBase.readPartialStatement(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataobj.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataobj.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.adapterfactory.events.tcAdpEvent.getChildTableFieldValue(Unknown Source)
    at com.thortech.xl.adapterfactory.events.tcAdpEvent.getRunTimeValue(Unknown Source)
    at com.thortech.xl.adapterfactory.events.tcAdpEvent.getRunTimeValue(Unknown Source)
    at com.thortech.xl.adapterGlue.ScheduleItemEvents.adpADREMOVEUSERFROMGROUP.implementation(adpADREMOVEUSERFROMGROUP.java:48)
    If anybody knows the solution for this then plz let me know.
    Thanks,
    Kalpana.

    I think the mappings and all would be correct. Here is what Kevin meant:
    - Let's assume the AD user account is a part of GroupA, GroupB and GroupC
    - Now on Change Organization completion if you invoke Remove user from Group then the adapter/process task has no way to know that which 3 of those groups has to be removed (or all 3 for your case)
    - Alternatively if you use API's to remove the group then this task would be invoked by the original OIM process/triggers and so the actual value would be known to adapter/process task.

Maybe you are looking for

  • Shopping Cart (page Refresh?)

    Ive created a working shopping cart by storing structures in the session scope but now I'm having problems where if someone were to add 2 items to the cart and then click the back button the page does not refresh to show the new amount of items in th

  • Easy ORACLE RAC 11g question....

    Hi everyone..... Im new at this .... I've setup using VMware a 2 node cluster that works fine... 11g Im planning to move our production database that is currently 10g ... Heres the question... Is it possible to run a 10g instance on 11g RAC... withou

  • Bug report: Reordering columns

    Version 2.2 Came across a major bug in the reorder columns feature in Report Attributes 1. Create a report region with the following query select 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 from dual2. Click on Report Attributes 3. Uncheck the

  • Error in default workflow Project Supplier Invoice Charge Account

    Hi, We applied the patch for E-Business Suite extended support requirements in our clone server and we advise users to test the modules. On the AP-PA module, we received an error saying "The default workflow for the Oracle Payables account function P

  • IDVD Chapter limit?

    I have edited an instructional video in Final Cut Pro and imported it into iDVD to burn to a DVD since DVD Studio Pro keeps crashing under Snow Leopard. Everything imports fine, except iDVD only generates menus for the first 16 chapters. Is there a l