Powershell Scripts

On site phone directory.

This script will pull information from Active Directory and format it into a phone directory

import-module activedirectory

$d = Get-Date -Format dd.MMM.yyyy

$a = "<style type=text/css>"
$a = $a + "body {background-color:white; font-family: arial; font-size: 0.8em;}"
$a = $a + "table {border-width: 1px; border-style: none; border-color: white; border-collapse: collapse;}"
$a = $a + "th {border-bottom: solid 1px black;}"
$a = $a + "tr:nth-child(odd) {background: #d3d3d3; }"
$a = $a + "td {padding: 3px;}"
$a = $a + ".footer {font-size: 0.7em;}"
$a = $a + "</style>"

$Pre = "<font size=4>Phone Directory - $d</font size>"
$Post = "<font size=1>Uncontrolled when Printed</font size>"

Get-ADUser -filter {OfficePhone -like '*' } -Properties sn, GivenName, OfficePhone, Department, Title |
    Select-Object sn, GivenName, OfficePhone, Department, Title |
    Sort-Object sn |
    ConvertTo-Html -head $a -pre $Pre -Post $Post|
    Out-File c:\temp\phones.html

invoke-expression c:\temp\phones.html

User count per OU

A good way for tracking accounts

Import-Module ActiveDirectory

$BaseOU = "OU=Mt Alex Users,OU=Mt Alex Hospital,DC=mtalexhosp,DC=vic,DC=gov,DC=au"
$DNs = (Get-ADOrganizationalUnit -Filter * –SearchBase $BaseOU | `
    Select DistinguishedName)
”” | out-file c:\temp\count.txt
foreach ($DN in $DNs) {
    $DN | Out-File C:\temp\count.txt -append
    (get-aduser -filter * -SearchBase $DN.DistinguishedName).count | `
        Out-File c:\temp\count.txt -append
}

Exchange onsite email deletion tool

If you are running an onsite Exchange, this tool can be handy to remove specific emails that may have been missed by SPAM filters.

The logged in account needs to be a member of a group that has access to all mailboxes.

Change the Search Term to the Subject line you are look for, and the Mailbox name to the account you need to search.

As written, this script will search all mailboxes and email the results to the account that is running the script. This is a good way to verify the settings are correct prior to committing to deleting the emails.

$Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://chex01.mtalexhosp.vic.gov.au/powershell -Authentication Kerberos
Import-PSSession $Session

get-Mailbox | search-mailbox -searchquery 'subject:"Search Term" and to:"Mailbox name"' -Logonly -LogLevel Full -Targetmailbox pdigby -Targetfolder "Inbox"

Remove-PSSession $Session

When you are ready to delete the emails, use this script.

$Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://chex01.mtalexhosp.vic.gov.au/powershell -Authentication Kerberos
Import-PSSession $Session

get-Mailbox | search-mailbox -searchquery 'subject:"Search Term" and to:"Mailbox name"' -DeleteContent

Remove-PSSession $Session