Created
August 26, 2015 20:33
-
-
Save jrocha/744d8bbd828272adab4c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Log([string]$Details, [ConsoleColor]$Colour) { | |
if ($Colour -eq $null) { | |
$Colour = [ConsoleColor]::White | |
} | |
Write-Host $Details -ForegroundColor $Colour | |
if ( $LogFile -eq "" -or $LogFile -eq $null ) { return } | |
$Details | Out-File $LogFile -Append | |
} | |
Function LogVerbose([string]$Details) { | |
Write-Host $Details | |
if ( $LogFile -eq "" -or $LogFile -eq $null ) { return } | |
$Details | Out-File $LogFile -Append | |
} | |
Function LoadEWSManagedAPI() { | |
# Find and load the managed API | |
if ( ![string]::IsNullOrEmpty($EWSManagedApiPath) ) { | |
if ( { Test-Path $EWSManagedApiPath } ) { | |
Add-Type -Path $EWSManagedApiPath | |
return $true | |
} | |
Write-Host ( [string]::Format("Managed API not found at specified location: {0}", $EWSManagedApiPath) ) -ForegroundColor Yellow | |
} | |
$a = Get-ChildItem -Recurse "C:\Program Files (x86)\Microsoft\Exchange\Web Services" -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Name -eq "Microsoft.Exchange.WebServices.dll" ) } | |
if (!$a) { | |
$a = Get-ChildItem -Recurse "C:\Program Files\Microsoft\Exchange\Web Services" -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Name -eq "Microsoft.Exchange.WebServices.dll" ) } | |
} | |
if ($a) { | |
# Load EWS Managed API | |
Write-Host ([string]::Format("Using managed API {0} found at: {1}", $a.VersionInfo.FileVersion, $a.VersionInfo.FileName)) -ForegroundColor Gray | |
Add-Type -Path $a.VersionInfo.FileName | |
$script:EWSManagedApiPath = $a.VersionInfo.FileName | |
return $true | |
} | |
return $false | |
} | |
Function TrustAllCerts() { | |
<# | |
.SYNOPSIS | |
Set certificate trust policy to trust self-signed certificates (for test servers). | |
#> | |
## Code From http://poshcode.org/624 | |
## Create a compilation environment | |
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider | |
$Compiler=$Provider.CreateCompiler() | |
$Params=New-Object System.CodeDom.Compiler.CompilerParameters | |
$Params.GenerateExecutable=$False | |
$Params.GenerateInMemory=$True | |
$Params.IncludeDebugInformation=$False | |
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null | |
$TASource=@' | |
namespace Local.ToolkitExtensions.Net.CertificatePolicy { | |
public class TrustAll : System.Net.ICertificatePolicy { | |
public TrustAll() | |
{ | |
} | |
public bool CheckValidationResult(System.Net.ServicePoint sp, | |
System.Security.Cryptography.X509Certificates.X509Certificate cert, | |
System.Net.WebRequest req, int problem) | |
{ | |
return true; | |
} | |
} | |
} | |
'@ | |
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource) | |
$TAAssembly=$TAResults.CompiledAssembly | |
## We now create an instance of the TrustAll and attach it to the ServicePointManager | |
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll") | |
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll | |
} | |
function CreateService($targetMailbox) | |
{ | |
# Creates and returns an ExchangeService object to be used to access mailboxes | |
# First of all check to see if we have a service object for this mailbox already | |
if ($script:services -eq $Null) | |
{ | |
$script:services = @{} | |
} | |
if ($script:services.ContainsKey($targetMailbox)) | |
{ | |
return $script:services[$targetMailbox] | |
} | |
# Create new service | |
$exchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1) | |
# Set credentials if specified, or use logged on user. | |
if ($Credentials -ne $Null) | |
{ | |
LogVerbose "Applying given credentials" | |
$exchangeService.Credentials = $Credentials.GetNetworkCredential() | |
} | |
elseif ($Username -and $Password) | |
{ | |
LogVerbose "Applying given credentials for $Username" | |
if ($Domain) | |
{ | |
$exchangeService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($Username,$Password,$Domain) | |
} else { | |
$exchangeService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($Username,$Password) | |
} | |
} | |
else | |
{ | |
LogVerbose "Using default credentials" | |
$exchangeService.UseDefaultCredentials = $true | |
} | |
# Set EWS URL if specified, or use autodiscover if no URL specified. | |
if ($EwsUrl) | |
{ | |
$exchangeService.URL = New-Object Uri($EwsUrl) | |
} | |
else | |
{ | |
try | |
{ | |
LogVerbose "Performing autodiscover for $targetMailbox" | |
if ( $AllowInsecureRedirection ) { | |
$exchangeService.AutodiscoverUrl($targetMailbox, {$True}) | |
} else { | |
$exchangeService.AutodiscoverUrl($targetMailbox) | |
} | |
if ([string]::IsNullOrEmpty($exchangeService.Url)) { | |
Log "$targetMailbox : autodiscover failed" Red | |
return $Null | |
} | |
LogVerbose "EWS Url found: $($exchangeService.Url)" | |
} | |
catch { | |
Log "$targetMailbox : autodiscover failed (catch)" Red | |
} | |
} | |
$exchangeService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $targetMailbox) | |
if (![String]::IsNullOrEmpty($TraceFile)) | |
{ | |
CreateTraceListener $exchangeService | |
$exchangeService.TraceFlags = [Microsoft.Exchange.WebServices.Data.TraceFlags]::All | |
$exchangeService.TraceEnabled = $True | |
} | |
$script:services.Add($targetMailbox, $exchangeService) | |
return $exchangeService | |
} | |
function SaveToDisk($findResults, $targetPath) { | |
ForEach ($itemId in $findResults.Items) { | |
$item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($svc, $itemId.Id, $propSet) | |
$messageId = $item.InternetMessageId.Replace("<", "").Replace(">", "") | |
[io.file]::WriteAllBytes("$targetPath\$messageId.dat", $item.MimeContent.Content) | |
Write-Host "$targetPath\$messageId.dat" | |
# $item.Body | |
} | |
} | |
function Extract($svc, $targetMailbox) { | |
$targetMbx = New-Object Microsoft.Exchange.WebServices.Data.Mailbox( $SourceMailbox ) | |
$propSet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent, [Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::InternetMessageId) | |
$folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail, $sourceMbx ) | |
$junkMail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($svc, $folderId) | |
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(500, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::End) | |
$view.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly) | |
$findResults = $junkMail.FindItems($view) | |
SaveToDisk $findResults "C:\temp\bad" | |
$folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $sourceMbx ) | |
$junkMail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($svc, $folderId) | |
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(500, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::End) | |
$view.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly) | |
$searchQuery = "received:(NOT today AND NOT NOT yesterday AND last week) AND size:<=30000" | |
$findResults = $junkMail.FindItems($searchQuery, $view) | |
SaveToDisk $findResults "C:\temp\good" | |
} | |
function ProcessMailbox($targetMailbox) { | |
$svc = CreateService $targetMailbox | |
Extract $svc $targetMailbox | |
} | |
$api = LoadEWSManagedAPI | |
$allBoxes = Get-Mailbox | |
ForEach ($box in $allBoxes) { | |
ProcessMailbox $box.PrimarySmtpAddress | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment