Wednesday 20 November 2013

Powershell. Get 'Email Quota', 'Password Expire' from Exchange in Active Directory.



Task: collect data about group of people from domain:
  • qoute size;
  • max qoute for e-mail (Exchange);
  • count of the days when password will be expired;
Information about users need to keep in XML file.
Here is example of XML file:

<?xml version="1.0"?>
<tree>
<sender id="yourEmail1@domain.net">
  <filename id="firstfile.out">
    <account>Igor.Pa</account>
    <account>Ka.G</account>
    <account>Alex.Kir</account>
    <account>Les.Samyl</account>
    <account>Serg.Klov</account>
    <account>Alex.Doro</account>
  </filename>
  <filename id="secondfile.out">
   <account>Serg.Kolo</account>
   <account>Serg.Berez</account>
   <account>Irena.Kolots</account>
   <account>Elena.Venko</account>
  </filename>
</sender>
</tree>

Those tags used another program that collect data from powershell script (below), create Excel file (tag <filename>) and send to customer email (tag <sender>). So for now we'll use only tag <account> in cycle

Developed and tested in Windows Server 2008 R2.

  1. Create function that will get list of the users ($accounts) and file name where it will be save ($filename).
  2. We should to create parser for our XML file.
Create function

function getAccountData {

param ([string]$account, [string]$filename)

#for using this package, you need to download Quest.ActiveRoles.ADManagement

Add-PSSnapin Quest.ActiveRoles.ADManagement;
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://KV-MBX-02.YOURDOMAIN.COM/PowerShell/ -Authentication Kerberos;
Import-PSSession $s;

[string]$strProhibit = 'Could not get ProhibitQuota'
[string]$strTotal = 'Could not get TotalSize'

$user = Get-QADUser -Identity $account
$mailbox = $user.Mail
$prohibitQuota = Get-Mailbox -Identity $mailbox | select ProhibitSendQuota
$strProhibit = $prohibitQuota.ProhibitSendQuota.Substring(0, $prohibitQuota.ProhibitSendQuota.IndexOf("("));
$totalSize = Get-MailboxStatistics -Identity $mailbox | select TotalItemSize
$strTotal = $totalSize.TotalItemSize.Substring(0, $totalSize.TotalItemSize.IndexOf("("));
$passexp = $user.PasswordExpires - (Get-Date)
$name = $user.DisplayName
$post = $user.Title
$day = $passexp.Days
[string]$returnStr = $name + ';' + $post + ';' + $mailbox + ';' + $strProhibit + ';' + $strTotal + ';' + $day;
Remove-PSSnapin -Name 'Quest.ActiveRoles.ADManagement'; get-pssession | remove-pssession | Where-Object {$_.ConfigurationName -like 'Microsoft.Exchange' }
# $returnStr | Out-File $filename -append;
$returnStr >> $filename;

}

XML parser

[xml] $xml = Get-Content D:\data.xml
$filenames = $xml.tree.sender.filename
foreach($filename in $filenames) { 
$file = $filename.id;
$nodes = $filename.ChildNodes;
foreach($node in $nodes) {
getAccountData -account $node -filename $file
}
}