My Goal is to apply a retention policy to newly created mailboxes. Details from previous article here.
My Current Script code is located here for easy readability or below:
# Get Start Time for script timer
$startDTM = (Get-Date)
#Authenticate using cached credentials or re-prompt for credentials.
if (Test-Path C:\temp\mycred.xml) {
$UserCredential = Import-CliXML C:\temp\mycred.xml}
else{
Get-Credential | Export-CliXml C:\temp\mycred.xml
$UserCredential = Import-CliXML C:\temp\mycred.xml}
#Connect to Exchange Server
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://munprdcasht04.exchange.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session
#returns alias' for mailboxes where creation date is <= 7 days and
#resides on "ABC" or "DEF" server and has no retention policy applied
$NeedsRetentions = (Get-Mailbox -ResultSize Unlimited| Where-Object {
($_.WhenCreated –ge ((Get-Date).Adddays(-7))) -and
(($_.ServerName -like "*munprdmbxa*") -or ($_.ServerName -like "*wauprdexa*")) -and
($_.retentionpolicy -ne "PurgeDeletedItemsFolder_60days")} |
ft -auto alias)
ForEach ($NeedsRetention in $NeedsRetentions){
set-mailbox -Identity $NeedsRetention -RetentionPolicy "PurgeDeletedItemsFolder_60days"
}
# Get End Time
$endDTM = (Get-Date)
# Echo Time elapsed
"Elapsed Time: $(($endDTM-$startDTM).totalseconds) seconds"
When I echo the $NeedsRetentions
i receive the list of AD users that i need to apply a retention policy to. But for some reason, when i loop through the the variable list with the below loop it errors out saying that the -Identity is no valid.
ForEach ($NeedsRetention in $NeedsRetentions){
set-mailbox -Identity $NeedsRetention -RetentionPolicy "PurgeDeletedItemsFolder_60days"
}
To troubleshoot i reduced the loop to this in order to display the individual usernames being affected by the script:
ForEach ($NeedsRetention in $NeedsRetentions){
[System.Windows.Forms.MessageBox]::Show($NeedsRetention)
}
Doing this causes a message box to show up for every line in the variable but the string seems to be empty and thus the default message shows up on the message box.
Any ideas why $NeedsRetention
isn't passing correctly into my loop task?