Using SHA512 SSL certs with Exchange 2013 on Windows Server 2012 R2 breaks TLS at lower OS rollup levels

We use and internal certificates in my company for Exchange 2013 and recently we employed a company wide mandate to move all internal SSL certificates from SHA1 to SHA512. Our current company patching policy is to apply security patches and only install other patches on an as needed basis. When the time came to renew our SHA1 cert for Exchange 2013 we discovered that SMTP fails when using TLS 1.2 with a SHA512 certificate on windows 2012 R2 (and possibly Server 2008 R2).  There are two options to fix this situation

  1. Install the August 2014 update rollup which enables SHA512 for TLS 1.2
  2. Disable TLS 1.2 via the registry, this forces TLS 1.1 (a weaker protocol) and also breaks windows update
    1. Over all this a solution that should be avoided, but it’s nice to know it works in a pinch

I’ve tested both successfully in my environment and in the end we went with the update.

Posted in Exchange, Exchange 2013 | Leave a comment

Email messages with a blank X-OriginatorOrg header will repeatedly crash the FrontEndTransport Service in EX2013 CU8+

My company recently ran into this issue 2 weeks ago and confirmed with MS that it affects Exchange 2013 CU8, CU9, and CU10 (Exchange 2016 is fine). Basically any message that contains an X-OriginatorOrg header with a null or just white spaces will cause The FrontEndTransport Service to Crash. As long as that header contains any other info it’s fine.
Here is an example of what the message would look like

From: "Student Loan Notice"
MIME-Version: 1.0
To:
Subject: Forgiving Student Loans is possible
Content-Language: en-us
X-Originating-IP: 162.253.55.77
X-OriginatorOrg:
Content-Type: text/plain; charset=ISO-8859-1

Message body

Once this message is received by the FrontEndTransport service the following two event logs entries will occur. Once stating a messages with an invalid SMTP domain was found

Log Name: Application
Source: MSExchangeFrontEndTransport
Event ID: 1033
Task Category: SmtpReceive
Level: Error
Keywords: Classic
User: N/A
Computer: XCH201301.contoso.com
Description:
An exception was thrown while processing data from client IP address 192.168.250.125. The exception is System.FormatException: "" isn't a valid SMTP domain.
at Microsoft.Exchange.Data.SmtpDomain..ctor(String domain, Boolean check)
at Microsoft.Exchange.Transport.Agent.TrustedMail.InboundTrustAgent.GetOriginatingDomain(EndOfHeadersEventArgs endOfHeadersEventArgs)
at Microsoft.Exchange.Transport.Agent.TrustedMail.InboundTrustAgent.EndOfHeadersHandler(ReceiveMessageEventSource eventSource, EndOfHeadersEventArgs eventArgs)
at Microsoft.Exchange.Data.Transport.Smtp.SmtpReceiveAgent.Invoke(String eventTopic, Object source, Object e)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.Dispatcher.Invoke(MExSession session)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.Invoke()
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.AsyncInvoke(Object state)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.BeginInvoke(String topic, Object source, Object e, AsyncCallback callback, Object callbackState)
at Microsoft.Exchange.Protocols.Smtp.DataBdatHelpers.RaiseEOHEvent(Object state, ISmtpInSession session, AsyncCallback callback, EndOfHeadersEventArgs eventArgs)
at Microsoft.Exchange.Protocols.Smtp.DataInboundProxySmtpCommand.RawDataReceived(Byte[] data, Int32 offset, Int32 numBytes)
at Microsoft.Exchange.Protocols.Smtp.SmtpInSession.ReadComplete(IAsyncResult asyncResult).

Followed by one entry for the crash of the FrontEndTransport service

Log Name: Application
Source: MSExchange Common
Event ID: 4999
Task Category: General
Level: Error
Keywords: Classic
User: N/A
Computer: XCH201301.contoso.com
Description:
Watson report about to be sent for process id: 87600, with parameters: E12IIS, c-RTL-AMD64, 15.00.1076.009, MSExchangeFrontendTransport, M.Exchange.Data, M.E.D.SmtpDomain..ctor, System.FormatException, 6379, 15.00.1076.009.
ErrorReportingEnabled: False

This will continue to happen until the message it removed from whatever upstream source is trying to deliver it to your Exchange server. MS has identified it as a bug and delivered us an out of band patch that applies to CU10 but can’t be applied to CU11. MS has told us that the fix will be included in CU12.

I originally posted this issue in the Exchange subreddit, any updates will be posted there.

Posted in Exchange, Exchange 2013 | Leave a comment

PowerShell script to download attachments from an email

Recently I was asked to automate the process of grabbing an email from a mailbox and downloading all the attachments to a specified destination. The following script accomplishes this using the Exchange Managed Webservices API. A few notes about this script:

  1. It must be run by either the same account that owns the mailbox being searched or an account with the impersonation RBAC role assigned to it
  2. It requires the EWS API, and you can specify the path to your installed version
  3. The Script searches for any email with a similar supplied subject
  4. Optionally the script can do the following:
    1. Do an exact search for the subject supplied
    2. Delete the email after a successful download of all the attachments
    3. Can be set not to overwrite files with the same name in the target directory
    4. If the attachments are zip files it can extract the files to the specified location (does not work with overwrite protection)
    5. Search for only emails matching today’s date
    6. Send an email error report to a specified email (good if the script is going to be run through a simple scheduler like Scheduled Tasks

This script currently cannot download attached EML/MSG files or embedded attachments in those files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<#
.SYNOPSIS
Get-AttachmentFromEmail.ps1 will use Exchange Web Services to search the inbox of a given mailbox associated with an SMTP Address for any emails with attachments that are similar to the subject specified. If found all attachments in the emails found will be saved to the specified path. Options include the ability to search for just emails that arrived today, a search for an exact subject match, the ability to automatically unzip *.zip files, and the ability to delete the emails once the attachments have been successfully downloaded. The script also supports using impersonation to access a mailbox not belonging to the run time user
.DESCRIPTION
Before attempting any work the script checks for the existence of the EWS managed API, if it cannot be found the script will send an error to the console and to the email address specified to receive error reports
Once the EWS managed API is loaded a connection to Exchange is made to the mailbox of the current runtime user or using impersonation to connect to a mailbox of another user. Once connected the total items of in the mailbox being worked is found, this will be used to ensure the entire inbox is searched when looking for the email in question.
Then a search query is built to look for the following
1. Any email with a subject similar to the subject specified
a. The –ExactSearch parameter will search for emails with a subject that exactly matches the one specified
2. That also has attachments
This search will return all emails that match this query in the inbox, conversely the –TodayOnly switch can be used to return only emails matching the runtime date (e.g. 10/1/2013)
If any emails are found then the attachments are saved to the specified path (overwriting any files with the same name), if the path is not accessible then the script will send an error to the console and to the email address specified to receive error reports.
If the switch –UnZipFiles is used and the email attachments are indeed zip files then the script first copy the zip files to the destination path specified, un-compress the contents, and delete the zip file
If the switch –DeleteEmail is used then after all the attachments have been downloaded the emails found will be moved to the Deleted folder on the mailbox in question. 
.PARAMETER EmailSubject
The exact subject of the email that the script will search for
.PARAMETER SavePath
The local or network path the attachments found will be save to
.PARAMETER SMTPAddress
The SMTP address of the of the mailbox that the script will search for regardless if it's the current runtime user or a different user
.PARAMETER DeleteEmail
If specified any email found and it’s attachments successfully saved will be moved to the deleted folder. 
.PARAMETER TodayOnly
If specified only emails found that match the Day, Month, and Year of the current script runtime will be returned by the inbox search 
.PARAMETER ExactSearch
By default the script will search for any email matching any of the terms in the subject being searched for, when using this parameter the script will look for emails with a subject that exactly matches the subject being searched for
.PARAMETER UnZipFiles
If any attachments found are zip files you can specify that the script extract the files within the zip file and store them at the specified location instead of the zip file itself
.PARAMETER EwsUrl
Instead of using auto discover you can specify the EWS URL
.PARAMETER ExchangeVersion
Specify the Exchange Version the EWS service should use, the default is "Exchange2010_SP2"
.PARAMETER IgnoreSSLCertificate
Used to ignore any SSL certificate errors encountered when using EWS
.PARAMETER EWSManagedApiPath
Used to specify the path for the EWS Managed API, the default is C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll
.PARAMETER EWSTracing
Used to turn on EWS tracing for troubleshooting
.PARAMETER ImpersonationUserName
The Username of the account to user for impersonation
.PARAMETER ImpersonationPassword
The Password of the account to user for impersonation
.PARAMETER ImpersonationDomain
The Domain of the account to user for impersonation
.PARAMETER EmailFrom
The SMTP address error emails will come from
.PARAMETER EmailErrorsTo
The SMTP address error emails will go to
.PARAMETER SMTPServer
The SMTP address server used to send error emails 
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath “\\FileServer\Email Attachments” -SMTPAddress John.Doe@company.com
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath “\\FileServer\Email Attachments” -SMTPAddress John.Doe@company.com -ExactSearch –UnZipFiles 
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with the exact subject of “Important Attachment” and save the attachments to \\FileServer\Email Attachments. If any of those attachments are zip files then the script will extract the contents of the zip files leaving only the contents and not the zip file
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Sales Results” –SavePath “C:\Email Attachments” -SMTPAddress John.Doe@company.com -DeleteEmail -TodayOnly 
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Sales Results” with the runtime date of today and save the attachments to \\FileServer\Email Attachments. Once the attachments have been saved then move the email to the delete items folder
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress differentUser@company.com –ImpersonationUserName ServiceMailboxAutomation –ImpersonationPassword “$*fnh23587” –ImpersonationDomain CORP
 
Description
-----------
Will search the mailbox associated with “differentUser@company.com” using the account “ServiceMailboxAutomation” which will need the impersonation RBAC role to access the mailbox. The search will be for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments. 
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress John.Doe@company.com –EmailFrom EmailTeam@company.com –EmailErrorsTo HelpDesk@company.com –SMTPServer mail.company.com
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments. If any errors are encountered then send an email from “EmailTeam@company.com” to “HelpDesk@company.com” using the SMTP server of “mail.company.com”
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress John.Doe@company.com –EwsUrl https://webmail.company.com/EWS/Exchange.asmx –EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll" -$ExchangeVersion Exchange2010_SP1 –IgnoreSSLCertificate -EWSTracing
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" any emails in the inbox that exactly match “Important Attachment” and save the attachments to \\FileServer\Email Attachments. Before connecting to the mailbox the EWS connection will use the following options
1. The EWS URL of https://webmail.company.com/EWS/Exchange.asmx
2. The EWS Managed API Path of "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
3. The Exchange version of "Exchange2010_SP1"
4. Ignore all SSL Certificate errors
5. Turn on EWS tracing
.INPUTS
System.String
You cannot pipe to this script
.OUTPUTS
NONE
.NOTES
AUTHOR: John Mello 
CREATED : 10/29/2013 
CREATED BECAUSE: To automate the retrieval, download, and deletion of a daily delivered email attachment 
.LINK
DSMS Script Storage location : \\Bala01\World\Technology\EnterpriseServices\PlatformServices\Directory and Messaging Services\Scripts
DSMS SharePoint Scripting Portal : http://techweb/ess/dci/dsms/scripting/default.aspx
DSMS PowerShell KB : http://techweb/ess/dci/dsms/scripting/powershellscripting/Home.aspx
#>
[CmdletBinding(DefaultParameterSetName="Default")]
Param(
[Parameter(Mandatory=$True,Position=0)]
[string]$EmailSubject,
 
[Parameter(Mandatory=$True,Position=1)]
[string]$SavePath,
 
[Parameter(Mandatory=$True,Position=3)]
[string]$SMTPAddress,
 
[Parameter(Mandatory=$false)]
[switch]$DeleteEmail,
 
[Parameter(Mandatory=$false)]
[switch]$TodayOnly,
 
[Parameter(Mandatory=$false)]
[switch]$ExactSearch,
 
[Parameter(Mandatory=$false)]
[switch]$UnZipFiles,
 
[Parameter(Mandatory=$false)]
[string]$EwsUrl = "https://webmail.susq.com/EWS/Exchange.asmx" ,
 
[Parameter(Mandatory=$false)]
[ValidateSet("Exchange2007","Exchange2007_SP1","Exchange2007_SP2","Exchange2007_SP3","Exchange2010","Exchange2010_SP1","Exchange2010_SP2","Exchange2010_SP3")]
[string]$ExchangeVersion = "Exchange2010_SP2",
 
[Parameter(Mandatory=$false)]
[switch]$IgnoreSSLCertificate,
 
[Parameter(Mandatory=$false)]
[string]$EWSManagedApiPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll",
 
[Parameter(Mandatory=$false)]
[switch]$EWSTracing,
 
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[string]$ImpersonationUserName,
 
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[string]$ImpersonationPassword,
 
[Parameter(Mandatory=$false,ParameterSetName="Impersonation")]
[string]$ImpersonationDomain,
 
[Parameter(Mandatory=$False)] 
[string]$EmailFrom, 
 
[Parameter(Mandatory=$False)] 
[string[]]$EmailErrorsTo,
 
[Parameter(Mandatory=$False)] 
[string]$SMTPServer = "mailhost.susq.com"
)
 
#Region Functions
 
Function New-EWSServiceObject {
<#
.SYNOPSIS
Returns an EWS Service Object
.DESCRIPTION
Creates a EWS service object, with the option of using impersonation and/or An EWS URL or fall back to Autodiscover
.PARAMETER SMTPAddress
The SMTP address of the Exchange mailbox that is associated with the EWS object
.EXAMPLE
PS C:\powershell> New-EWSServiceObject -SMTPAddress "John.Doe@Company.com"
 
------------------
Description 
------------------
 
This will return and EWS object that uses impersonation with a specifed URL
#>
[CmdletBinding(DefaultParameterSetName="OtherUser")]
Param() 
 
Write-Verbose "Creating EWS Service connection object"
$EWSService = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion)
 
If ($EWSTracing) {
Write-Verbose "EWS Tracing enabled"
$EWSService.traceenabled = $true
}
 
if ($IgnoreSSLCertificate){
Write-Verbose "Ignoring any SSL certificate errors"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };
} 
 
If ($SMTPAddress) {Write-Verbose "Creating service for the following address $SMTPAddress"}
Else {Write-Verbose "Creating service for the following runtime user $ENV:UserName"} 
 
Write-Verbose "Checking if the runtime or a seperate account will be used for impersonation"
If ($ImpersonationUserName -and $ImpersonationPassword) {
Write-Verbose "Secondary account for Impersonation specifed ($ImpersonationUserName)"
If ($ImpersonationDomain) {
#If a domain is presented then use that as well
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword,$ImpersonationDomain)
}
Else {
#Otherwise leave the domain blank
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword)
}
Write-Verbose "Saving impersonation credentials for EWS service"
$EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SMTPAddress)
}
Else{
Write-Verbose "Runtime account specifed for impersonation ($ENV:Username)"
$EWSService.UseDefaultCredentials = $true 
}
 
#Set the EWS URL, the EWS URL is needed if the the runtime user is specifed since they may not have a mailbox
If ($EWSURL) {
Write-Verbose "Using the specifed EWS URL of $EWSURL"
$EWSService.URL = New-Object Uri($EWSURL)
}
Else {
Write-Verbose "Using the AutoDiscover to find the EWS URL"
$EWSService.AutodiscoverUrl($SMTPAddress, {$True})
}
#Now Return the Service Object
Return $EWSService
}
 
Function Send-ErrorReport {
<#
.SYNOPSIS
Used to create a one line method to write an error warning to the console, send an error email, and exit a script when an terminal error is encountered
.DESCRIPTION
Send-ErrorReport Takes a Subject and message body field and uses the Subject to write a warning messages to the console and as the email subject. It uses the body as the body of the email that will be sent. You can also specify and SMTP Server, From, and To address or set the default options. Once complete the script sends the exit command to script calling the function 
.PARAMETER Subject
The subject of the email to be sent and the warning message that is sent to the console
.PARAMETER body 
The body of the email sent
.PARAMETER HaltScript
Sends the Exit command to the script caling the function, used to report on terminating errors
.EXAMPLE
PS C:\powershell> Send-ErrorReport -Subject "can't load EWS module" -Body "can't load EWS module, verify this path : $EWSManagedApiPath" -HaltScript
 
WARNING: can't load EWS module
 
------------------
Description 
------------------
 
This will send an email through the specifed SMTP server, from and to the specifed addresses with the specifed subject and body and use the sbubject to write a warning message. Then function will stop the script that called it
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$true)]
[string]$Subject,
 
[Parameter(Position=1,Mandatory=$true)]
[string]$body,
 
[Parameter()]
[switch]$HaltScript
) 
 
Write-Warning $Subject
#Appened Script name to email Subject
If ($EmailFrom -and $EmailErrorsTo -and $SMTPServer) {
$Subject = "Get-AttachmentFromEmail.ps1 : " + $Subject
send-mailmessage -from $EmailFrom -to $EmailErrorsTo -smtpserver $SMTPServer -subject $Subject -Body ($body | Out-String) -BodyAsHtml
}
If ($HaltScript) {Exit 1}
}
 
#EndRegion
 
#Region PreWork
 
#Remove double qoutes from Subject, File Path, and SMTP address (just in case)
#Need to find a way around this
$EmailSubject = $EmailSubject -replace "`""
$SavePath = $SavePath -replace "`""
$SMTPAddress = $SMTPAddress -replace "`""
 
# Check if the save path is available, if not then exit the script
Try {Test-Path $SavePath -ErrorAction Stop | Out-Null}
Catch {Send-ErrorReport -Subject "Save path cannot be accessed" -body "Please the following user name <B>$($ENV:USERNAME)<?B>, has access to this path : <B>$SavePath</B>" -HaltScript}
 
# Check if EWS Managed API available, if not then exit the script
Try {Get-Item -Path $EWSManagedApiPath -ErrorAction Stop | Out-Null}
Catch {Send-ErrorReport -Subject "EWS Managed API path cannot be accessed" -body "Please verify the following EWS API path on <B>$($ENV:COMPUTERNAME)</B> : <B>$EWSManagedApiPath</B>" -HaltScript}
 
# Load EWS Managed API
[void][Reflection.Assembly]::LoadFile($EWSManagedApiPath);
 
#EWS requires double back whacks "\\" for each normal back whack "\" when
#it comes to the file path to save to
#E.g. C:\Windows\System32 needs to look like C:\\Windows\\System32
$EWSSavePath = $SavePath -replace "\\","\\"
 
#Create EWS Service
$EWSservice = New-EWSServiceObject
#EndRegion
 
#Region Main Program Work
#Attach to the inbox to find the total number of items
#This will be used on in the search query so that we search the entire inbox
$InboxID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
Try {$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWSservice,$InboxID)}
Catch {Send-ErrorReport -Subject "Account is not permissioned for Impersonation" -body "Please verify that the following account <B>$ImpersonationUserName</B> has the ability to impersonate <B>$SMTPAddress</B>" -HaltScript}
 
$NumEmailsToReturn = $InboxFolder.TotalCount
If ($InboxFolder.TotalCount -eq 0) {
Write-Warning "Inbox is empty, exiting script or the Runtime Account of $($ENV:USERNAME) does not have impersonation rights for $SMTPAddress"
Exit
}
 
#Create mailbox view
$view = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList $NumEmailsToReturn
#Define properties to pull for each item in the view
$propertyset = New-Object Microsoft.Exchange.WebServices.Data.PropertySet (
[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayTo,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayCc,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeSent,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived
)
#Assign view to porperty set
$view.PropertySet = $propertyset
#Define the search quuery
#An EWS exact search puts the search term in "" so if we need that then add the qoutes again)
If ($ExactSearch) {
$EmailSubject = "`"$EmailSubject`""
}
If ($TodayOnly) {$query = "Subject:$EmailSubject AND HasAttachments:True AND Received:today"}
Else {$query = "Subject:$EmailSubject AND HasAttachments:True"}
 
#Preform the search
$FoundEmails = $EWSservice.FindItems("Inbox",$query,$view)
#$FoundEmail = $items | Where-Object {$_.Subject -like $EmailSubject}
If ($FoundEmails) {
If ($UnZipFiles) {$ZipFileNames = @()}
Foreach ($Email in $FoundEmails) {
$emailProps = New-Object -TypeName Microsoft.Exchange.WebServices.Data.PropertySet(
[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments
)
 
$EmailwithAttachments = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($EWSservice, $Email.Id, $emailProps)
Foreach ($File in $EmailwithAttachments.Attachments) {
Try {
#Just to be safe, remove any invaild characters from the attachment name
$FileName = $File.name -replace ("[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())))
#Current can't handle Emails that are attacments, so we skip them
If ($File.contenttype -eq $null) {
Write-Warning "Attachment is an email, skipping"
$EMLAttachment = $TRUE
continue
}
Else {$EMLAttachment = $FALSE}
$File.load($EWSSavePath + "\\" + $FileName)
If (($FileName -like "*.zip") -and $UnZipFiles) {$ZipFileNames += $SavePath + "\"+ $FileName}
}
Catch {Send-ErrorReport -Subject "Attachment save path cannot be accessed" -body "Please verify the following path <B>$SavePath</B><BR>Full Error:<BR> $_" -HaltScript}
}
If ($DeleteEmail -and (-not $EMLAttachment)) {$Email.Delete("MoveToDeletedItems")}
Else {Write-Warning "DeleteEmail specifed but embedded EML file in email could not be downloaded"}
}
If ($UnZipFiles) {
Try {
$shell = new-object -com shell.application
$Location = $shell.namespace($SavePath)
foreach ($ZipFile in $ZipFileNames)
{
$ZipFolder = $shell.namespace($ZipFile)
$Location.Copyhere($ZipFolder.items())
Remove-item $ZipFile
}
}
Catch {Send-ErrorReport -Subject "Attachment save path cannot be accessed" -body "Please verify the following path <B>$SavePath</B><BR>Full Error:<BR> $_" -HaltScript}
}
}
#EndRegion
Posted in Email, EWS, Exchange | Leave a comment

Powershell script to sync select details of calendar entries from one calendar to another

Recently at work I received a request to sync the calendar of one of our employee’s to the iPhone of a person external to the company. After much deliberation between all of our internal IT teams we decided on the following method:

  1. Created an exchange mailbox that can’t send and receive email for the external user
  2. Installed the Good Mobile app on the external user’s device and activate it against our Good for Enterprise system
  3. Used a PowerShell EWS Script (running every 15 minutes) to copy a rolling 2 years’ worth of entries from the source mailbox to the destination mailbox
    1. For company specified security reasons the script only syncs the Subject, Date/Time, and location of all calendar entries.
    2. If an entry is removed from the source calendar it is removed from the destination calendar along with any entries in the destination calendar that are not present in the source calendar.

Originally I tried to copy the entries from the source mailbox to the destination mailbox but I ran into two issues:

  1. The source account needs full mailbox access to the source account, this is because impersonation is used to access the mailboxes. Which means the copy action is being performed as the source account.
  2. Reoccurring appointments, unlike other appointments, cannot be copied and have to be re-created. So instead of trying to figure out a way to copy them and any changes in the reoccurrence pattern I decided to create new entries for all the appointments.

Below is a copy of the script I created for this task, it’s not great but it’s currently getting the job done.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<#
.SYNOPSIS
      Sync-EWSCalendarOneWay.ps1 uses Exchange Web Services to do a one way sync of only the Subject, Start Time, End Time, Free Busy information, 
	  and location information of all calendar items in a given range of runtime of the script up to two years from a source Exchange 2010 mailbox 
	  to a destination Exchange 2010 mailbox. All entries in the same time frame on the destination mailbox calendar that are not in the source 
	  calendar will be deleted. 
.DESCRIPTION
      Sync-EWSCalendarOneWay.ps1 will 1st load the EWS Managed API using the path specified, once loaded the script will create date time objects 
	  using the current runtime date (or a specified date) as the start range and provide day range as the ending range (choosing Midnight for 
	  each date). Then 2 separate EWS service objects are created for the source and destination mailbox using Impersonation (via a credential file
	  or specifed login info) or the current runtime account and EWS URL or auto discover. For each service all the calendar entries for the given 
	  range are pulled. If at least one calendar returns entries then the Source Mailbox Calendar search results are compared to the Destination 
	  Mailbox Search results. Any equal entries are ignored. Any Entries found only in the Source mailbox are saved in an list that will be the
	  additions to the destination calendar. Any Entries found only in the Destination mailbox are saved in a list that will be the deletion to the 
	  destination calendar. 
      If Adds to the destination calendar are found, the script creates new Appointment EWS objects with only the following information : Subject, 
	  Location, Start Time, End Time, If It’s an All Day Event, The Free Busy Status, and the reminder set to false. This new object is then saved 
	  to the destination calendar. Note that the entries from the source are not copied from the destination calendar due to the following:
            1.    This requires the source mailbox to have full access to the destination mailbox
            2.    This script was meant to copy only the basic appointment info and to remove attendee info, Appointment body, etc. 
            3.    You cannot copy reoccurring appointments from one calendar to another using EWS, you would have to create a new reoccurring appointment 
			with the same information at the destination calendar. 
      If Deletes to the destination calendar are found then for each entry:
            1.    A search of is made against the destination calendar for the start and stop time of the appointment to delete with all entries in that time 
			frame returned
            2.    All returned entries are searched for one that matches all the properties of the current entry to delete.
            3.    Once a matching entry found is it is deleted and all other results are ignored and the script moves onto the next Appointment to delete
      Once all Adds and Deletes are processed if any errors are found during then an email detailing the action, subject, start, and stop time of the calendar 
	  entry that error’ed out.  
.PARAMETER SourceMailbox
      The SMTP address on of the source mailbox to pull calendar entries from
.PARAMETER DestinationMailbox
      The SMTP address of the destination mailbox to sync calendar entries to
.PARAMETER TimeToSyncInDays
      The number in days that the search range will encompass, up to a maximum of 730. If none is specified then the default will be 730 days
.PARAMETER StartingDate
      The Starting date of the search range, if none is specified then the default will be the runtime of the script 
.PARAMETER ImpersonationXMLFilePath
      Path to a saved credential file that can be decoded by the current run time user. This file will need to contain a user and password at the very least
.PARAMETER ImpersonationUserName
      If impersonation is needed the supply the user name  for the account that has the impersonation RBAC role
.PARAMETER ImpersonationPassword
      If impersonation is needed the supply the password of the user name  for the account that has the impersonation RBAC role
.PARAMETER ImpersonationDomain
      If impersonation is needed you can optionally supply the domain for the account that has the impersonation RBAC role 
.PARAMETER EWSManagedApiPath
      The path to the EWS Managed API, if none is specified then the default is "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll" 
.PARAMETER ExchangeVersion
      Version of Exchange to pass to the creation of the EWS service, if none is specified then the default will be "Exchange2010_SP2"
.PARAMETER EwsUrl
      Specify the EWS URL, if none is specified then Auto Discover is used.
.PARAMETER EmailErrorsTo
      The Email address(es) to send any error reports or script run time error reports too
.PARAMETER EmailErrorsFrom
      The Email address any error reports or script run time error reports are sent from
.PARAMETER SMTPServer
      The SMTP server used to send any error reports
.PARAMETER EWSTracing
      Enables EWS tracing if needed
.PARAMETER IgnoreSSLCertificate
      Sets the EWS connection to ignore any SSL errors
.EXAMPLE
      PS C:\> .\Sync-EWSCalendarOneWay.ps1 –SourceMailbox Joe.Doe@Company.com –DestinationMailbox Jane.Doe@Company.com –TimeToSyncInDays 365 –StartingDate 01/01/2013 
	  –ImpersonationUserName ImpService –ImpersonationPassword Password1 –ImpersonationDomain CORP 
	  –EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
	  –ExchangeVersion Exchange2010_SP2 –EwsUrl https://webmail.susq.com/EWS/Exchange.asmx -EmailErrorsTo HelpDesk@company.com 
	  –EmailErrorsFrom ScriptReports@company.com –SMTPServer mail.company.com
 
      Description
      -----------
      Syncs all the calendar entries found between 01/01/2013 12:00AM and 365 days in the future (01/01/2014 12:00AM) in the source mailbox with the SMTP address of 
	  Joe.Doe@Company.com to the destination mailbox with the SMTP address of Jane.Doe@Company.com. The sync is done through an account that has the impersonation RBAC 
	  role and it’s username, password, and domain are supplied. The path for the EWS API has been specified along with the version of Exchange to work with. Any 
	  errors encountered during the run time of the script will be sent to HelpDesk@company.com from ScriptReports@company.com using the SMTP server mail.company.com
.EXAMPLE
      PS C:\> .\Sync-EWSCalendarOneWay.ps1 –SourceMailbox Joe.Doe@Company.com –DestinationMailbox Jane.Doe@Company.com –TimeToSyncInDays 365 –StartingDate 01/01/2013 
	  -ImpersonationXMLFilePath C:\Cred.xml –EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll" 
	  –ExchangeVersion Exchange2010_SP2 –EwsUrl https://webmail.susq.com/EWS/Exchange.asmx -EmailErrorsTo HelpDesk@company.com –EmailErrorsFrom ScriptReports@company.com 
	  –SMTPServer mail.company.com
 
      Description
      -----------
      Syncs all the calendar entries found between 01/01/2013 12:00AM and 365 days in the future (01/01/2014 12:00AM) in the source mailbox with the SMTP address of 
	  Joe.Doe@Company.com to the destination mailbox with the SMTP address of Jane.Doe@Company.com. The sync is done through an account that has the impersonation RBAC 
	  role and an XML file holding the credentials of the impersonation account is used. The path for the EWS API has been specified along with the version of Exchange 
	  to work with. Any errors encountered during the run time of the script will be sent to HelpDesk@company.com from ScriptReports@company.com using the SMTP server 
	  mail.company.com
.INPUTS
      None
.OUTPUTS
      None
.NOTES
      Author: John Mello
      Date: September 17 2013
#>          
 
[CmdletBinding(DefaultParameterSetName="Default")]
Param(
      [Parameter(Position=0,Mandatory=$True)]
      [string]$SourceMailbox,
 
      [Parameter(Position=1,Mandatory=$True)]
      [string]$DestinationMailbox,
 
      [Parameter(Position=2,Mandatory=$false)]
      [ValidateRange(1,730)]
      [int]$TimeToSyncInDays = 730,
 
      [Parameter(Position=3,Mandatory=$false)]
      [DateTime]$StartingDate = (Get-Date),
 
      [Parameter(Position=4,Mandatory=$False)]
      [Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
      [String]$ImpersonationUserName,
 
      [Parameter(Position=4,Mandatory=$False,ParameterSetName="ImpersonationFile")]
      [ValidateScript({Test-Path $_ })]
      [String]$ImpersonationXMLFilePath,
 
      [Parameter(Position=5,Mandatory=$False)]
      [Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
      [String]$ImpersonationPassword,
 
      [Parameter(Position=6,Mandatory=$False)]
      [Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
      [String]$ImpersonationDomain,
 
      [Parameter(Position=7,Mandatory=$False)]
      [ValidateScript({Test-Path $_ })] 
      [String]$EWSManagedApiPath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll",
 
      [Parameter(Position=8,Mandatory=$False)]
      [String]$ExchangeVersion = "Exchange2010_SP2",
 
      [Parameter(Position=9,Mandatory=$False)]
      [String]$EwsUrl,
 
      [Parameter(Position=10,Mandatory=$False)]
      [String[]]$EmailErrorsTo,
 
      [Parameter(Position=11,Mandatory=$False)]
      [String]$EmailErrorsFrom,
 
      [Parameter(Position=12,Mandatory=$False)]
      [String]$SMTPServer,
 
      [Parameter(Position=13,Mandatory=$False)]
      [switch]$EWSTracing,
 
      [Parameter(Position=14,Mandatory=$False)]
      [switch]$IgnoreSSLCertificate
 
)
 
#Region Helper Functions
 
Function Send-ErrorReport {
      <#
      .SYNOPSIS
            Used to create a one line method to write an error warning to the console, send an error email, and exit a script when an terminal error is encountered
      .DESCRIPTION
            Send-ErrorReport Takes a Subject and message body field and uses the Subject to write a warning messages to the console and as the email subject. It 
			uses the body as the body of the email that will be sent. You can also specify and SMTP Server, From, and To address or set the default options. Once 
			complete the script sends the exit command to script calling the function 
      .PARAMETER Subject
            The subject of the email to be sent and the warning message that is sent to the console
      .PARAMETER body 
            The body of the email sent
      .PARAMETER HaltScript
            Sends the Exit command to the script caling the function, used to report on terminating errors
      .EXAMPLE
            PS C:\powershell> Send-ErrorReport -Subject "can't load EWS module" -Body "can't load EWS module, verify this path : $EWSManagedApiPath" -HaltScript
 
            WARNING: can't load EWS module
 
            ------------------
            Description 
            ------------------
 
            This will send an email through the specifed SMTP server, from and to the specifed addresses with the specifed subject and body and use the sbubject to 
			write a warning message. Then function will stop the script that called it
      #>
      [CmdletBinding()]
      Param(
            [Parameter(Position=0,Mandatory=$True)]
            [string]$Subject,
 
            [Parameter(Position=1,Mandatory=$True)]
            [string]$body,
 
            [Parameter()]
            [switch]$HaltScript
      )     
 
      Write-Warning $Subject
      #Appened Script name to email Subject
      $Subject = "Set-TechCalendar.ps1 : " + $Subject
      send-mailmessage -from $EmailErrorsFrom -to $EmailErrorsTo -smtpserver $SMTPServer -subject $Subject -Body $body -BodyAsHtml
      If ($HaltScript) {Exit}
}
 
Function New-ErrorTableEntry {
      <#
      .SYNOPSIS
            Returns a error table object
      .DESCRIPTION
            Creates a PSObject with the strings provided and returns it
      .PARAMETER Error
            At what step the error occured
      .PARAMETER Detail 
            Item that the error occured on or the actual error
      .EXAMPLE
            PS C:\powershell> New-ErrorTableEntry -Error "Deleting Calendar Entry" -Detail "This Calendaer entry"
 
            ------------------
            Description 
            ------------------
 
            This will return the a table entry with the specifed information
      #>
      [CmdletBinding()]
      Param(
            [Parameter(Position=0,Mandatory=$True)]
            [string]$Error,
 
            [Parameter(Position=1,Mandatory=$True)]
            [String]$Detail
      )     
    $Entry = New-Object PSObject -Property @{                                       
      Error = $Error
           Detail = $Detail
      }
      Return $Entry
}
 
Function Get-EWSCalendarSearchResults {
      <#
      .SYNOPSIS
            Returns all the the Calender entries from a specifed search range
      .DESCRIPTION
            Given a starting and ending searach range along with the and EWS Service object and EWS folder ID, the Function will search for and return all the 
			entires within that range
      .PARAMETER StartRange
            A start range in DateTime format
      .PARAMETER EndRange
            An end range in DateTime format
      .PARAMETER EWSService 
            The EWS Service object that will be searched
      .PARAMETER EWSCalFolder
            The EWS Folder object that the search results will be returned from
      .EXAMPLE
            PS C:\powershell> Get-EWSCalendarSearchResults -StartRange "01/01/2013" -EndRange "01/01/2014" -EWSService $SomeUserEWSService -EWSCalFolder $EWSCalendarFolder
 
            ------------------
            Description 
            ------------------
 
            This will return and EWS object that uses impersonation with a specifed URL
      #>
 
      [CmdletBinding()]
      Param(
            [Parameter(Position=0,Mandatory=$True)]
            [DateTime]$StartRange,
 
            [Parameter(Position=1,Mandatory=$True)]
            [DateTime]$EndRange,
 
            [Parameter(Position=2,Mandatory=$True)]
            [Object]$EWSService,
 
            [Parameter(Position=3,Mandatory=$True)]
            [Object]$EWSCalFolder
      )
 
      #Create the range to search and return up to 1000 items
      $Calview = new-object Microsoft.Exchange.WebServices.Data.CalendarView($StartRange,$EndRange,1000)
      #Use the search to pull create a result set
      $CalSearchResult = $EWSService.FindAppointments($EWSCalFolder.id,$Calview)
      #if more items are available then double the search range and try again until no more items are left
      While ($CalSearchResult.MoreAvailable) {
            $Calview.MaxItemsReturned = ($Calview.MaxItemsReturned * 2)
            $CalSearchResult = $EWSService.FindAppointments($EWSCalFolder.id,$Calview)
      }
      Return $CalSearchResult
}
 
#EndRegion Helper Functions
 
#Region Load Dependencies
Write-Verbose "Loading EWS Managed API"
Try{
      Import-Module -Name $EWSManagedApiPath -ErrorAction Stop
}
Catch {
      Send-ErrorReport -Subject "Can't load EWS module (Sync-EWSCalendarOneWay.PS1)" -Body "Please verify this path : $EWSManagedApiPath<BR>Full error is as follows:<BR>$_" -HaltScript
}
#EndRegion Load Dependencies
 
#Region Variable Creation
#Create Table to Hold errors
$ErrorTable = @()
 
#Pull the search range in days specifed by $TimeToSyncInDays, the maximum search range in EWS is 2 years
#12AM was choosen as the Startdate since we wanted to correctly capture any changes made during the day
Write-Verbose "Creating Search range with the start time of $StartingDate and $TimeToSyncInDays days in the future"
[DateTime]$Today = $StartingDate.ToLongDateString() + " 12:00 AM"
[DateTime]$Future = ((Get-Date).Adddays($TimeToSyncInDays)).ToLongDateString() + " 12:00 AM"
 
#Load saved credential file if needed
If ($ImpersonationXMLFilePath) {
      Write-Verbose "Impersonation credential file specifed, importing login info”
      Try  {
            $ImportCreds = Import-Clixml $ImpersonationXMLFilePath -ErrorAction Stop
            $NewCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $ImportCreds.UserName, ($ImportCreds.Password | ConvertTo-SecureString -Erroraction Stop) -ErrorAction Stop
      }
      Catch {
            Send-ErrorReport -Subject "Issue using the specified Impersonation credential file (Sync-EWSCalendarOneWay.PS1)" -Body "<H4>Please verify that the runtime account being used can access and decode the credential file</H4><BR><B>Runtime User: </B>$ENV:UserName<BR><B>FIlePath: </B>$ImpersonationXMLFilePath<BR><B>Full error is as follows:</B><BR>$($_.Exception)" -HaltScript
      }
      $ImpersonationUserName= $NewCreds.GetNetworkCredential().UserName
      $ImpersonationPassword = $NewCreds.GetNetworkCredential().Password
      $ImpersonationDomain = $NewCreds.GetNetworkCredential().Domain
}
 
#Create Folder ID for the well know folder 'Calenadar', used to pull the calendar folder for each mailbox
$FolderID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)
 
#Create EWS Service object
Try {
      If ($EWSTracing) {
      Write-Verbose "EWS Tracing enabled"
            $EWSservice.traceenabled = $true
      }
      if ($IgnoreSSLCertificate){
            Write-Verbose "Ignoring any SSL certificate errors"
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };
      }
      Write-Verbose "Creating EWS Service object"
      $EWSService = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion) -ErrorAction Stop
      Write-Verbose "Checking if the runtime or a seperate account will be used for impersonation"
      If ($ImpersonationUserName -and $ImpersonationPassword) {
            Write-Verbose "Secondary account for Impersonation specifed ($ImpersonationUserName)"
            If ($ImpersonationDomain) {
                  #If a domain is presented then use that as well
                  $EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword,$ImpersonationDomain) -ErrorAction Stop
            }
            Else {
                  #Otherwise leave the domain blank
                  $EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword) -ErrorAction Stop
            }
      }
      Else{
            Write-Verbose "Runtime account specifed for impersonation ($ENV:Username)"
            $EWSService.UseDefaultCredentials = $true
      }
      If ($EwsUrl) {
            Write-Verbose "Using the specifed EWS URL of $EwsUrl"
            $EWSService.URL = New-Object Uri($EwsUrl) -ErrorAction Stop
      }
}
Catch{
      Send-ErrorReport -Subject "Can't create EWS Service (Sync-EWSCalendarOneWay.PS1)" -Body "Please verify this path : $EWSManagedApiPath<BR>Full error is as follows:<BR>$_" -HaltScript
}
 
#Connect to each mailbox and pull calendar entries
Try{
      Write-Verbose "Pointing EWS Service connection to the source mailbox ($SourceMailbox)"
      $EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SourceMailbox) -ErrorAction Stop
      If (-not $EwsUrl) {
            Write-Verbose "Using the AutoDiscover to find the EWS URL"
            $EWSService.AutodiscoverUrl($SMTPAddress, {$True})
      }
      $SourceCalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($EWSService,$FolderID)
      $SourceSearchResults = Get-EWSCalendarSearchResults -StartRange $Today -EndRange $Future -EWSService $EWSService -EWSCalFolder $SourceCalendarFolder
 
      Write-Verbose "Pointing EWS Service connection to the destination mailbox ($DestinationMailbox)"
      $EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $DestinationMailbox) -ErrorAction Stop
      If (-not $EwsUrl) {
            Write-Verbose "Using the AutoDiscover to find the EWS URL"
            $EWSService.AutodiscoverUrl($SMTPAddress, {$True})
      }
      $DestinationCalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($EWSService,$FolderID)
      $DestinationSearchResults = Get-EWSCalendarSearchResults -StartRange $Today -EndRange $Future -EWSService $EWSService -EWSCalFolder $DestinationCalendarFolder
}
Catch {
      $body = "<H4>Verify the following info:</h4><BR><B>Source Mailbox: </B>$SourceMailbox<BR><B>Destination Mailbox: </B> $DestinationMailbox<BR>If using impersonation or an EWS url check that as well<BR><B>Full error is as follows:</B><BR>$_"
      Send-ErrorReport -Subject "Can't bind to a calender (Sync-EWSCalendarOneWay.PS1)" -Body $body -HaltScript
}
 
#EndRegion Variable Creation
 
#Region Comparison Work
#If items were found in the date range then compare the list
If ($DestinationSearchResults.count -or $SourceSearchResults.count) {
      Write-Verbose "Items found in at least one calendar, creating compare list"
      $Comparelist = Compare-Object -ReferenceObject $DestinationSearchResults -DifferenceObject $SourceSearchResults -Property Subject,Start,End,Location,IsAllDayEvent,LegacyFreeBusyStatus
}
Else {
      #No entires found, both calendars are blank
      $body = "<h4>Verify the following info:</H4><BR>Check runtime account or impersonation account<BR><B>Source Mailbox: </B>$SourceMailbox<BR><B>Destination Mailbox: </B>$DestinationMailbox<BR><B>Search Range: </B>$TimeToSyncInDays"
      Send-ErrorReport -Subject "Both Calendars are empty (Sync-EWSCalendarOneWay.PS1)" -Body $body -HaltScript
}
 
Write-Verbose "Seperating the differences into an Add and Delete list"
$Adds = $Comparelist | Where-Object {$_.SideIndicator -eq "=>"}
$Deletes = $Comparelist | Where-Object {$_.SideIndicator -eq "<="}
 
#Work on the new appts, if any
#Note that the EWSService should still be set to the destination mail box, which was accessed last
#but we double check just to be sure
if (-not $EWSService.ImpersonatedUserId.Id -eq $DestinationMailbox) {
      $EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $DestinationMailbox)
}
 
If ($Adds) {
      Write-Verbose "$($Adds.count) Calendar entries found only in the soruce mailbox, adding to the destination calendar"
      foreach ($NewAppt in $Adds) {
            $EWSCalObjectCopy = New-Object Microsoft.Exchange.WebServices.Data.Appointment($EWSService)
            $EWSCalObjectCopy.Subject = $NewAppt.Subject
            $EWSCalObjectCopy.Location = $NewAppt.Location
            $EWSCalObjectCopy.Start = $NewAppt.Start
            $EWSCalObjectCopy.End = $NewAppt.End
            $EWSCalObjectCopy.IsAllDayEvent = $NewAppt.IsAllDayEvent
            $EWSCalObjectCopy.LegacyFreeBusyStatus = $NewAppt.LegacyFreeBusyStatus
            $EWSCalObjectCopy.IsReminderSet = $false
            Try {$EWSCalObjectCopy.Save()}
            Catch {
                  Write-Warning "Can't create calendar entry with the subject : $($EWSCalObjectCopy.Subject), logging"
                  $ErrorTable += (New-ErrorTableEntry -Error "Error creating Calender Entry" -Detail "Subject = $($EWSCalObjectCopy.Subject), Start = $($EWSCalObjectCopy.Start), End = $($EWSCalObjectCopy.End)")
            }           
      }
}
Else {Write-Verbose "After comparison no adds have been found"}
 
#Work on the removed appts, if any
If ($Deletes) {
      Write-Verbose "$($Deletes.count) Calendar entries found only in the destination mailbox, deleting from the destination calendar"
      foreach ($DeletedAppt in $Deletes) {
            #Create the range to search and return up to 10 items
            $MatchingAppts = Get-EWSCalendarSearchResults -StartRange $DeletedAppt.Start -EndRange $DeletedAppt.End -EWSService $EWSService -EWSCalFolder $DestinationCalendarFolder
            #Check if any results were found
            If ($MatchingAppts)  {
                  #In case of multiple entries use Istem fount and delete 
                  $ItemFoundAndDeleted = $false
                  #Compare all entries found and if there is a match delete that entry and move onto the next appt on the delete list
                  Foreach ($FoundAppt in ($MatchingAppts)) {
                              If (($FoundAppt.subject -eq $DeletedAppt.subject) -and
                                    ($FoundAppt.Location -eq $DeletedAppt.Location) -and
                                    ($FoundAppt.Start -eq $DeletedAppt.Start) -and
                                    ($FoundAppt.End -eq $DeletedAppt.End) -and
                                    ($FoundAppt.IsAllDayEvent -eq $DeletedAppt.IsAllDayEvent) -and
                                    ($FoundAppt.LegacyFreeBusyStatus -eq $DeletedAppt.LegacyFreeBusyStatus)) 
                              {
                                          Try {
                                                #Item Found, doing a hard delete (Not sent to recovery folder)
                                                $FoundAppt.Delete([Microsoft.Exchange.Webservices.Data.DeleteMode]::HardDelete)
                                                #Set item found to true so we don't search the rest of the results
                                                $ItemFoundAndDeleted = $True
                                                }
                                          Catch {
                                                Write-Warning "Can't delete Calendar Entry with the subject : $($FoundAppt.Subject), logging"
                                                $ErrorTable += (New-ErrorTableEntry -Error "Error Deleting Calender Entry" -Detail "Subject = $($FoundAppt.Subject), Start = $($FoundAppt.Start), End = $($FoundAppt.End)")
                                          }                             
                              }
                              If ($ItemFoundAndDeleted) {Break}
                        }
                  }
            Else {
                  Write-Verbose "Can't find entry with the subject : $($DeletedAppt.Subject), logging"
                  $ErrorTable += (New-ErrorTableEntry -Error "Error finding Calendar Entry to delete" -Detail "Subject = $($FoundAppt.Subject), Start = $($FoundAppt.Start), End = $($FoundAppt.End)")
            }
      }
}
Else {Write-Verbose "After comparison no deletes have been found"}
 
#Used only to show the script is working in tidal
If ($Adds) {
      If ($Adds.count) {Write-Host "$($Adds.count) new entries added"}
      Else {Write-Host "1 new entries added"}
}
Else {Write-Host "0 new entries added"}
 
If ($Deletes) {
      If ($Deletes.count) {Write-Host "$($Deletes.count) entries deleted"}
      Else {Write-Host "1 entries deleted"}
}
Else {Write-Host "0 entries deleted"}
 
 
#EndRegion Comparison Work
 
#Region Error Reporting
 
#If any errors enteringm, finding, or deleting emails then send a report
If ($ErrorTable) {
 
$HTMLBody = @"
<style>
BODY{
background-color:grey;font-family:Tahoma}
"font-family:Tahoma
}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;Font-Size:9pt}
TH{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:lightblue}
TD{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:lightgrey}
</style>
"@                      
      Write-verbose "Erros found, creating table and emailing report"
      $HTMLBody += $ErrorTable | 
            Select-Object Error, Detail | 
            Sort-Object Error |
            ConvertTo-HTML -body "<H5>Full Error Report</H5>"
      If ($ErrorTable.Count) {$Subject = "$($ErrorTable.Count) Errors found in Sync-EWSCalendarOneWay.PS1"}
      Else {$Subject = "1 Errors found in Sync-EWSCalendarOneWay.PS1"}
      send-mailmessage -from $EmailErrorsFrom -to $EmailErrorsTo -smtpserver $smtpServer -subject $Subject -Body ($HTMLBody | Out-String)  -BodyAsHtml
}
 
#EndRegion Error Reporting
Posted in EWS, Exchange 2010, PowerShell | Leave a comment

The 2013 Scripting Games, Beginner Event #3

Question

Dr. Scripto has been fielding a lot of calls from the Help Desk lately. They’ve been asking him to look up information about the local hard drives in various servers—mainly size and free space information. He doesn’t mind helping, but all the requests have been getting in the way of his naps. He’s asked you to write a one-liner command that can get the information for him, and he wants the output in an HTML file. The HTML file should look something like this:

Capture

 

The Doctor says you don’t need to parameterize your command. It’s okay to write it to run against LocalHost, and he can just change that computer name as needed in the future. The resulting HTML does need to go into an HTML file on disk someplace, and he wants you to pay special attention to the following:

  • The browser displays “Disk Free Space Report” in the page tab when viewing the report.
  • “Local Fixed Disk Report” is in the Heading 2 (H2) HTML style.
  • The report ends with an HTML horizontal rule, and the date and time that the report was generated.
  • The size and free space values are shown as gigabytes (GB) and megabytes (MB) respectively, each to two decimal places.

The command you write can assume that both WMI and CIM are available on the remote computers, and that all the necessary firewall rules and authentication have already been taken care of.

Answer

Actual Entry (forgot to save the HTML)

Get-WmiObject -class Win32_Logicaldisk -computername "Localhost" -Filter "DriveType=3" | Select @{label="Drive";Expression={$_.DeviceID}},@{label="Size(GB)";Expression={"{0:N2}" -f($_.Size / 1GB)}},@{label="Size(MB)";Expression={"{0:N2}" -f($_.FreeSpace / 1MB)}} | ConvertTo-Html -head "

Local Fixed Disk Report

" -PostContent ("

" + (get-Date))

Should have been (used body to hold title and output the file)

Get-WmiObject -class Win32_Logicaldisk -computername "Localhost" -Filter "DriveType=3" | Select @{label="Drive";Expression={$_.DeviceID}},@{label="Size(GB)";Expression={"{0:N2}" -f($_.Size / 1GB)}},@{label="Size(MB)";Expression={"{0:N2}" -f($_.FreeSpace / 1MB)}} | ConvertTo-Html -body "

Local Fixed Disk Report

" -PostContent ("

" + (get-Date))| Out-File -FilePath $PWD\DiskReport.html

 

Learning Points

Hard Coded Paths (Boe Prox)

Hard path’s like C:\test\ won’t work for everyone, a better solution would be to use one of the built in PowerShell path variables like:

  • $pwd (present working directory)
  • $Env:TEMP  (OS temp directory)
  • $Env:USERPROFILE. (Current user root profile)
  • Among others

ConvertTo-Html Tricks (Bartek Bielawski)

The -preContent and -PostContent parameters can take string arrays, e.g.:

  • ConvertTo-Html (...) -PostContent '

    ', (Get-Date)

You can also submit a hashtable for the -Property parameter, thus bypassing the need to use Select-Object if needed, e.g. :

Get-Process | ConvertTo-Html -Property @{                Label = 'Process Name'                Expression = { $_.Name }            }, @{                Label = 'Process Id'                Expression = { $_.Id }            }, @{                Label = 'Path to executable'                Expression = { $_.Path }            } | Out-File Processes.html

CIM vs WMI (Jan Egil Ring and Ann Hershel)

  • While we should be moving towards CIM due to its use of both DCOM and WinRM. Granted they both can’t be used in the same statement and need to specified separately since CIM uses WinRM by default
  • if any W2K systems were present they would only work with DCOM, and most modern systems that are set up securely would block DCOM access

Advanced Notes (Bartek Bielawski)

  • I know this particualr notion appeard with a different blogger but it’s good enough to mention twice
  • Use splatting if you plan to use the same info over and over again in a script, in fact it’s not a bad idea to do it all the time
    • Instead of 

Send-MailMessage -To user@domain.com -From user1@domain.com -Subject Test -SMTPServer server@domain.com -Body “This is a test”

    • Do
$email = @{ To = 'user@domain.com' From = 'user1@domain.com' Subject = 'Test' SMTPServer = 'server.domain.com' Send-MailMessage @email
  • Uses aliases for parameter that might have multiple input names. E.g. -ComputerName could also have __Server or Name to compensate for different inputs on different PS versions

Advanced Notes (Ann Hershel)

  • You can created parameters sets such that when a parameter that is not required can become required when another parameter is specified
  • This next portion appeared in a previous blog entry as well but once again it’s good info and this had a more fleshed out example
  • When you declare a parameter as ValueFromPipeline you need to use a process block in order for the script/function to work with each pipelined in object.
function Get-DiskInfo { param( [Parameter(ValueFromPipeline=$true)] [String[]] $ComputerName ) process { "Processing $ComputerName" } }
  • So this would work
'server1', 'server2' | Get-DiskInfo
  • But a string array won’t, as it will process the both names at the same time
Get-DiskInfo -ComputerName 'server1', 'server2'
  • In order to get this to work you need to have the process block unroll the content of $ComputerName and process each element separately.
function Get-DiskInfo { param( [Parameter(ValueFromPipeline=$true)] [String[]] $ComputerName ) process { $ComputerName | Foreach-Object { "Processing $_" } } }
Posted in PowerShell, Scripting Games | Leave a comment

The 2013 Scripting Games, Beginner Event #2

Question

Dr. Scripto finally has the budget to buy a few new virtualization host servers, but he needs to make some room in the data center to accommodate them. He thinks it makes sense to get rid of his lowest-powered old servers first… but he needs to figure out which ones those are.All of the virtualization hosts run Windows Server, but some of them don’t haveWindows PowerShell installed, and they’re all running different OS versions. Theo ldest OS version is Windows 2000 Server (he knows, and he’s embarrassed, but he’s just been so darn busy). The good news is that they all belong to the same domain, and that you can rely on having a Domain Admin account to work with. The good Doctor has asked you to write a PowerShell command or script that can show him each server’s name, installed version of Windows, amount of installed physical memory, and number of installed processors. For processors, he’ll be happy getting a count of cores, or sockets, or even both — whatever you can reliably provide across all these different versions of Windows. To help you out, he’s given you a text file, C:\IPList.txt, that contains one server IP address per line. If you can write this as a one-liner — awesome! If not, try to keep your answer is concise and compact as possible (although it’s perfectly okay to use full command and parameter names).

My Answer

Get-Content C:\IPList.txt | 
 Foreach-object {
  Get-WmiObject -Namespace root\CImv2 -Class Win32_ComputerSystem -ComputerName $_ | 
   Select-object Name, 
                 @{Label="OS";Expression={(Get-WmiObject -Namespace root\CImv2 -Class Win32_OperatingSystem).Caption}}, 
                 TotalPhysicalMemory, 
                 NumberOfProcessors, 
                 NumberOfLogicalProcessors
  } | 
   Format-Table -AutoSize

To make PS_2 compatible use __Servername instead of Name

My answer, but rounding up the size calculations

Using the format ( f{}) commands

Get-Content C:\IPList.txt | 
 Foreach-object {Get-WmiObject -Namespace root\CImv2 -Class Win32_ComputerSystem -ComputerName $_ | 
 Select-object Name, 
 @{Label="OS";Expression={(Get-WmiObject -Namespace root\CImv2 -Class Win32_OperatingSystem -ComputerName $_.Name).Caption}}, @{Label="Mem in GB";Expression={"{0:N0}" -f($_.TotalPhysicalMemory / 1GB)}}, 
 NumberOfProcessors, 
 NumberOfLogicalProcessors} | 
Format-Table –AutoSize

Using the .Net Math class

Get-Content C:\IPList.txt | 
 Foreach-object {Get-WmiObject -Namespace root\CImv2 -Class Win32_ComputerSystem -ComputerName $_ | 
 Select-object Name, 
 @{Label="OS";Expression={(Get-WmiObject -Namespace root\CImv2 -Class Win32_OperatingSystem -ComputerName $_.Name).Caption}}, @{Label="MEM in GB";expression={[System.Math]::Round(($_.TotalPhysicalMemory / 1GB),1)}}, 
 NumberOfProcessors, 
 NumberOfLogicalProcessors} | 
 Format-Table –AutoSize

Learning Points

Splatting (Boe Prox)

Use splatting if you plan to use the same info over and over again in a script, in fact it’s not a bad idea to do it all the time

  • Instead of
Send-MailMessage -To user@domain.com -From user1@domain.com -Subject Test -SMTPServer server@domain.com -Body "This is a test"
  • Do
$email = @{
 To = 'user@domain.com'
 From = 'user1@domain.com'
 Subject = 'Test'
 SMTPServer = 'server.domain.com'
}
Send-MailMessage @email

Stop using $ErrorActionPreference (Boe Prox)

This changes it for the entire script, use it as needed for each command using -ErrorAction

Using Passthru to combine different objects (taygibb‘s entry)

The PassThru parameter is one of the common parameters of most PowerShell cmdlets and returns an object when a cmdlet normally wouldn’t return an object. For example, The Copy-Item cmdlet will perform an action but not return any information on the copied object but when specifying the Passthru parameter you can return the copied object and perform further work on it. In TayGibbs script he uses this technique to add a new member to the management object returned from query the 1st set of required WMI information. Normally Add-Member wouldn’t return information to the console. But when using the Passthru cmdlet it will  return the new changed object

Get-WmiObject -Class "Win32_ComputerSystem" -ComputerName localhost | 
 Select-Object -Property Name,
                         TotalPhysicalMemory,
                         NumberOfLogicalProcessors,
                         NumberOfProcessors | 
                            Add-Member -Name "OS Version" -Value $(Get-WmiObject -Class Win32_OperatingSystem -ComputerName localhost | 
                                                                     Select-Object -ExpandProperty Caption) -MemberType NoteProperty -PassThru

Advanced Notes (Art Beane)

  • If your entry calls for array entry in the parameter then make sure to add it, e.g.
    • [string[]]$ComputerName
  • Match your parameter names to the properties of the expected item (e.g. ComputerName and not Server)
  • When working in V3 with CIM why not Try{WSMAN} Catch{DCOM}

Misc Advanced Notes

  • Uses #Requires -version X to show the version your script works with
  • Be careful with shorthand parameter declarations, for examle
    • This works in v2 and v3
      • [Parameter(Position=0,ValueFromPipeline=$True,Mandatory=$True)]
    • This only works in V3
      • [Parameter(Position=0,ValueFromPipeline,Mandatory)]

 

 

Posted in Uncategorized | Leave a comment

The 2013 Scripting Games, Beginner Event #1 follow-up

It’s been a while since I blogged and i have the skeletons of multiple blogs post waiting to be edited. But now that I’ve settled into my new job and the scripting games have died down I can finally start posting my notes and learning points from the rest of the scripting games events. So here is the 1st in a series of follow-ups on the scripting games. Each entry the following:

  • The original question
  • My submitted answer
  • A revised answer after reviewing other entries and judges notes
  • A summary of learning points I took away from the event

Question 1

Dr. Scripto is in a tizzy! It seems that someone has allowed a series of application log
files to pile up for around two years, and they’re starting to put the pinch on free
disk space on a server. Your job is to help get the old files off to a new location.
The log files are located in C:\Application\Log. There are three applications that
write logs here, and each uses its own subfolder. For example,
C:\Application\Log\App 1, C:\Application\Log\OtherApp, and
C :\Application\Log\ThisAppAlso. Within those subfolders, the filenames are
random GUIDs with a .LOG filename extension. Once created on disk, the files are
never touched again by the applications.
Your goal is to grab all of the files older than 90 days and move them to
\\NASServer\Archives. You need to maintain the subfolder structure, so that files
from C:\Application\Log\Appl get moved to \\NASServer\Archives\Appi, and so
forth.
You want to ensure that any errors that happen during the move are clearly
displayed to whoever is running your command. You also want your command to be
as concise as possible — Dr. Scripto says a one-liner would be awesome, if you can
pull it off, but it’s not mandatory that your command be that concise. It’s also okay to
use full command and parameter names. If no errors occur, your commaid doesn’t
need to display any output — “no news is good news.”

My Answer

Get-ChildItem -Path "C:\Application\Log" -Recurse -Filter *.log | Where-object {$_.CreationTime -le (get-date).AddDays(-90)} | Select Name,Directory,FullName  | ForEach-Object {Move-Item $_.FullName -Destination ("\\NASServer\Archives\"+($_.Directory.Name)+"\"+$_.Name)}

After reviewing other entries my revised entry is

Get-ChildItem -Path "C:\Application\Log" -Recurse -Filter "*.log" | Where-object {$_.CreationTime -le (get-date).AddDays(-90)} | ForEach-Object {Move-Item $_.FullName -Destination ("\\NASServer\Archives\"+$_.Directory.Name)}

Removed:

  • Redundant select statement, for some reason when I 1st did the script I thought this was the only way to get the Directory Name info
  • Didn’t need the extra $_.Name portion since I’m coming to a directory not an actual file
  • I didn’t incase *.log in quotations so it will find *.log123 etc. in addition to *.log

Learning Points

Think before using -recurse (Ann Hershel)

If you are working with a deep folder structure you can use wildcards to specify a at just a few levels, e.g.

Get-ChildItem -Path C:\Application\Log\*\*.log

Foreach() versus ForEach-Object (Ann Hershel)

foreach() is faster but it requires the data to be collected in memory first, so large sets can chew up a lot of memory. If the collection gathering fails then the whole command fails. Foreach-Object processes objects as they appear, so it uses less memory and is potentially better for large data sets

Create directories while moving them

You can make a check for the destination folders and create them using New-item If they weren’t present. Using New-Item alone will create the destination files and directories but will not remove them from the source. But you can get around this with a simple if statement

if (-not(Test-Path $ArchiveDirectory)) {New-Item $ArchiveDirectory -ItemType Directory | Out-Null} Move-Item $file.FullName $ArchiveDirectory }

Honor Verb Hyphen Noun when creating functions (Bartek Bielawski)

Use approved verbs, you should rarely deviate from this. And your nouns should not be plural.

Don’t use Boolean if you don’t need to (Bartek Bielawski)

You can test for a value by using if ($Value) and the opposite by if (-not $Value)

Don’t repeat calculations in your pipeline (June Blender)

For example the following will do the math for Get-Date for every file passed down the pipeline

Get-ChildItem C:\Application\Log\*\*.log | 
 Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-90)} | 
 Move-Item -Destination ...

It would be better do it once, save it as a variable then and re-use it

$ArchiveDate = (Get-Date).AddDays(-90)
Get-ChildItem C:\Application\Log\*\*.log | 
 Where-Object {$_.LastWriteTime -lt $ArchiveDate} | 
 Move-Item -Destination ...

Another issue with doing the calculation every time an object is passed down the pipeline is that the date is changing each time. What if you ran this command at 11:59PM? The files that hit the pipeline at 12:00AM are being compared using a different date.

Validate your parameters before running the script (Glenn Sizemore)

Example

Param ( 
    [Parameter(Mandatory=$true, ValuefrompipelineByPropertyName=$true)]
  [ValidateScript({Test-Path $_ -PathType Container})] 
    [Alias("FullName")]
  [string]$Source,

 [Parameter(Mandatory=$true, ValuefrompipelineByPropertyName=$true)]
    [ValidateScript({Test-Path $_ -PathType Container})] 
  [Alias("FullName")]
    [string]$Destination
}

Don’t make you Parameter names all start with the same letter (Glenn Sizemore)

It makes tab completion harder than it needs to be!

How to correctly use Pipeline input for your functions (Boe Prox)

If you have a parameter that accepts pipeline input then you need to have the work performed on the pipeline input in a process block, otherwise it will only execute on the last object piped in. For example, take this function:

Function Test-Something { 
 [cmdletbinding()] 
 Param ( 
  [parameter(ValueFromPipeLine=$True)] 
  [string[]]$Computername
 ) 
 ForEach ($Computer in $Computername) { 
  $Computer
 }
}

If the you try the following:

1,2,3,4,5 | Test-Something

You will only get the following back

5

If you add a process block, like so:

Function Test-Something { 
 [cmdletbinding()] 
 Param ( 
  [parameter(ValueFromPipeLine=$True)] 
  [string[]]$Computername
 ) 
 Process {
  ForEach ($Computer in $Computername) { 
   $Computer
  }
 }
}

And rerun the command you will get each item output instead of the last item in the pipeline.

So over all use the Begin{} to initialize anything that you need to run only once prior to the Process{} block (e.g. make a SQL connection). The Process{} block will then execute for each piped in object. Finally the End{} block will execute any one time work that needs to be done after working with the piped in results (e.g. closing a SQL connection)

Posted in PowerShell, Scripting Games, Uncategorized | Leave a comment

The 2013 Scripting Games, Beginner Event #1

Having participated in the 2013 Winter Scripting Camp I was excited to try out my scripting skills again in the 2013 Scripting Games. While my scripting skills have advanced a lot of over the past 6 months since I co-founded the Philadelphia PowerShell User Group (PhillyPoSH), I still feel that I’m not cut out for the advanced events just yet. Especially considering the Beginner events of Winter Scripting Camp took me much longer than I expected. For those 2 events I struggled to get the answer down to one or two lines. While I believed that my scripting skills have evolved, the beginner events left me feeling as if I hadn’t advanced that much. For a quick history of the games and my submissions for the Winter Scripting Camp check the presentation I gave at PhillyPosh in March of this year.

So the 1st event for both the advanced and beginner track of the Scripting Games is over and the voting phase for the 1st event is under way. As a recap the question for the beginner track was

The log files are located in C:\Application\Log. There are three applications that write logs here, and each uses its own subfolder. For example, C:\Application\Log\App1, C:\Application\Log\OtherApp, and C:\Application\Log\ThisAppAlso. Within those subfolders, the filenames are random GUIDs with a .log filename extension. After they are created on disk, the files are never touched again by the applications.

Your goal is to grab all of the files older than 90 days and move them to \\NASServer\Archives. You need to maintain the subfolder structure, so that files from C:\Application\Log\App1 get moved to \\NASServer\Archives\App1, and so forth.

You want to ensure that any errors that happen during the move are clearly displayed to whoever is running your command. You also want your command to be as concise as possible — Dr. Scripto says a one-liner would be awesome, if you can pull it off, but it’s not mandatory that your command be that concise. It’s also okay to use full command and parameter names. If no errors occur, your command doesn’t need to display any output — “no news is good news.”

After trying a few attempts I originally came up with

Get-ChildItem -Path "C:\Application\Log" -Recurse -Filter *.log | Where-object {$_.CreationTime -le (get-date).AddDays(-90)} | Select Name,Directory,FullName  | ForEach-Object {Move-Item $_.FullName -Destination ("\\NASServer\Archives\"+($_.Directory.Name)+"\"+$_.Name)}

At the time, I kept having issues getting $_.Directory.Name to work. When I referenced it I would get an error that the property Directory didn’t exist. Using Select-Object fixed it for me, but upon further review I noticed that it worked without Select-Object. So I guess I probably had a misspelling somewhere when I originally wrote out the command.

I also thought that  I need to include the full file name path when copying to the destination, which obviously isn’t the case. My command would essentially say : copy C:\Application\Logs\SomeOtherApp\Test.log to \\NASserver\Archive\SomeOtherApp\Test.log
when it should have just dropped the file name mention in the destination and used \\NASserver\Archive\SomeOtherApp\ instead.

I also didn’t realize my query for *.log would return files with extensions like *.log123 etc. Encasing the filter in double quotations will ensure that I only look for *.log files

So after reviewing and voting on some entries I realized I could have shorten (and corrected) my command to

Get-ChildItem -Path "C:\Application\Log" -Recurse -Filter "*.log" | Where-object {$_.CreationTime -le (get-date).AddDays(-90)} | ForEach-Object {Move-Item $_.FullName -Destination ("\\NASServer\Archives\"+$_.Directory.Name)}

One of the cool parts about this year’s Scripting Games is that every can vote and comment on everyone else’s scripts. So far I’ve seen the following interesting things:

  • Using a wildcard in the path name instead of using the –Filter parameters
    • Get-ChildItem -Path C:\Application\Logs\*\*.Log -recurse
  • Even though the question didn’t ask for it some contestants made a check for the destination folders and created them (using New-item) If they weren’t present, as an example in a foreach loop. Using New-Item alone will create the destination files and directories but will not remove them from the source.
    • if (-not(Test-Path $ArchiveDirectory)) {New-Item $ArchiveDirectory -ItemType Directory | Out-Null} Move-Item $file.FullName $ArchiveDirectory }

Blooger Bartek Bielawski posted his answers to both the beginner and the advanced track and I found his use of script block in the beginner event to be very interesting.

Get-ChildItem -Path C:\Application\Log\*\*.Log | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-90)} | Move-Item -Destination {"\\NASServer\Archives\{0}\" -f $_.Directory.Name}

I still plan to vote on a few of the beginner entries this week until the next event opens. As I come across more interesting answers I’ll update this post

Posted in PowerShell, Scripting Games | Tagged as: | Leave a comment

PowerShell script to find all Active Sync devices on an Exchange 2010 server that haven’t synced in a specified amount of time

I published my 1st Powershell script to Technet’s Script repository and Poshcode.org. You can grab it here and below are the details of the script straight from the help file:

.SYNOPSIS
Get-InactiveActiveSyncDevices pulls all user mailboxes with an Active Sync partnership and then selects the Active Sync devices that haven't synced in the specified period. These devices are sorted in ascending order and placed in a HTML table which is emailed to the specified user using a specified reply to address and SMTP server
PLEASE TEST BEFORE RUNNING THIS SCRIPT IN PRODUCTION
.DESCRIPTION
The script 1st checks to see if Implicit remoting is needed to load the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010), this is done by seeing it the $ExchangeConnectionUri variable does not have a $NULL value. If it contains a URI then create a new PSsession using the current credentials and import the session. If Implict remoting isn't needed then verify that the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010) is loaded and if not try to load it locally. Then  Get-InactiveActiveSyncDevices uses Get-CasMailbox to pull all the user mailboxes (Not Discovery or CAS mailboxes) with Active Sync device partnerships and saves them to a variable called $ActiveSyncMailboxes. It then walks through each mailbox and uses Get-ActiveSyncDeviceStatistics to pull DeviceType, DeviceUserAgent, DeviceID, LastSyncAttemptTime, LastSuccessSync for each mailbox’s separate Active Sync device partnership and puts these properties in addition to the full name associated with the mailbox into a hashtable called $UserActiveSyncStats. The reason why Get- ActiveSyncDeviceStatistics isn’t used exclusively is because it does not have a property that stores just the name of the user who owns the Active Sync device, only a full Active Directory path to the Active Sync device. This hash table is used to create a custom PowerShell Object which is then added to $ActiveSyncDeviceList. A variable called $MatchingActiveSyncDevices holds all the Active Sync devices in $ActiveSyncDeviceList that haven’t synced to the Exchanger server in less than or equal to the number of hours specified in $HourInterval . $MatchingActiveSyncDevices is then checked to see if it’s an empty array or not. If it contains items an HTML header is created to format the table for the HTML email report and saved in a variable called $HTMLHeader . Then The Body of the email contains all of the criteria matching Active Sync devices from $MatchingActiveSyncDevices in ascending order which is converted to HTML using the HTML header information created earlier in $HTMLHeader. Otherwise a the body contains a message stating that no devices matched the given criteria.. An Email is then sent out to the user specified in $to from the address specified in $from using the email server specified in $SmtpServer. The body is generated from the sorted Active Synce Devices in $ActiveSyncDeviceList.

 

Posted in Exchange 2010, PowerShell | Leave a comment

Multiple Exchange accounts in Outlook 2010 and 2013

We have added a lot of new email domains at my company recently and one most common request from our users is to work with multiple Exchange mailboxes within Outlook 2010. This would normally be accomplished by giving the user full access to whatever additional mailbox they need access to. But this method had some drawbacks for our users, mainly:

  • The user has to manually select the outgoing  email address of another mailbox they had full access to if they want to send as that account
    • The preferred behavior is that when they select the mail box from the Outlook tree and create a new email it will default to the outgoing address for that mailbox. This is not the behavior when granted full access to a mailbox, instead the outgoing email will always default to the primary Exchange account.
  • If the user requires separate signatures for each additional mailbox they have to manually specify them since the signature used will be the one for the main Exchange account. While you can create multiple signatures you can only attach one signature each for new email and reply to the main Exchange account and not the additional mailboxes the user was granted access to.

These might not seem like huge issues, but when these additional mailboxes are treated as if they came from separate companies it turn into a huge issue when a user accidentally sends an email intended for a client working with Company A with the outgoing email and signature from Company B. So in searching for a solution I came across this Microsoft Article detailing how to carry out adding multiple Exchange accounts to an Outlook profile. The problem is that it requires volume licenses of Office 2010 and a fairly complicated process to a get the additional accounts added. All the office licenses at my company are Medialess License Kits (MLK) so that ruled out this method. Originally it appears that the ability to add multiple accounts existed in the preview of Outlook 2010, but the method describe in the article no longer worked. And since there was an article detailing the process for retail release I assumed this feature was dropped. When the Office 2013 preview came out one of the 1st things I did was test its ability to add multiple accounts and surprisingly it worked! All I need to do was:

  1. After adding the first account in Outlook 2013 go to the File Tab.
  2. Under Info click on the +Add Account button
  3. From there fill in the info for the 2nd Exchange Account and it will be added to your Account Tree

This method allowed me to address the issues my users were having with managing additional mailboxes and didn’t require the user to have full access granted to the mailbox. Wondering if this worked in Outlook 2010 as well, I tried it and delighted it worked despite the documentation from Microsoft detailing a much more involved process to do so. I have since tested it up to 3 different Exchange accounts on the same Exchange server with no issues. I’m not sure what the limit is but I assume it might be 3 accounts per Outlook profile, like originally specified in the preview build of Outlook 2010.  

 

Posted in Exchange 2010, Outlook | Leave a comment
  • Archives

  • November 2017
    M T W T F S S
    « Jul    
     12345
    6789101112
    13141516171819
    20212223242526
    27282930  
  • Page list