Powershell script to apply retention policy by group

I am working on a script to apply a specific retention policy to individuals who are members of a particular group, another for rooms, and yet another to everyone else.  Below is what I'm working with:
I run into an error that states "Pipeline not executed because a pipeline is already executing..." and the retention policy doesn't get set.  can someone tell me where I've gone wrong here?  Or perhaps an easier solution?
#Check entire domain
Set-ADServerSettings -ViewEntireForest $true
#Active Directory Group
$Group = [ADSI]("LDAP://CN=EXCHANGE_DISABLE_PURGE,OU=EXCHANGE ACCOUNTS,DC=domain,dc=com")
#Enum Group Members and set equal to array
$Grouplist = $Group.member
#do loop varaible setup
$GroupLength=$Grouplist.count
$GroupArrayLength=$GroupLength - 1
$GroupCount = 0
$Userlist= @(0..$GroupArrayLength)
$UsersDN=@(0..$GroupArrayLength)
#do loop to disable purge policy for all array members
do {
 $Userlist[$GroupCount] = [ADSI]("LDAP://" + $Grouplist[$GroupCount])
 $UsersDN[$GroupCount] = $userlist[$GroupCount].distinguishedname
 $GroupLength=$GroupLength - 1
 $GroupCount++
until ($GroupLength -eq 0)
Get-mailbox -database db01 -resultsize Unlimited | foreach-object{
 if ([string[]]$UsersDN -contains $_.DistinguishedName){
  if ($_.RetentionPolicy -ne "NoPurge"){
   set-mailbox $_ -RetentionPolicy NoPurge
   write-host("Applied - No Purge Policy to "+$_.DisplayName) -ForeGroundColor Green
 elseif (($_.RecipientTypeDetails -eq "RoomMailBox") -or ($_.RecipientTypeDetails -eq "EquipmentMailbox")){
  if ($_.RetentionPolicy -ne "Default Resource/Equipment Policy"){
   set-mailbox -identity $_ -RetentionPolicy "Default Resource/Equipment Policy"
   write-host("Applied - Default Resource/Equipment Policy to "+$_.DisplayName) -ForeGroundColor Green
 else{
  if ($_.RetentionPolicy -ne "180DayDefault"){
   set-mailbox -identity $_ -RetentionPolicy "180DayDefault"
   write-host("Applied - Default 180 Day Purge Policy to "+$_.DisplayName) -ForeGroundColor Green

Hi,
In order to resolve this issue more efficiently, I recommend you post to the Script forum which is staffed by more experts specializing in this kind of problems. You might get a better answer there. Thanks for understanding.
http://social.technet.microsoft.com/Forums/scriptcenter/en-US/home?category=scripting
Best regards,
Belinda
Belinda Ma
TechNet Community Support

Similar Messages

  • Powershell script to apply retention policy by group - Exchange 2010

    I am working on a script to apply a specific retention policy to individuals who are members of a particular group, another for rooms, and yet another to everyone else.  Below is what I'm working with:
    I run into an error that states "Pipeline not executed because a pipeline is already executing..." and the retention policy doesn't get set.  can someone tell me where I've gone wrong here?  Or perhaps an easier solution?
    #Check entire domain
    Set-ADServerSettings -ViewEntireForest $true
    #Active Directory Group
    $Group = [ADSI]("LDAP://CN=EXCHANGE_DISABLE_PURGE,OU=EXCHANGE ACCOUNTS,DC=domain,dc=com")
    #Enum Group Members and set equal to array
    $Grouplist = $Group.member
    #do loop varaible setup
    $GroupLength=$Grouplist.count
    $GroupArrayLength=$GroupLength - 1
    $GroupCount = 0
    $Userlist= @(0..$GroupArrayLength)
    $UsersDN=@(0..$GroupArrayLength)
    #do loop to disable purge policy for all array members
    do {
    $Userlist[$GroupCount] = [ADSI]("LDAP://" + $Grouplist[$GroupCount])
    $UsersDN[$GroupCount] = $userlist[$GroupCount].distinguishedname
    $GroupLength=$GroupLength - 1
    $GroupCount++
    until ($GroupLength -eq 0)
    Get-mailbox -database db01 -resultsize Unlimited | foreach-object{
    if ([string[]]$UsersDN -contains $_.DistinguishedName){
      if ($_.RetentionPolicy -ne "NoPurge"){
       set-mailbox $_ -RetentionPolicy NoPurge
       write-host("Applied - No Purge Policy to "+$_.DisplayName) -ForeGroundColor Green
    elseif (($_.RecipientTypeDetails -eq "RoomMailBox") -or ($_.RecipientTypeDetails -eq "EquipmentMailbox")){
      if ($_.RetentionPolicy -ne "Default Resource/Equipment Policy"){
       set-mailbox -identity $_ -RetentionPolicy "Default Resource/Equipment Policy"
       write-host("Applied - Default Resource/Equipment Policy to "+$_.DisplayName) -ForeGroundColor Green
    else{
      if ($_.RetentionPolicy -ne "180DayDefault"){
       set-mailbox -identity $_ -RetentionPolicy "180DayDefault"
       write-host("Applied - Default 180 Day Purge Policy to "+$_.DisplayName) -ForeGroundColor Green

    Hi,
    I generally get all mailboxes first and then use a foreach loop to process each one. This usually seems to fix the error about concurrent pipelines.
    $mbxs = Get-Mailbox
    foreach ($mbx in $mbxs) {
    # Do stuff here on each mailbox
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • Script set to auto apply Retention policy to all new mailbox created and run everyday

      Script to set auto apply Retention policy to all new mailbox created and run everyday on Exchange 2007 , 2010 , and 2013.
     Could you please help me with the script will rename the policy name please help me with script..
     Thanks,
     Chandu

    Hi Chandu,
    Have you find the solution finally? Have you tried Pavan's suggestion?
    Sorry for my lacking of code and script. If your requirement still haven't been achieved, I suggest we can ask a question in Exchange Development forum and Script Center for more professional suggestion:
    Microsoft Exchange Development forum
    http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/threads
    Script Center
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/home?forum=ITCG
    Regards,
    Winnie Liang
    TechNet Community Support

  • Powershell script: to get the AD Security Group Name

    I need PowerShell script that takes input: AD Security Group Name and loop
    through all web applications and their content in the farm to know where this particular group is used.

    hi
    AD groups are represented in Sharepoint as SPUser object with
    SPUser.IsDomainGroup set to true. I.e. you may use the same script which is used for users:
    Powershell script to find permissions for a specific user.
    Blog - http://sadomovalex.blogspot.com
    Dynamic CAML queries via C# - http://camlex.codeplex.com

  • Apply Retention Policy to All New Mailboxes

    I have created a retention policy tag to “Delete and Allow Recovery” after 14 days of all items in the “Deleted Items” folder.
    I then created a Retention Policy to apply the tag. I see using the EMS I can run a command “Get-Mailbox | Set-Mailbox –RetentionPolicy “Empty Trash” to apply to all existing mailboxes but how do I apply this to all new mailboxes as
    well?
    I see a posting at
    http://www.proexchange.be/blogs/exchange2010/archive/2011/08/31/using-the-scripting-agent-to-automate-some-basic-housekeeping-tasks.aspx
    that describes using the Scripting Agent to automate this processes but it seems overkill for my simple requirement. If I go this route does this need to be applied to each Exchange Server? Is this the only way or is there a simpler way to apply a recipient
    policy to all existing and future mailboxes?
    Pacerfan9

    Hi,
    Any updates on this issue?
    If anything is unclear, please feel free to let us know. 
    Thanks,
    Evan Liu
    TechNet Subscriber Support
    in forum
    If you have any feedback on our support, please contact
    [email protected]  
    Evan Liu
    TechNet Community Support

  • Powershell script to Get members of AD group members with first, last, email address

    I'm running a powershell script to retrieve AD users from a specific AD group and pipe specific attributes to a csv file. The script is working perfectly except for one detail. I want the script to ignore any users who have a null value in any of the values
    I'm piping to the spreadsheet. Meaning that if any of the users found in the queried groups have a null value in the attributes givenname, sn or mail, ignore the user and do not pipe to the csv.
    Get-ADGroupMember -identity adgroup -recursive | get-adobject -Properties givenname,sn,mail | select givenname,sn,mail |export-csv -path c:\powershell\groupmembers.csv
    –NoTypeInformation

    Hi,
    You can pipe your user objects through ForEach-Object and then use if to verify all three properties exist. If so, output the object. If not, move to the next object. After you've processed all user objects, then pipe into Export-Csv.
    EDIT: See below.
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • Applying retention Policy tags to inbox in Exchange Server 2010

    I configured a Journal inbox in Exchange server 2010. I would like to configure a retention policy of 30 days so after a month all emails will be deleted from the Inbox of the Journal account. I configured the retention policy but messages
    would never get deleted.

    Hi,
    Based on the description, you created a retention policy tag, the type was Inbox, added this tag to a retention policy and then applied this policy to the journal mailbox. However, this retention policy didn't work.
    For this issue, first, I recommend you check if this tag is disabled. Besides, please check the application log to see if the Managed Folder Assistant has processed this journal mailbox. You can force the Managed Folder Assistant to apply the policy manually
    by running the Start-ManagedFolderAssistant command.
    If you have checked the above, I suggest you change the Action that retention policy tag performs to check the result.
    Best regards,
    Belinda
    Belinda Ma
    TechNet Community Support

  • Retention Policy problems

    Hello,
    i am trying to set up the automated archival of Exchange 2013.
    So that e-mails, which are older than e.g. 1 year are get moved to the archive.
    What i did:
    1.  Create a archive database
    2.  Create a archive mailbox
    3.  Create a retention tag
    4.  Create a retention policy
    4.1 Including a Default tag and a personal tag
    5. Linked it to a user: Set-mailbox “administrator” -RetentionPolicy "Movetoarchivpolicy"
    6. Checked the User: Get-Mailbox “administrator” | Select RetentionPolicy
    7. Started the ManagedFolderAssistant: Start-ManagedFolderAssistant -Identity “administrator”
    8. But all Mails stayed in the Mailbox
    9. I tryed to manually assign a retention tag to a Mail, but I dont have the button. (OWA and Outlook 2013 ProPlus).
    Have anyone an idea, why i don't have the "assign policy" button?
    And why all Mails stay in the Mailbox?
    Thanks,

    Hi,
    Event 9018 means that Mailbox Assistant has processed the mailbox successfully. But retention policy still didn't work.
    I recommend you create a new test mailbox and apply retention policy to this new mailbox to check if it works.
    And please increase diagnostic logging level for MRM, and then monitor application log to check if there is any related events.
    Best regards,
    Belinda
    Belinda Ma
    TechNet Community Support

  • CONFIGURE RETENTION POLICY TO REDUNDANCY 0

    Our database is 11g R2, below is our RMAN script
    Presently our retention policy is 1, so 1 backup is retained along with the current backup.
    I Just want to have 1 backup, i.e RMAN should take the backup and delete the old bacup.
    Will it work if i change the retention policy to 0 ?
    RUN
      ALLOCATE CHANNEL ch1 DEVICE TYPE DISK;
      ALLOCATE CHANNEL ch2 DEVICE TYPE DISK;
      ALLOCATE CHANNEL ch3 DEVICE TYPE DISK;
      DELETE NOPROMPT OBSOLETE;
      BACKUP DATABASE INCLUDE CURRENT CONTROLFILE format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
      SQL "ALTER SYSTEM ARCHIVE LOG CURRENT";
      BACKUP ARCHIVELOG ALL DELETE INPUT format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
    RMAN> show all
    2> ;
    using target database control file instead of recovery catalog
    CONFIGURE RETENTION POLICY TO REDUNDANCY 1;
    CONFIGURE BACKUP OPTIMIZATION OFF; # defaultEdited by: user10243788 on Apr 24, 2012 1:14 AM

    user10243788 wrote:
    Our database is 11g R2, below is our RMAN script
    Presently our retention policy is 1, so 1 backup is retained along with the current backup.
    I Just want to have 1 backup, i.e RMAN should take the backup and delete the old bacup.
    Will it work if i change the retention policy to 0 ?You cannot set the retention policy to redundancy 0 because redundancy count must be greater than zero.
    >
    RUN
    ALLOCATE CHANNEL ch1 DEVICE TYPE DISK;
    ALLOCATE CHANNEL ch2 DEVICE TYPE DISK;
    ALLOCATE CHANNEL ch3 DEVICE TYPE DISK;
    DELETE NOPROMPT OBSOLETE;
    BACKUP DATABASE INCLUDE CURRENT CONTROLFILE format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
    SQL "ALTER SYSTEM ARCHIVE LOG CURRENT";
    BACKUP ARCHIVELOG ALL DELETE INPUT format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
    }Just switch the order of operation:
    use
    BACKUP DATABASE INCLUDE CURRENT CONTROLFILE format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
    DELETE NOPROMPT OBSOLETE;
    instead of
    DELETE NOPROMPT OBSOLETE;
    BACKUP DATABASE INCLUDE CURRENT CONTROLFILE format 'G:\Oracle\flash_recovery_area\BACKUPSET\tmp\rman_backup\df_%d_%s_%p_%T';
    You can also exclude the operation SQL "ALTER SYSTEM ARCHIVE LOG CURRENT" because BACKUP ARCHIVELOG ALL implicitly switch logfile before archiving.

  • C an you display set retention policy?

    Is there a way for a Outlook client to display the current applied retention policy for all items in a folder? I know it is displayed on each item, and I looked for a column to add but didn't see anything applicable.
    This is a request from staff that have large mailboxes that are just starting to use MRM.
    Stunpals - Disclaimer: This posting is provided "AS IS" with no warranties.

    Hi,
    DPTs apply to untagged mailbox items in the entire mailbox. Untagged items are mailbox items that don't already have a retention tag applied, either by inheritance from the folder in which they're located or by the user.
    There is no way to list all items that have the DPT policy applied either.
    Best regards,
    Belinda Ma
    TechNet Community Support

  • Hit with Virus that executed via PowerShell Scripting. Can I disable Powershell on my network via Group Policy and what implications does that have for me.

    Our network was hit recently with virus previously unknown, O97M.Crigent.  It is a nasty Macro virus that targets Microsoft Office Documents & Spreadsheets and uses a combination of Macros and Scripts via Powershell. 
    How do I disable PowerShell scripting via Group Policy?
    Will this raise any issues such as random application or network failures or other issues?
    Can I apply it to the entire domain or should I be selective and only apply it to the workstations?
    Network Summary: Windows 2008 Active Directoy Server, 75% Windows 7, 25% Windows XP workstations.
    DouglasOfSanMarcos

    Disabling Windows PowerShell can be done with GPO:
    Computer Configuration | Administrative Templates | Windows Components | Windows PowerShell
    From GPO Description: "This setting exists under both "Computer Configuration" and "User Configuration" in the group policy editor. The "Computer Configuration" has precedence over "User Configuration."
    By default this option is restricted any way on computers.
    I would be very selective when apply it at all:
    Workstations - I would apply to test group of workstations first, just to see that there are no side effects before applying to all computers. 
    Server - I wouldn't apply it at all. I have seen too many issues when setting this policy on Exchange and other systems.
     If you are using a Group Policy to define a PowerShell logon, logoff or computer script, that script will disregard any execution policy set locally or through a GPO.
    http://4sysops.com/archives/set-powershell-execution-policy-with-group-policy/
    http://technet.microsoft.com/en-us/library/hh849812.aspx
    Please take a moment to Vote as Helpful and/or Mark as Answer where applicable. Thanks.

  • How can I setup a scheduled task to run a Powershell Script delivered as a Group Policy Preference

    I have a Powershell script I want to run only once when a user logs onto their system. This script would move all the PST files from the Local drive and the Home drive to a folder location within the users profile. I wanted to run this as a Windows 7 Scheduled Task using Group Policy Preferences. How can I get this to happen short of a logon script? I have updated all the machines to WMF 4.0 so could I use a Scheduled Job instead? I wanted to run the script as the logon user but elevated.#Start Outlook and Disconnect attached PST files.
    $Outlook = New-Object -ComObject Outlook.Application
    $namespace = $outlook.getnamespace("MAPI")
    $folder = $namespace.GetDefaultFolder("olFolderInbox")
    $explorer = $folder.GetExplorer()
    $explorer.Display()
    $myArray= @()
    $outlook.Session.Stores | where{ ($_.FilePath -like'*.PST') } | foreach{[array]$myArray+= $_.FilePath}
    for
    ($x=0;$x-le$myArray.length-1;$x++)
    $PSTPath= $myArray[$x]
    $PST= $namespace.Stores | ?{$_.FilePath -like$PSTPath}
    $PSTRoot= $PST.GetRootFolder() #Get Root Folder name of PST
    $PSTFolder= $Namespace.Folders.Item($PSTRoot.Name) #Bind to PST for disconnection
    $Namespace.GetType().InvokeMember('RemoveStore',[System.Reflection.BindingFlags]::InvokeMethod,$null,$Namespace,($PSTFolder)) #Disconnect .PST
    #Move All PST files to the default location while deleting the PST files from their original location.
    $SourceList = ("$env:SystemDrive", "$env:HOMEDRIVE")
    $Destination = ("$env:USERPROFILE\MyOutlookFiles")
    (Get-ChildItem -Path $SourceList -Recurse -Filter *.PST) | Move-Item -Destination $Destination
    #Attach all PST files from the default location.
    Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace("MAPI")
    dir “$env:USERPROFILE\MyOutlookFiles\*.pst” | % { $namespace.AddStore($_.FullName) }

    Mike,
    I do not understand what appears to be a regular expression above. I did add the PowerShell script to the HKCU RunOnce Key as suggested.
    Windows Registry Editor Version 5.00
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -noprofile -sta -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File "C:\scripts\Windows PowerShell\Move-PST.ps1"
     I'm delivering this using Group Policy Preferences. It seems to fail or time out when run because the behavior is different if I run the script from within the PowerShell IDE. I added the parameters to the script and will try it again in the morning.

  • How to force group policy update remotely in a bunch of desktops(computers name in a textfile) by using powershell script?

    Hi,
    I want to force group policy on a collection of computers remotely.The name of computers can be stored in a text file.
    By using this info. (about computer names) , Could you please guide me writing a Powershell script for this.
    Thanks in advance.
    Daya

    This requires that PSRemoting is enabled in your environment.
    $Computers = Get-Content -Path 'C:\computers.txt'
    Invoke-Command -ComputerName $Computers -ScriptBlock {
    GPUpdate /Force

  • Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Sales Group then add to Distribution list based on Region

    Hey Scripting Guys,
    I have been in and out of Powershell last few years, not that great at it tbh !!! I'm looking for advice on how I can as in Title, Create a Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Group then add to Distribution
    list based on Region/Country
    I was thinking along the lines of get-aduser -LDAPFilter "(department=SALES France) and adding a where clause for country.
    Any help would be great.
    Dec

    So I have tried a few variations but get errors on both 
    get-aduser -LDAPFilter "(&(department=SALES)(c=us))" | Add-ADPrincipalGroupMembership -MemberOf "testgroup"
    get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADGroupMember -identity "testgroup"
    Add-ADPrincipalGroupMembership : Object reference not set to an instance of an
    object.
    At line:1 char:86
    + get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADPrincipalGroupMe
    mbership <<<< -MemberOf "testgroup"
    + CategoryInfo : NotSpecified: (:) [Add-ADPrincipalGroupMembershi
    p], NullReferenceException
    + FullyQualifiedErrorId : Object reference not set to an instance of an ob
    ject.,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMem
    bership

  • Powershell script for security groups and users for multiple share folders

    Hi scripting team,
    I need your help with powershell script for the below queries 
    1. List out the security groups for more than one server share path and output it to a file ( csv ) 
    For eg.
    If the are are two share paths 
    \\servername\foldermain\folder1
    \\servername\foldermain\folder2
    So I needs the list of security groups for each share path
    And the output needs to be under each any every path.
    2. Grab the users belongs to main security groups and it nested groups for more than one security group and listed the users under each and every group. No need to display nested groups. Just users belongs to main group and users under nested.
    Your teams help is much appreciated 
    Thank you.
    Thilochana kumararatne

    Hi Braham,
    Thanks for your quick reply.
    Are we able to do this on two stage method
    1. grab the security groups from the share paths
    if can grab the share path from a separate txt file than copying it to the <your path> location
    so i can modify the txt file
    once run the script
    if can the output like below to a CSV file
    \\servername\foldermain\folder1group 1group 2group 3\\servername\foldermain\folder2group 1group 2group 3then i know which groups belongs to which share paththen i can remove the duplicate groups and keep the common groups to grab the users belongs to itso with the second script same as the first copy the security groups to a txt file and the out put as below.what I needs is the users full name and the samaccount name ( user id )group 1user1user2user3
    group 2user1user2user3looking forward your help on thisThank you.Thilo

Maybe you are looking for

  • Cannot send or receive email using Thunderbird, but can get it just fine on Verizon server.

    Every time Mozilla/Thunderbird does a major upgrade I have a problem with sending and receiving my email. When trying to send an email, I get the message: "An error occurred while sending mail. The mail server responded: 5.7.1 Missing or literal doma

  • Why can't I download "Adobe InDesign CS6: JavaScript" documentation?

    I am using IE that came with Windows 8 on a Lenovo N581 computer, and Adobe Acrobat XI Pro Version 11.0.2. When I click on the link: vhttp://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/indesign/sdk/cs6/scri pting/InDesign_ScriptingG

  • Flat file upload: constans in TRs?

    Hi, I am having a flat file, which has only limited fields, where as the requirement is to upload all the fields which are relevant! However,  for the remaing fields which are relevant are all constants! In a case such as the above said, can we have

  • Size of Custom Still Image Transcoding Settings

    I need Custom Still Images, but want them not to exceed 40kb in size. Is there any way to control the size of a custom Still Image?

  • Redundent Namespace Problem

    I am working on creating SOAP messages by using my own serialization for non-built-in type on WLS 8.1 SP4. I followed the specs by implementing the following methods. public void serialize(Object obj,XMLName name,XMLOutputStream writer,SerializationC