top of page
Search
laylaviellelni

Script to remove Inactive systems from domain by querying the last logon time



Active Directory contains an account for every user. Over time, users leave the organization and those user accounts may not get removed from Active Directory. Stale user accounts are a significant security issue, as former employees and external attackers could use those accounts to attack the organization. Stale accounts also use up space in the directory database that could be reclaimed.




Script to remove Inactive systems from domain



PowerShell is one of many tools that can help you find inactive computers in your Active Directory. Using PowerShell, you can get inactive computers and export them to a CSV file; you can even schedule a script to run regularly to report on stale computer objects. However, creating and maintaining the scripts takes both time and expertise with PowerShell commands. Moreover, while the scripts can collect inactive computer accounts, they do not help with the critical step of disabling them.


The following script will query Configmgr for inactive devices and automatically remove them if they are no longer in Active Directory. Personally I prefer this simple script over the built in Configmgr maintenance task (Delete Inactive Client Discovery Data) because the task does not check Active Directory and it will remove any inactive device with the criteria that you have configured. By default, this maintenance task will remove any device that has been inactive for 90 days. At least in my environment, if a computer does not exist in Active Directory it should not be in MEMCM so I have the script run on a daily basis as a scheduled task to remove the devices that are not in AD.


I showed you two examples for finding and removing inactive user accounts in Active Directory. I highly recommend you add this to your monthly maintenance checklist. Security is a big concern with Active Directory but as I pointed out there are several reasons why this is an important task. PowerShell is a great option for finding inactive accounts but does require knowledge of scripting. For those that are not into scripting or just want a quick and simple solution, there is the AD Cleanup GUI Tool.


To remove multiple computers using a list in a TXT file, use the script above for joining computers to a DC, replacing the Add-Computer cmdlet with Remove-Computer. Note that you will still need domain admin credentials to complete this unjoin operation.


To delete a computer account from AD, use the Remove-ADObject cmdlet. The -Identity parameter specifies which Active Directory computer to remove. You can specify a computer by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.


If you have a text file with a list of old computers, you can streamline the task of removing them using PowerShell. The following script will read the computer names from a TXT file and delete the corresponding accounts via a chain of commands, or pipeline:


Stale accounts in Active Directory can be compromised, leading to security incidents, so it is critical to keep an eye on them. This PowerShell script will query Active Directory and return all computers that have not been logged in to for the past 30 days; you can easily change this default value in the script. It also will remove those accounts to keep your AD clean.


Administrators should occasionally delete old user profiles (retired or inactive users, etc.) from C:\Users on Windows workstations and servers. The Windows user profile cleanup task is most commonly performed on Remote Desktop Services (RDS) terminal servers. (adsbygoogle = window.adsbygoogle []).push();


Delete Old User Profiles with PowerShell ScriptInstead of using the automatic profile cleanup policy described above, you can use a simple PowerShell script to find and remove the profiles of disabled or inactive users.


To remove all these user profiles, it is sufficient to pipe the list of users to the Remove-WmiObject command (it is recommended that you check the output of the script with the -WhatIf parameter before running it):


To avoid deleting the profiles of some users (such as System and Network Service accounts, a local administrator account, accounts of users having active sessions, and other accounts from the exception list), you can modify the script as follows:


Hi Gents, I have a question with regard to the scripts above. I have an environment running RDS sessions and want to create a script too clear all inactive user profiles older that 60days. Now my problem is I dont want to delete the profiles like Public and Remote User and Admin and cscsa user profiles. How do I go about altering this script to work for me. I am not a powershell guru so any assistance would be appreciated.


You can use the Get-ADComputer cmdlet to find inactive computer objects in a domain. The LastLogonTimeStamp attribute can be used as search criteria. Note that this attribute cannot be used to retrieve real-time information about the last time a computer logged on to the domain. However, due to the fact that this attribute is replicated between DCs every 9-14 days, you can get information about the last computer logon time from any domain controller (unlike the LastLogonDate attribute, which is updated only on the DC through which the computer logged in).


This is very useful PowerShell cmdlet, you can get a lot of information from it.But if you are not so advanced PowerShell user then I can recommend my free Active Directory reporting toolThere you can much easier generate inactive, disabled, password expired, password will expire in X days and much more reports.


When production workload VMs in a DJI Frame account are created (due to a publish or an increase in the max capacity of a production pool), the production workload VMs are added to the specified Windows Active Directory as computer objects. Each time there is a publish (for non-persistent DJI Frame accounts) or if the max capacity of a production pool is reduced, workload VMs are terminated. However, the corresponding AD computer objects are not automatically removed from the Windows domain.


Domain administrators can run the following PowerShell scripts to identify and remove stale computer objects in their domain, where stale computer objects are defined as computer objects that have not been logged in for a defined period of time. These scripts must be run with a Windows domain user with the proper Windows domain privileges to query the domain controller for the first PowerShell script and to delete computer objects from the domain for the second PowerShell script.


You\u2019re ready to thrive, learn, share, and connect with others. And you\u2019re not alone.", "imageupload.max_uploaded_images_per_upload" : 10, "imageupload.max_uploaded_images_per_user" : 5000, "integratedprofile.connect_mode" : "", "tkb.toc_maximum_heading_level" : "", "tkb.toc_heading_list_style" : "disc", "sharedprofile.show_hovercard_score" : true, "config.search_before_post_scope" : "community", "tkb.toc_heading_indent" : "", "p13n.cta.recommendations_feed_dismissal_timestamp" : -1, "imageupload.max_file_size" : 4000, "layout.show_batch_checkboxes" : false, "integratedprofile.cta_connect_slim_dismissal_timestamp" : -1 }, "isAnonymous" : true, "policies" : "image-upload.process-and-remove-exif-metadata" : false , "registered" : false, "emailRef" : "", "id" : -1, "login" : "Community Alums" }, "Server" : "communityPrefix" : "/community/s/cgfwn76974", "nodeChangeTimeStamp" : 1675927707199, "tapestryPrefix" : "/community", "deviceMode" : "DESKTOP", "responsiveDeviceMode" : "DESKTOP", "membershipChangeTimeStamp" : "0", "version" : "22.12", "branch" : "22.12-release", "showTextKeys" : false , "Config" : "phase" : "prod", "integratedprofile.cta.reprompt.delay" : 30, "profileplus.tracking" : "profileplus.tracking.enable" : false, "profileplus.tracking.click.enable" : false, "profileplus.tracking.impression.enable" : false , "app.revision" : "2302010131-s48b13a6fef-b73", "navigation.manager.community.structure.limit" : "2500" , "Activity" : "Results" : [ ] , "NodeContainer" : "viewHref" : " -p/Developer", "description" : "Create custom applications for your service catalog, integrations, knowledge management, incident management, change and release management, notifications, and share knowledge.", "id" : "Developer", "shortTitle" : "Developer", "title" : "Developer", "nodeType" : "category" , "Page" : "skins" : [ "servicenow", "theme_hermes", "responsive_peak" ], "authUrls" : "loginUrl" : "/community/s/plugins/common/feature/oidcss/sso_login_redirect/providerid/default?referer=https%3A%2F%2Fwww.servicenow.com%2Fcommunity%2Fdeveloper-forum%2Fautomate-the-process-of-removing-inactive-members-of-active%2Fm-p%2F1524126%2Fthread-id%2F181052", "loginUrlNotRegistered" : "/community/s/plugins/common/feature/oidcss/sso_login_redirect/providerid/default?redirectreason=notregistered&referer=https%3A%2F%2Fwww.servicenow.com%2Fcommunity%2Fdeveloper-forum%2Fautomate-the-process-of-removing-inactive-members-of-active%2Fm-p%2F1524126%2Fthread-id%2F181052", "loginUrlNotRegisteredDestTpl" : "/community/s/plugins/common/feature/oidcss/sso_login_redirect/providerid/default?redirectreason=notregistered&referer=%7B%7BdestUrl%7D%7D" , "name" : "ForumTopicPage", "rtl" : false, "object" : "viewHref" : "/community/developer-forum/automate-the-process-of-removing-inactive-members-of-active/td-p/1524126", "subject" : "Automate the process of removing inactive members of active groups", "id" : 1524126, "page" : "ForumTopicPage", "type" : "Thread" , "WebTracking" : "Activities" : , "path" : "Community:ServiceNow Community/Category:Discussions/Category:Developer/Board:Developer forum/Message:Automate the process of removing inactive members of active groups" , "Feedback" : "targeted" : , "Seo" : "markerEscaping" : "pathElement" : "prefix" : "@", "match" : "^[0-9][0-9]$" , "enabled" : false , "TopLevelNode" : "viewHref" : " ", "description" : "", "id" : "cgfwn76974", "shortTitle" : "ServiceNow Community", "title" : "ServiceNow Community", "nodeType" : "Community" , "Community" : "viewHref" : " ", "integratedprofile.lang_code" : "en", "integratedprofile.country_code" : "US", "id" : "cgfwn76974", "shortTitle" : "ServiceNow Community", "title" : "ServiceNow Community" , "CoreNode" : "conversationStyle" : "forum", "viewHref" : " -forum/bd-p/developer-forum", "settings" : , "description" : "", "id" : "developer-forum", "shortTitle" : "Developer forum", "title" : "Developer forum", "nodeType" : "Board", "ancestors" : [ "viewHref" : " -p/Developer", "description" : "Create custom applications for your service catalog, integrations, knowledge management, incident management, change and release management, notifications, and share knowledge.", "id" : "Developer", "shortTitle" : "Developer", "title" : "Developer", "nodeType" : "category" , "viewHref" : " -p/User_forums", "description" : "", "id" : "User_forums", "shortTitle" : "Discussions", "title" : "Discussions", "nodeType" : "category" , "viewHref" : " ", "description" : "", "id" : "cgfwn76974", "shortTitle" : "ServiceNow Community", "title" : "ServiceNow Community", "nodeType" : "Community" ] };LITHIUM.Components.RENDER_URL = '/community/util/componentrenderpage/component-id/#component-id?render_behavior=raw';LITHIUM.Components.ORIGINAL_PAGE_NAME = 'forums/v5/ForumTopicPage';LITHIUM.Components.ORIGINAL_PAGE_ID = 'ForumTopicPage';LITHIUM.Components.ORIGINAL_PAGE_CONTEXT = 'rsxZXxT2NKrK4feSy-0XmglR-gwm7tqQgXj8-c_J2LylMl113z3nz_Z1dxA1s4E-M8eniojkrwnvHJf9NKRrP7t1lwtQc--PLVd8Q_9iNszc8yN3TAQPebE4d2MbPRm6S8JkRuC0x1B7KOV5El-q20LKzSwlxTUdORfP_mvkTn7n-IP6lO1LQomYJ60e3_kOOqJIHsktcX9f3apaC-VynTgPFIhzM736cZhz4hneIU_Q5-lMm-vJ9D-SOs7V1HI3kKpN9JXiI6zcFlSzdM4xyHgYdVihx_F1ojFJdf598QDsQfHtZ24bbVRoOgaLzhLCTCB5TpVtTXDJypJ2H-uUIYwBpUeqMFxm_Ci-tvur9d0X5jF-QJFem41fZuIVe_IhzX3s1nhpoV2synNpH3o0BkYuva2gS0oL9j5OHcaa6h8.';LITHIUM.Css = "BASE_DEFERRED_IMAGE" : "lia-deferred-image", "BASE_BUTTON" : "lia-button", "BASE_SPOILER_CONTAINER" : "lia-spoiler-container", "BASE_TABS_INACTIVE" : "lia-tabs-inactive", "BASE_TABS_ACTIVE" : "lia-tabs-active", "BASE_AJAX_REMOVE_HIGHLIGHT" : "lia-ajax-remove-highlight", "BASE_FEEDBACK_SCROLL_TO" : "lia-feedback-scroll-to", "BASE_FORM_FIELD_VALIDATING" : "lia-form-field-validating", "BASE_FORM_ERROR_TEXT" : "lia-form-error-text", "BASE_FEEDBACK_INLINE_ALERT" : "lia-panel-feedback-inline-alert", "BASE_BUTTON_OVERLAY" : "lia-button-overlay", "BASE_TABS_STANDARD" : "lia-tabs-standard", "BASE_AJAX_INDETERMINATE_LOADER_BAR" : "lia-ajax-indeterminate-loader-bar", "BASE_AJAX_SUCCESS_HIGHLIGHT" : "lia-ajax-success-highlight", "BASE_CONTENT" : "lia-content", "BASE_JS_HIDDEN" : "lia-js-hidden", "BASE_AJAX_LOADER_CONTENT_OVERLAY" : "lia-ajax-loader-content-overlay", "BASE_FORM_FIELD_SUCCESS" : "lia-form-field-success", "BASE_FORM_WARNING_TEXT" : "lia-form-warning-text", "BASE_FORM_FIELDSET_CONTENT_WRAPPER" : "lia-form-fieldset-content-wrapper", "BASE_AJAX_LOADER_OVERLAY_TYPE" : "lia-ajax-overlay-loader", "BASE_FORM_FIELD_ERROR" : "lia-form-field-error", "BASE_SPOILER_CONTENT" : "lia-spoiler-content", "BASE_FORM_SUBMITTING" : "lia-form-submitting", "BASE_EFFECT_HIGHLIGHT_START" : "lia-effect-highlight-start", "BASE_FORM_FIELD_ERROR_NO_FOCUS" : "lia-form-field-error-no-focus", "BASE_EFFECT_HIGHLIGHT_END" : "lia-effect-highlight-end", "BASE_SPOILER_LINK" : "lia-spoiler-link", "FACEBOOK_LOGOUT" : "lia-component-users-action-logout", "BASE_DISABLED" : "lia-link-disabled", "FACEBOOK_SWITCH_USER" : "lia-component-admin-action-switch-user", "BASE_FORM_FIELD_WARNING" : "lia-form-field-warning", "BASE_AJAX_LOADER_FEEDBACK" : "lia-ajax-loader-feedback", "BASE_AJAX_LOADER_OVERLAY" : "lia-ajax-loader-overlay", "BASE_LAZY_LOAD" : "lia-lazy-load";LITHIUM.noConflict = true;LITHIUM.useCheckOnline = false;LITHIUM.RenderedScripts = [ "LazyLoadComponent.js", "Events.js", "EarlyEventCapture.js", "Placeholder.js", "MessageViewDisplay.js", "ElementQueries.js", "AjaxFeedback.js", "jquery.ui.dialog.js", "AutoComplete.js", "SpoilerToggle.js", "DropDownMenu.js", "HelpIcon.js", "jquery.effects.slide.js", "jquery.ui.position.js", "Namespace.js", "jquery.function-utils-1.0.js", "Throttle.js", "Auth.js", "jquery.position-toggle-1.0.js", "Globals.js", "jquery.ui.mouse.js", "jquery.tmpl-1.1.1.js", "jquery.scrollTo.js", "jquery.clone-position-1.0.js", "DeferredImages.js", "Loader.js", "ThreadedDetailMessageList.js", "InlineMessageEditor.js", "jquery.viewport-1.0.js", "Video.js", "jquery.autocomplete.js", "json2.js", "jquery.ui.core.js", "jquery.json-2.6.0.js", "jquery.ui.draggable.js", "Forms.js", "MessageBodyDisplay.js", "ResizeSensor.js", "addthis_widget.js", "Text.js", "jquery.delayToggle-1.0.js", "PartialRenderProxy.js", "jquery.effects.core.js", "Cache.js", "InformationBox.js", "DropDownMenuVisibilityHandler.js", "jquery.ajax-cache-response-1.0.js", "Components.js", "jquery.iframe-transport.js", "InlineMessageReplyContainer.js", "Tooltip.js", "InlineMessageReplyEditor.js", "NoConflict.js", "jquery.ui.widget.js", "ActiveCast3.js", "Link.js", "OoyalaPlayer.js", "AjaxSupport.js", "DataHandler.js", "jquery.iframe-shim-1.0.js", "jquery.blockui.js", "PolyfillsAll.js", "jquery.hoverIntent-r6.js", "prism.js", "jquery.appear-1.1.1.js", "Lithium.js", "jquery.placeholder-2.0.7.js", "jquery.ui.resizable.js", "jquery.lithium-selector-extensions.js", "ProductTagList.js", "jquery.css-data-1.0.js", "ElementMethods.js", "LiModernizr.js", "jquery.tools.tooltip-1.2.6.js", "SearchAutoCompleteToggle.js", "ForceLithiumJQuery.js", "jquery.fileupload.js", "SearchForm.js", "Sandbox.js", "jquery.js"];(function(){LITHIUM.AngularSupport=function(){function g(a,c)a=avar d,f,b=coreModule:"li.community",coreModuleDeps:[],noConflict:!0,bootstrapElementSelector:".lia-page .min-width .lia-content",bootstrapApp:!0,debugEnabled:!1,useCsp:!0,useNg2:!1,k=function()var a;return function(b)();LITHIUM.Angular=;return{preventGlobals:LITHIUM.Globals.preventGlobals,restoreGlobals:LITHIUM.Globals.restoreGlobals,init:function(){var a=[],c=document.querySelector(b.bootstrapElementSelector);a.push(b.coreModule);b.customerModules&&0(window.BOOMR_mq=window.BOOMR_mq[]).push(["addVar","rua.upush":"false","rua.cpush":"true","rua.upre":"false","rua.cpre":"false","rua.uprl":"false","rua.cprl":"false","rua.cprf":"false","rua.trans":"SJ-06a28851-3a8c-447b-b27b-8f27c462b484","rua.cook":"false","rua.ims":"false","rua.ufprl":"false","rua.cfprl":"false","rua.isuxp":"false","rua.texp":"norulematch"]); !function(a){var e=" -mpulse.net/boomerang/",t="addEventListener";if("True"=="True")a.BOOMR_config=a.BOOMR_config,a.BOOMR_config.PageParams=a.BOOMR_config.PageParams,a.BOOMR_config.PageParams.pci=!0,e=" -mpulse.net/boomerang/";if(window.BOOMR_API_key="RL5JW-PHDQ7-UYYZD-J2FGS-FE4LN",function(){function n(e)if(!a.BOOMR!a.BOOMR.version&&!a.BOOMR.snippetExecuted){a.BOOMR=a.BOOMR,a.BOOMR.snippetExecuted=!0;var i,_,o,r=document.createElement("iframe");if(a[t])a[t]("load",n,!1);else if(a.attachEvent)a.attachEvent("onload",n);r.src="javascript:void(0)",r.title="",r.role="presentation",(r.frameElementr).style.cssText="width:0;height:0;border:0;display:none;",o=document.getElementsByTagName("script")[0],o.parentNode.insertBefore(r,o);try_=r.contentWindow.documentcatch(O)i=document.domain,r.src="javascript:var d=document.open();d.domain='"+i+"';void(0);",_=r.contentWindow.document_.open()._l=function()var a=this.createElement("script");if(i)this.domain=i;a.id="boomr-if-as",a.src=e+"RL5JW-PHDQ7-UYYZD-J2FGS-FE4LN",BOOMR_lstart=(new Date).getTime(),this.body.appendChild(a),_.write(" 2ff7e9595c


0 views0 comments

Recent Posts

See All

Comments


!
Widget Didn’t Load
Check your internet and refresh this page.
If that doesn’t work, contact us.
bottom of page