Deactivate users who are no longer exist in AD but were added into resource pool

Hello forum members,
does anyone know how to deactivate users who are no longer exist in AD , but were added into resource pool?
I an trying to write some code that would update a custom value for each resource, but my code breaks whenever it encounters a resource that is not longer exists in AD. Any suggestions are appreciated.
  // Modify the resources, code was taken from http://msdn.microsoft.com/en-us/library/websvcresource.resource.updateresources(v=office.12).ASPX
                foreach (SvcResource.ResourceDataSet.ResourcesRow resourceRow in resourceDs.Resources)
                    Console.WriteLine("Check out " + resourceRow.RES_NAME);
                    if (resourceRow.IsRES_CHECKOUTBYNull())
                        resourceSvc.CheckOutResources(new Guid[] { resourceRow.RES_UID });
                        checkedOut = true;
                    else
                        if (resourceRow.RES_CHECKOUTBY == me)
                            checkedOut = true;
                        else
                            checkedOut = false;
                            Console.WriteLine("\tCan't check out this resource, skip updating this one.");
                    if (checkedOut)
                        SvcResource.ResourceDataSet updateDs = resourceSvc.ReadResource(resourceRow.RES_UID);
                            if (resourceRow.RES_TYPE <= (int)PSLibrary.Resource.Type.INACTIVATED_OFFSET)
                                updateDs.Resources[0].RES_CODE = "A" + rand.Next(1000, 9999);
                                Console.WriteLine("Update RES_CODE to " + updateDs.Resources[0].RES_CODE);
                                resourceSvc.UpdateResources(updateDs, false, false);
                                Console.WriteLine("Check in " + resourceRow.RES_NAME);
                                resourceSvc.CheckInResources(new Guid[] { resourceRow.RES_UID }, false);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("".PadRight(30, '-'));
                    Console.ResetColor();
tatiana

This is the logic I used:
1) Try to inactivate the user
2) If it fails with "AdminNTAccountNotFound" then delete
try {
using( OperationContextScope ocs = new OperationContextScope( resourceClient.InnerChannel ) ) {
resourceClient.CheckOutResources( new Guid[] { resourceUID } );
// Perform the update
rsDS = ( SvcResource.ResourceDataSet ) rsDS.GetChanges();
resourceClient.UpdateResources( rsDS, false, true );
catch( Exception ex ) {
if( ex.Message.Contains( "AdminNTAccountNotFound" ) ) {
try {
resourceClient.CheckInResources( new Guid[] { resourceUID }, true );
catch {
//The resource does not have a valid account, deleting...
using( OperationContextScope ocs = new OperationContextScope( resourceClient.InnerChannel ) ) {
resourceClient.CheckOutResources( new Guid[] { resourceUID } );
resourceClient.DeleteResources( new Guid[] { resourceUID }, "No longer in RBS structure and/or AD" );
120811049008

Similar Messages

  • Powershell Script to find out Orphan Users ( Who are no longer available in AD but SharePoint) in SharePoint 2013

    Hi,
    Can you please on the above issue? I have one script which works fine for sp2010 but not sp2013 below,
    Script
    function Check_User_In_ActiveDirectory([string]$LoginName, [string]$domaincnx)
    $returnValue = $false
    #Filter on User which exists and activated
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(samAccountName=$LoginName))"
    #Filter on User which only exists
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(samAccountName=$LoginName))"
    #Filter on User and NTgroups which only exists
    $strFilter = "(&(|(objectCategory=user)(objectCategory=group))(samAccountName=$LoginName))"
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry($domaincnx)
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    #$objSearcher.PropertiesToLoad.Add("name")
    $colResults = $objSearcher.FindAll()
    if($colResults.Count -gt 0)
    #Write-Host "Account exists and Active: ", $LoginName
    $returnValue = $true
    return $returnValue
    function ListOrphanedUsers([string]$SiteCollectionURL, [string]$mydomaincnx)
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
    $site = new-object Microsoft.SharePoint.SPSite($SiteCollectionURL)
    $web = $site.openweb()
    #Debugging - show SiteCollectionURL
    write-host "SiteCollectionURL: ", $SiteCollectionURL
    Write-Output "SiteCollectionURL - $SiteCollectionURL"
    $siteCollUsers = $web.SiteUsers
    write-host "Users Items: ", $siteCollUsers.Count
    foreach($MyUser in $siteCollUsers)
    if(($MyUser.LoginName.ToLower() -ne "sharepoint\system") -and ($MyUser.LoginName.ToLower() -ne "nt authority\authenticated users") -and ($MyUser.LoginName.ToLower() -ne "nt authority\local service"))
    #Write-Host "  USER: ", $MyUser.LoginName
    $UserName = $MyUser.LoginName.ToLower()
    $Tablename = $UserName.split("\")
    Write-Host "User Login: ", $MyUser.LoginName
    $returncheck = Check_User_In_ActiveDirectory $Tablename[1] $mydomaincnx 
    if($returncheck -eq $False)
    #Write-Host "User not exist: ",  $MyUser.LoginName, "on domain", $mydomaincnx 
    Write-Output $MyUser.LoginName 
    $web.Dispose()
    $site.Dispose()
    function ListOrphanedUsersForAllColl([string]$WebAppURL, [string]$DomainCNX)
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
    $Thesite = new-object Microsoft.SharePoint.SPSite($WebAppURL)
    $oApp = $Thesite.WebApplication
    write-host "Total of Site Collections: ", $oApp.Sites.Count
    $i = 0
    foreach ($Sites in $oApp.Sites)
    $i = $i + 1
    write-host "Collection N° ", $i, "on ", $oApp.Sites.Count
    if($i -gt 0)
    $mySubweb = $Sites.RootWeb
    $TempRelativeURL = $mySubweb.Url
    ListOrphanedUsers $TempRelativeURL $DomainCNX
    function StartProcess()
    # Create the stopwatch
    [System.Diagnostics.Stopwatch] $sw;
    $sw = New-Object System.Diagnostics.StopWatch
    $sw.Start()
    #cls
    ListOrphanedUsersForAllColl "http://portal" "LDAP://DC=Srabon,DC=com" 
    ListOrphanedUsersForAllColl "http://portal/sites/Test" "LDAP://DC=Srabon,DC=com"  
    $sw.Stop()
    # Write the compact output to the screen
    write-host "Time: ", $sw.Elapsed.ToString()
    StartProcess
    # Can be executed with that command : "Check-SharePoint-Orphaned-Users.ps1 > orphaned_users.txt"
    srabon

    Hi Srabon,
    Try this it works in SP2007, SP2010, and SP2013.
    Mod line 70: $WebAppURL="http://intranet.contoso.com" to your "http://WebApp"
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    #Functions to Imitate SharePoint 2007, 2010, 2013
    function global:Get-SPWebApplication($WebAppURL)
    return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
    function global:Get-SPSite($url)
    return new-Object Microsoft.SharePoint.SPSite($url)
    function global:Get-SPWeb($url)
    $site= New-Object Microsoft.SharePoint.SPSite($url)
    if ($site -ne $null)
    $web=$site.OpenWeb();
    return $web
    #Check if User exists in ActiveDirectory
    function CheckUserExistsInAD()
    Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )
    #Search the User in ActiveDirectory
    $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
    foreach ($Domain in $forest.Domains)
    $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Domain.Name)
    $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
    $root = $domain.GetDirectoryEntry()
    $search = [System.DirectoryServices.DirectorySearcher]$root
    $search.Filter = "(&(objectCategory=User)(samAccountName=$UserLoginID))"
    $result = $search.FindOne()
    if ($result -ne $null)
    return $true
    return $false
    $WebAppURL="http://intranet.contoso.com"
    #Get all Site Collections of the web application
    $WebApp = Get-SPWebApplication $WebAppURL
    #Iterate through all Site Collections
    foreach($site in $WebApp.Sites)
    #Get all Webs with Unique Permissions - Which includes Root Webs
    $WebsColl = $site.AllWebs | Where {$_.HasUniqueRoleAssignments -eq $True} | ForEach-Object {
    $OrphanedUsers = @()
    #Iterate through the users collection
    foreach($User in $_.SiteUsers)
    #Exclude Built-in User Accounts , Security Groups & an external domain "corporate"
    if (($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and
    ($User.LoginName.ToLower() -ne "sharepoint\system") -and
    ($User.LoginName.ToLower() -ne "nt authority\local service") -and
    ($user.IsDomainGroup -eq $false ) -and
    ($User.LoginName.ToLower().StartsWith("corporate") -ne $true) )
    $UserName = $User.LoginName.split("\") #Domain\UserName
    $AccountName = $UserName[1] #UserName
    if ( ( CheckUserExistsInAD $AccountName) -eq $false )
    Write-Host "$($User.Name)($($User.LoginName)) from $($_.URL) doesn't Exists in AD!"
    #Display Orphaned users
    $OrphanedUsers+=$User.LoginName
    # <<<UNCOMMENT to Remove Users#
    # Remove the Orphaned Users from the site
    # foreach($OrpUser in $OrphanedUsers)
    # $_.SiteUsers.Remove($OrpUser)
    # Write-host "Removed the Orphaned user $($OrpUser) from $($_.URL) "
    $web.Dispose()
    $site.Dispose()
    -Ivan

  • Sun DS version 5.2 deactivate users who are haven't logged in since 6months

    Hi,
    I'm using Sun DS version 5.2.
    I want to deactivate users who have not logged in since 6 months.
    How can i do that?
    Btw please note that Sun DS version 5.2 and so there is no attribute to track last login of users.
    Thanks.

    Hi,
    unless you know that after the login the user modifies any other attribute in his profile, so it may change the modifytimestamp, then there's no other way of getting such information querying the DS instance.
    In that case, I think a 'dirt' alternative could be to 'parse' the log files ... looking for the binds :(
    HTH,
    Marco

  • Equipment no longer exists in EQUI but found in EQUZ, EQKT tables

    Hi Experts,
    We found that the few equipments are no longer exists in EQUI, but left with the entries in the tables EQUZ, EQKT.Also, we found that we could able to read the system and user status for these equipments in the JEST table and STATUS_TEXT_EDIT Function module where it is showing the status as 'INST'
    We ran the report RISTEQ20 and got the message as ' Root segment not found'. We could understand that some how the inconsistencies occured. Also, we have confirmed these equipments listed out after we ran the report RCCLZUOB with class type 002 in the test mode.
    To remove these inconsistencies, Before we run the report RCCLZUOB in the update mode (Delete =X), we would like to know how this would have happened.No users in the production got training to the archiving process or deletion process.
    Can you please throw some hints for us to understand the problem completely.
    Thanks,
    Suresh
    Edited by: Suresh Babu on Jun 24, 2011 2:10 AM

    Hi Pete,
    Thanks for the reply. We havent assign any serial number profile for this particular category of equipment. Also We havent done any archving or put a deletion flag. We could read the status of these equipments still as 'INST' in JEST table.
    Thanks,
    Suresh

  • How to delete the queries in  BW Production which are no longer existing.

    Hi,
    How to  delete the queries in BW production which are no longer existing in DEV.
    1. I tried Using RSZDELETE in Production it is not getting deleted and the below message given.
    Query object 4A7V83T3RB4ABIOKSDJT2HWDL is blocked. Deletion has been cancelled.
    2. I tried creating another query in dev with the same technical name and send a transport with deletion
    it is not working.
    Please advise me on this for any function module or any other method.
    Thanks
    Surya

    Hi,
    If you transported the query from DEV and now you want to delete it, you should open a BEx request (Dev Class under which it was originally transported -- or-- Standard - type) in DEV delete the query and move the transport to Production.
    As far as your error is concerned, usually  when you  can delete a query using the delete option in query designer itself,
    Business Explorer> query-> delete objects , when you press execute the system offers you a list of dependent objects on the query(workbook,views), in case the sysytem is unable to delete them i.e.they being used as a input query for a characteristic variable (replacement path),then system throws this error.You can delete these all depndents under there prescribed roles , fav s & then proceed.
    Hope this will be expedite.
    Thax & regards.
    Vaibhave Sharma

  • How to list of Users who are using Crystal XI application?

    Hi all,
    Thanks for your support provided so far.
    I need to get the list of users who are all using the Crystal XI application. I tried to get this info from the Business Objects Enterprise Applications in CMC but it was not there. Where can I find this information?
    kindly help me.
    Thanks,
    Bhuvan R

    There is not such a portlet available out of the box...
    Have you looked at the code share section?
    If you want to develop yourself, I don't think this is achievable using the IDK (remote interface)
    But It is definitely possible to create such a portlet using the server API (drawback: the portlet has to live where a portal component is installed - WS, automation or Portal)

  • How to skip approving steps for users who are also approvers?

    We have a business need to be able to skip the approving steps for the users who are also approvers.
    For this following steps were followed :-
    1) Open .task file and go into the Assignment tab. Double click on the performer box within the routing slip, this should open the "Edit Participant Type" editor. Expand the "Advanced" section and place a check next to "specify skip rule", then click the edit icon to the right. Now enter an XPath expression that will test whether the current user is equal to the task creator.
    2) We used - isUserInRole XPath function in the "Identify Service Functions" dropdown - first param to function is the userID, the 2nd is the role name.
    We tried with hardcoded userID as well as by using
    ids:isUserInRole(/task:task/task:systemAttributes/task:updatedBy/task:id,'California')
    where 'California' is the group name (as one of the forum threads told this function works with groups).
    We also tried with swimlane roles(using bpm.getPerformer() function) but it does not work either.
    Please let me know if any one has any solution to this problem.

    session as DirectorySession = DirectorySession.currentEngineSession
    dirHum as Fuego.Fdi.DirHumanParticipant = DirHumanParticipant.fetch(session : session, id : "myUserId")
    result = hasRoleAssigned(dirHum, role : "Approver")Give that a try...
    HTH,
    -Kevin

  • Getting Lync enable users who are modified after specified time

    Getting Lync enable users who are modified after specified time
    Hi,
    I need to get all the Lync enabled users from Lync 2010 server who are modified after specified time.
    I have written a client with this below code for my purpose
    string
    dateString = "11/4/2014 11:19:10 PM";
    DateTime
    lastModifiedTime = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);
    PSCommand command = new PSCommand();
    command.AddCommand("Get-CsUser");
    command.AddParameter("Filter",
    "WhenChanged -gt " + lastModifiedTime.ToString());
    powershell.Commands
    = command;
    Collection<PSObject> outPut = powershell.Invoke();
    But on calling Invoke method I am getting the below exception,
    Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "Invalid cast problem for value: "11" type: "System.Nullable`1[System.DateTime]" query: "WhenChanged -gt 11/4/2014 11:19:10 PM" "17""
    Can anyone please point me what am I doing wrong.
    This command
    Get-CsUser -filter {whenchanged -gt
    "11/4/2014 11:19:10 PM"}
    when run directly on Windows Powershell works fine.
    Thanks in advance.
    Sandeep

    It appears you may be casting the date variable wrong. 
    If you have
    command.AddParameter("Filter",
    "WhenChanged -gt 11/4/2014 11:19:10 PM"
    And avoid the lastModifiedTime.ToString() addition, does it work?
    If so, it's just the way you're doing your date manipulation.
    Also, why convert from a string to a datetype and back for the datestring?  Are you trying to correct a timezone issue?
    Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".
    SWC Unified Communications
    This forum post is based upon my personal experience and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Message tracking log of internal users who are all sent the mails to external domain

    Hi ,
    How can i get the message tracking log from internal users to external users?
    We need the report of internal users who are all sent the mails to the external domain
    Regards,
    Sankar M
    Sankar M http://messagingdevelopment.blogspot.in/

    Sankar, your outbound send connector has an address space of *. So when you run "Get-SendConnector", you will see something like the following:
    Identity                                AddressSpaces                          
    Enabled
    Unix System Connection                  {SMTP:*.domfreebusy.contractor.hunti... True
    Outgoing SMTP Connector                
    {SMTP:*;10}                             True
    Mailbox Journaling Connector            {SMTP:pdwastap01.huntington.com;1}      True
    The middle one with the {SMTP:*;10} in my case (you may have a different number than 10 in yours) is my outbound connector. So yours will show an address space of {SMTP:*;<some number, 10 is the default>}. HTH ...

  • Using imessenger is it free to chat with iphone users who are in another country?

    Using imessenger is it free to chat with iphone users who are in another country?

    my understanding is yes because it worked with ipod touches via your Apple ID and there is no payment process agreement when setting up iMessage.

  • How to get the online user  who are browse some view?

    i want to get the current users who are browsing some view in EP6.additonal:which is developed as web dynpro project.

    Hi,
    Per my knowledge, we cannot get the SharePoint user context available in custom federated search connector with other methods.
    Here is a similar thread for your reference:
    https://answers.atlassian.com/questions/263735/atlassian-sharepoint-connector-federated-search-authentication-and-authorization
    Thanks,
    Linda Li                
    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]
    Linda Li
    TechNet Community Support

  • How to keep track of the users who are all currently logged in

    Hi All,
    I have basic knowledge of Session and Servlets. I am wondering how to keep track of the users who are all currently logged in. There should be some way of achieving it.
    I thought of it and come up with having an Application variable that hold it when ever a user successfully logged in.
    Thanks in advance for any reply.

    You can do this by keeping data in a static veriable in a some class of yours. The variable will need to be a collection.
    Whenever a user loogs in to the site a servlet/jsp should put the users information in to the collection and when logs off or when the session expires the entry should be take off.
    You can achive this by storing the velues in a some sort of a week collection where the entries are automaticaly removed when all the other refferences to the entry goes out of scope.
    You might need to read bit about java.lang.ref package and WeekReference
    Or you can make the entry in the collection contain the last time that the user visited any of the pages and a thread can run time to time and clean up the older entries which have timed out

  • IAC 3.1.1 users who are member of more than one OrgUnit are not able to order services?

    Hi,
    Power Down, Power Cycle, Take Snapshot and Decommission services are not working for users who are member of more than one organization!!
    Error Message:
    The service form could not be submitted because of following error: [newscale][SQLServer JDBC Driver][SQLServer]Conversion failed when converting the nvarchar value '1,2' to data type int.
    Thanks,
    Maz

    Hi,
    Power Down, Power Cycle, Take Snapshot and Decommission services are not working for users who are member of more than one organization!!
    Error Message:
    The service form could not be submitted because of following error: [newscale][SQLServer JDBC Driver][SQLServer]Conversion failed when converting the nvarchar value '1,2' to data type int.
    Thanks,
    Maz

  • Retrieve users who are not added to any group in site permissions page

    Hi,
    In the OOB (Site Permissions) "user.aspx" page, I have some users who are directly added to the site and not part of any OOB or custom group.
    Is it possible to retrieve only those users who are directly added to site permissions page programmatically  ( Using C# ) ?
    Thanks

    Hi,
    You can use the
    SPWeb.Users property which “Gets the collection of user objects that are explicitly assigned permissions in the website”.
    Thanks
    Patrick Liang
    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]
    Patrick Liang
    TechNet Community Support

  • Can it be possible to disable outlook anywhere for some few users who are working from home ?

    One of my customer wants to disable outlook anywhere for some of the users who are working from home.They have exchange server 2013 in their premises and also have outlook 2010/2013 on their clients machine.Please advice?

    Hi,
    In Exchange 2013, all Outlook connectivity (Internal and External) are using Outlook Anywhere anyways. It is not recommended to use the following command to disable Outlook Anywhere for a specific user:
    Set-CASMailbox UserA -MAPIBlockOutlookRpcHttp $True
    If you disable it, the UserA would not be able to access the mailbox from both Internal Outlook client (Office) and external Outlook client (Home).
    For your requirement about disable Outlook anywhere for some few users instead of all external users, there seems to be no method to achieve it directly in Exchange server. Sorry for any inconvenience.
    Regards,
    Winnie Liang
    TechNet Community Support

Maybe you are looking for