I need to automate applying exchange 2010 retention policy on mailboxes that have been created within 7 days. But i also need to exclude any non-US based servers as these are managed by IT overseas.
This is the preface to my script that allows for connection to exchange without any human interaction. Tis way i can schedule this in windows.
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}
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://munprdcasht04.exchange.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
import-PSSession $Session
This is my current code to return mailboxes created within 7 days
Get-Mailbox -ResultSize Unlimited| Where-Object {
($_.WhenCreated –ge ((Get-Date).Adddays(-7)))} |
ft -auto Name,WhenCreated,Retentionpolicy,servername
This works for me but when i add a operator to limit mailboxes on specific servers, the command completes but does not print any results so I'm assuming there are 0 matching records.
Get-Mailbox -ResultSize Unlimited| Where-Object {
($_.WhenCreated –ge ((Get-Date).Adddays(-7))) -and
($_.ServerName -contains "munprdmbxa") |
ft -auto Name,WhenCreated,Retentionpolicy,servername
I haven't yet looked into actually enabling the retention policy as i am just trying to return my target data prior to diving into that adventure. I appreciate any help.
-contains
in powershell returns True
only when a string is exact matched. It acts more like -eq
on a single string but also has ability to determine if an element is contained in a set.
e.g
$test = "aaa"
$test -contains "aaa"
$test = "aaa","bbb","ccc"
$test -contains "aaa"
The two above would return True
, however, it would not return true for a sub-string and wild card doesn't work with it.
$test = "aaa.domain.com"
$test -contains "aaa"
$test = "aaa.domain.com"
$test -contains "*aaa*"
would return False
Thus if the server name is FQDN with domain suffix etc, the string would not be an exact match. If you use -like
operation instead, you can match a subset of string within the given string with wildcard:
e.g:
$test = "aaa.domain.com"
$test -like "*aa*"
$test = "aaa.domain.com"
$test -like "aa*.com"
Will both return True
Thus using -like
operator would more likely to avoid false negative results.