Search code examples
powershellexchange-server-2010

Adding if condition into get-mailbox command


I have a PowerShell script to show which mailboxes do not have the Exchange Retention Policy applied. The script works well, but I cannot figure out how to add an if condition that if all mailboxes do have the Retention Policy applied, then the following statement "Master Policy applied to all Mailboxes" is added to the text file.

Get-Mailbox -OrganizationalUnit "Users*" -ResultSize Unlimited -filter {RetentionPolicy -eq $null} |
  where {$_.RecipientTypeDetails -eq 'UserMailbox'} |
  select Alias > c:\retention.txt

Solution

  • Collect the results of Get-Mailbox in a variable:

    $mailboxes = Get-Mailbox -OrganizationalUnit "Users*" -ResultSize Unlimited `
                   -Filter {RetentionPolicy -eq $null} |
                   ? {$_.RecipientTypeDetails -eq 'UserMailbox'} | select Alias
    

    then check if the result is $null (no matches found) and create the output accordingly:

    $outfile = 'C:\retention.txt'
    if ($mailboxes -ne $null) {
      $mailboxes > $outfile
    } else {
      'Master Policy applied to all Mailboxes' > $outfile
    }
    

    Replace > with >> if you want to append to the file.