PS script to disable users / Audit and remove Groups / Hide from GAL have bits but need to put it together

Hi All
I am trying to get a script together to run against a specific OU (our disabled Users OU) to make the process of leavers more automated.
I am trying to achieve the 4 main outcomes below
1. Disable User account 
2. Hide from GAL
3. Export users group membership to a file based on SamAccountName
4. Remove users from all groups except domain users
I have some parts of this working from other peoples scripts i have found on the web but need to tie it all together which is proving to be beyond my basic scripting ability
Below is what i have so far, this does disable users / hide from GAL and remove groups however as stated i would really like it to export the group membership to a file before removing them so i have a record should a mistake be made.
$users= get-aduser -Filter {(Enabled -eq "True")} -SearchBase "ou=Disabled Accounts,dc=test2k8,dc=local"
Function RemoveMemberships
param([string]$SAMAccountName)
$user = Get-ADUser $SAMAccountName -properties memberof
$userGroups = $user.memberof
$userGroups | %{get-adgroup $_ | Remove-ADGroupMember -confirm:$false -member $SAMAccountName}
$userGroups = $null
$users | %{RemoveMemberships $_.SAMAccountName}
ForEach ($user in $users)
set-aduser -identity $user.sAMAccountName -Enabled $false -replace @{msExchHideFromAddressLists=$true}
exit
If there is anyone here that can help i would be very grateful
Many Thanks
Nick

Try this:
$Users = get-aduser -Filter {(Enabled -eq "True")} -SearchBase "ou=DisabledAccounts,dc=test2k8,dc=local"
Function Remove-GroupMembership
[CmdletBinding()]
param
[parameter(ValueFromPipeline=$true)]
$Identity
process
if ($Identity -is [string] -or !$Identity.memberof)
$Identity = Get-ADUser $Identity -properties memberof
Write-Verbose -message $Identity.samAccountname
foreach ($Group in $Identity.memberof)
Write-Verbose $Group
Remove-ADGroupMember $Group -confirm:$false -member $Identity
$Users | Remove-GroupMembership -verbose 4> c:\users\mmcnabb\desktop\groups.txt
forEach ($User in $Users)
set-aduser -identity $user.sAMAccountName -Enabled $false -replace @{msExchHideFromAddressLists=$true}
It uses the verbose stream to redirect the groups out to a text file of your choice. Please note this is untested so please use with caution.

Similar Messages

  • How do I connect to Net Flix? I put in my user name and password which work fine with my iMac but not on my Apple TV?

    How do I connect to Net Flix? I put in my user name and password which work fine with my iMac but not on my Apple TV?

    Can you give me a screenshot of the User Accounts window in Control Panel?
    Please create a screenshot by following the guide mentioned at [[How do I create a screenshot of my problem?]].
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. You really help us to visualize the problem.

  • I did everything lllaass suggested and removed most of the itunes related components, but when I tried to remove itunes, I got the message, "The feature you are trying to use is on a network resource that is unavailable" so I was not able to uninstall it.

    I did everything lllaass suggested and removed most of the itunes related components, but when I tried to remove itunes, I got the message, "The feature you are trying to use is on a network resource that is unavailable" so I was not able to uninstall it.

    (1) Download the Windows Installer CleanUp utility installer file (msicuu2.exe) from the following Major Geeks page (use one of the links under the "DOWNLOAD LOCATIONS" thingy on the Major Geeks page).
    http://majorgeeks.com/download.php?det=4459
    Here's a screenshot showing the particular links on the page that you should be clicking:
    After clicking one of the circled links, you should be taken to another page, and after a few seconds you should see a download dialog appear for the msicuu2.exe file. Here's a screenshot of what it looks like for me in Firefox:
    Choose to Save the file. If the dialog box does not appear for you, click the link on the page that says "CLICK HERE IF IT DOES NOT". Here's a screenshot of the page with the relevant link circled:
    When the dialog appears, choose to save the file.
    (2) Go to the Downloads area for your Web browser. Doubleclick the msicuu2.exe file and follow the prompts to install the Windows Installer CleanUp utility. (If you're on a Windows Vista or Windows 7 system and you get a Code 800A0046 error message when doubleclicking the msicuu2.exe file, try instead right-clicking on the msicuu2.exe file and selecting "Run as administrator".)
    (3) In your Start menu click All Programs and then click Windows Install Clean Up. The Windows Installer CleanUp utility window appears, listing software that is currently installed on your computer.
    (4) In the list of programs that appears in CleanUp, select any iTunes entries and click "Remove", as per the following screenshot:
    (5) Quit out of CleanUp, restart the PC and try another iTunes install. Does it go through properly this time?

  • Getting list of all users and their group memberships from Active Directory

    Hi,
    I want to retrieve a list of all the users and their group memberships through JNDI from Active Directory. I am using the following code to achieve this:
    ==================
    import javax.naming.*;
    import java.util.Hashtable;
    import javax.naming.directory.*;
    public class GetUsersGroups{
         public static void main(String[] args){
              String[] attributeNames = {"memberOf"};
              //create an initial directory context
              Hashtable env = new Hashtable();
              env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
              env.put(Context.PROVIDER_URL, "ldap://172.19.1.32:389/");
              env.put(Context.SECURITY_AUTHENTICATION, "simple");
              env.put(Context.SECURITY_PRINCIPAL, "[email protected]");
              env.put(Context.SECURITY_CREDENTIALS, "p8admin");
              try {
                   // Create the initial directory context
                   DirContext ctx = new InitialDirContext(env);     
                   //get all the users list and their group memberships
                   NamingEnumeration contentsEnum = ctx.list("CN=Users,DC=filenetp8,DC=com");
                   while (contentsEnum.hasMore()){
                        NameClassPair ncp = (NameClassPair) contentsEnum.next();
                        String userName = ncp.getName();
                        System.out.println("User: "+userName);
                        try{
                             System.out.println("am here....1");
                             Attributes attrs = ctx.getAttributes(userName, attributeNames); // only asked for one attribute so only one should be returned
                             System.out.println("am here....2");
                             Attribute groupsAttribute = attrs.get(attributeNames[0]); // memberOf
                             System.out.println("-----"+groupsAttribute.size());
                             if (groupsAttribute != null){
                                  // memberOf is a multi valued attribute
                                  for (int i=0; i<groupsAttribute.size(); i++){
                                  // print out each group that user belongs to
                                  System.out.println("MemberOf: "+groupsAttribute.get(i));
                        }catch(NamingException ne){
                        // ignore for now
                   System.err.println("Problem encountered....0000:" + ne);
                   //get all the groups list
              } catch (NamingException e) {
              System.err.println("Problem encountered 1111:" + e);
    =================
    The following exception gets thrown at every user entry:
    User: CN=Administrator
    am here....1
    Problem encountered....0000:javax.naming.NamingException: [LDAP: error code 1 -
    000020D6: SvcErr: DSID-03100690, problem 5012 (DIR_ERROR), data 0
    ]; remaining name 'CN=Administrator'
    I think it gets thrown at this line in the code:
    Attributes attrs = ctx.getAttributes(userName, attributeNames);
    Any idea how to overcome this and where am I wrong?
    Thanks in advance,
    Regards.

    In this sentence:
    Attributes attrs = ctx.getAttributes(userName, attributeNames); // only asked for one attribute so only one should
    It seems Ok when I add "CN=Users,DC=filenetp8,DC=com" after userName, just as
    userName + ",CN=Users,DC=filenetp8,DC=com"
    But I still have some problem with it.
    Hope it will be useful for you.

  • How can I find and remove duplicate photos from my computer?

    How can I find and remove duplicate photos from my computer?

    Terence,
    Yes, the duplicates appear in the iPhoto window. I have folders with same name occuring two or even three times sometimes with exactly the same set of photos (ie photos with the same ID) and sometimes with a limited set of photos. Other  folders appear only once.
    I normally take my MacBook with me if I'm shooting a lot of photos, such as on holiday, and then want to transfer them to my iMac when i get home. Other times I transfer the camera's memory stick directly to my iMac.
    I have great difficulty transferring the photos from my MacBook to my iMac. I don't want to store my photos on my iDisk due to the length of time it takes to upload them.
    Thanks again.
    Simon

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

  • [svn:fx-trunk] 12001: Make List itemEditor work with FTETextInput via textInputClass style and remove unused _itemEditor from Tree .

    Revision: 12001
    Revision: 12001
    Author:   [email protected]
    Date:     2009-11-19 11:47:24 -0800 (Thu, 19 Nov 2009)
    Log Message:
    Make List itemEditor work with FTETextInput via textInputClass style and remove unused _itemEditor from Tree.
    QE notes:
    Doc notes:
    Bugs: SDK24172
    Reviewer: Gordon
    Tests run: checkintests, list tests
    Is noteworthy for integration: no
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/List.as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/Tree.as
        flex/sdk/trunk/frameworks/projects/spark/MXFTEText.css

    This is a duplicate post.  This should be locked to avoid further confusion.
    My CSS wont change
    Nancy O.

  • My daughter has an iphone 5s and I have her old 3GS. She receives all my imessages that I rcv or send to other people. Can anyone advise how to stop this? we have removed the 3gs from her itunes account but it hasn't stopped the issue.

    My daughter has an iphone 5s and I have her old 3GS. She receives all my imessages that I rcv or send to other people. Can anyone advise how to stop this? we have removed the 3gs from her itunes account but it hasn't stopped the issue.

    There are a lot of posts in the forums today with people having problems with iMessage.   There was also a published outage yesterday, so it's possible there are still some issues that may be impacting you both.
    I would just wait it out - I'm sure it will be sorted out soon.

  • [svn:osmf:] 16975: Fix bug FM-964, add media factory item for RTMFP multicast and remove the item from OSMFPlayer

    Revision: 16975
    Revision: 16975
    Author:   [email protected]
    Date:     2010-07-19 15:20:00 -0700 (Mon, 19 Jul 2010)
    Log Message:
    Fix bug FM-964, add media factory item for RTMFP multicast and remove the item from OSMFPlayer
    Ticket Links:
        http://bugs.adobe.com/jira/browse/FM-964
    Modified Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/OSMFPlayer.as
        osmf/trunk/framework/OSMF/org/osmf/media/DefaultMediaFactory.as

    Welcome guy -
    Unless you are using Spry menus as a learning experience, you should move forward to a menus system that will display properly on the millions of portable devices that won't work with Spry which was deprecated 2 years ago.
    Many are using JQuery menus or pure HTML/CSS menus.
    If you wish to continue your Spry for learning experience, we'll be glad to assist; please let us know.
    By the way, your submenus are not showing because you need to add the red value to this rule in your vertical CSS
    ul.MenuBarVertical ul.MenuBarSubmenuVisible{
        width: 220px;
        left: 180px;

  • I remove my device from " find my iphone " but i need to restored

    i remove my device from " find my iphone " but i need to restored

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                         
    If recovery mode does not work try DFU mode.                        
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings        
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: Back up and restore your iOS device with iCloud or iTunes
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload most iTunes purchases by:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store        
    If problem what happens or does not happen and when in the instructions? When you successfully get the iPod in recovery mode and connect to computer iTunes should say it found an iPod in recovery mode.

  • I removed my device from find my iphone but it still won't let me restore. How do I fix this?

    basically i forgot my password. it said "turn off find my ipod"
    i removed my device from find my iphone but it still won't let me restore. How do I fix this?

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                         
    If recovery mode does not work try DFU mode.                        
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings        
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: Back up and restore your iOS device with iCloud or iTunes
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload most iTunes purchases by:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store        
    If problem what happens or does not happen and when in the instructions? When you successfully get the iPod in recovery mode and connect to computer iTunes should say it found an iPod in recovery mode.

  • Old laptop died, got latest itunes on new laptop and recovered all music from external hard drive but ipad not recognised as device when plugged in? Do i reset my ipad2!!!

    Old laptop died, got latest itunes on new laptop and recovered all music from external hard drive but ipad2 not being recognised as a device when plugged in so can't sync? Do i reset my ipad2?!!!! Its only taken 7 months to get to this point.
    My ipad is set to sync via wifi but it is still trying to look for my old laptop which has been trashed..but i have deauthorised it and removed it from my account and still not recognised.
    Please help (an extreme novice to Apple products)

    Sync Your iOS Device with a New Computer Without Losing Data
    http://www.howtogeek.com/104298/sync-your-ios-device-with-a-new-computer-without -losing-data/
    iPad not appearing in iTunes
    http://www.apple.com/support/ipad/assistant/itunes/
    iOS: Device not recognized in iTunes for Mac OS X
    http://support.apple.com/kb/TS1591
    iOS: Device not recognized in iTunes for Windows
    http://support.apple.com/kb/TS1538
    IOS: Syncing with iTunes
    http://support.apple.com/kb/HT1386
    Apple - Support - iPad - Syncing
    http://www.apple.com/support/ipad/syncing/
     Cheers, Tom

  • TS3899 I have set up two email accounts on my iphone4, one with tiscali, my ISP, and the other on gmail. I am able to receive emails on both accounts, and can send emails from my gmail account, but am "Unable to Send Email" from my tiscali (talktalk) acco

    I have set up two email accounts on my iphone4, one with tiscali, my ISP, and the other on gmail. I am able to receive emails on both accounts, and can send emails from my gmail account, but am "Unable to Send Email" from my tiscali (talktalk) account. I get the error message "A copy has been placed in your Outbox. The sender address "name"@tiscali.co.uk was rejected by the server".

    Hi apmichael,
    If you are having issues sending email from one of your mail accounts on your iPhone, you may find the following article helpful:
    iOS: Troubleshooting Mail
    http://support.apple.com/kb/ts3899
    Regards,
    - Brenden

  • Just downloaded Lion and now iMovie won't respond when I try to open it. Even tried deleting the program (since it was an older version) and bought it new from the app store, but still won't respond.

    Just downloaded Lion and now iMovie won't respond when I try to open it. Even tried deleting the program (since it was an older version) and bought it new from the app store, but still won't respond.

    Thanks for this mha007 - I can now open FF with a new profile. Can I copy my settings from the old profile or will this bring over the same problem, maybe a corrupt file. If it would bring the same problem, is there any way I can check which file is corrupt, apart from taking them over one by one?

  • Unable to sync iPad to iMac. Get message 'iPad can't be synced because not enough free space to hold items in iTunes Library'. Only major content is iTunes U stuff. Deleted this on iPad and unticked iTunes U from syncing on iMac but message remains

    Unable to sync iPad to iMac. Get message 'iPad can't be synced because not enough free space to hold items in iTunes Library'. Only major content is iTunes U stuff (lots of videos). Don't download any music or other videos to iPad.
    Deleted iTunesU content on iPad and unticked iTunes U from syncing on iMac but message remains.
    Very frustrating.

    No longer a problem. After leaving a while and trying again the iPad and iMac successfully synced.

Maybe you are looking for

  • How to updgrade from Mac OS 10.3.9 to 10.4 or 10.5?

    Hi, how do i upgrade from Mac OS 10.3.9 to 10.4 or 10.5? (except buying the software) do i have to achieve all my files before? is there any risks of loosing data? would i require to also buy a new Iwork office? or the 2007 version is still applicabl

  • Microsoft office 2003 not working after software update

    I tried opening up my MS Word and Powerpoint programs last night by clicking on their icons.  It did not open.  However, I opened the programs a few weeks ago when I created several documents but now nothing.  But at the same time it does open my exi

  • Link to iTunes  on iWeb

    Is there a way/widget to install so I can add to my iwebsite a link to puchase a song directly from iTunes? It's my own recordings that are for sale on iTunes and i'd like people to be able to immediately go to iTunes and get the songs.

  • Corrupted Control Bar

    In CS4 and CS5, on two different computers (XP and Win7), the same problem happens: In text mode (the T tool active), the opacity and the font size controls on the control bar occasionally get tangled up with each other. It looks like the context-swi

  • Macbook battery, and replacement, won't charge

    I have an early 2008 white macbook. The battery recently stopped charging. The icon on the menubar  reads, "Condition: Replace Now." I installed a new battery and also bought a new mag adapter powercord. Still no luck. The computer runs if the powerc