As part of our Full-Cost Maturity Model (FMM), my management chain took the number of employees and created a SWAG of our billable time – they then took these billable hours, and in my case divided them by the number of mailboxes in our organization. – That’s how much it costs for 1 Exchange Administrator per mailbox.
My direct supervisor got the idea that he’d like a more accurate idea of how much time his people have available to bill, and asked me to look into this using PowerShell.
As always, I said “No Problem” 🙂
I’d seen Glen Scale’s “FreeBusy In/Out Board for Exchange 2007 using EWS and Powershell” But I wanted to use the managed API, as it’s easier.
I’d previously seen Glen’s groundbreaking work “Using the EWS Managed API with powershell”, and had done some work with it, along with working on a cmdlet project in c#, which is on the back burner for now.
While working on the specification for this script, it was decided that:
- We only want to know about appointments that occur during each person’s working hours.
- We would ignore “All day” appointments.
- Everyone works a 40 hour week.
- Any appointment marked as “Free” would be skipped
- Any appointment marked as “Lunch” would be skipped.
- We would allow other managers to run the script as needed.
I added a few requirements
- The script should take a user’s email address or a distribution group as the target.
- The script should default to the domain of the person running the script, if the email address is entered without the domain – IE karlmitschke
- The script should accept a start date and end date, defaulting to a time period of the previous two weeks.
- The script should show either minimal information or detailed information
- The script should attempt to handle multiple appointments that overlap. (The HCBY principle)
I quickly found that the FreeBusyViewOptions.TimeWindow has a maximum duration of 42 days. MSDN says this can be modified, but doesn’t say how, so I decided to slice my time windows into 42 day chunks and loop them.
if ($EndDate – $StartDate -gt 42)
{
$TimeSegments = [math]::floor(($EndDate – $StartDate).Days/42)
$TimeRemaining = ($EndDate – $StartDate).Days – ($timesegments * 42)
}
I had the script “mostly” complete, and my boss mentioned that we won’t want each manager to install the DLL, so it had to be available from a network share.
I tried to load the dll from a network share using:
[void][Reflection.Assembly]::LoadFile(\\share\folder\dll)
That produces the helpful error: “Failed to grant minimum permission requests.”
I did find that the .dll could be copied locally and then loaded, so I copy it to the user’s temp folder:
$dll = Split-Path -parent $MyInvocation.MyCommand.Definition
$dll += “\Microsoft.Exchange.WebServices.dll”
if (!(Test-Path $env:temp\Microsoft.Exchange.WebServices.dll))
{
copy $dll $env:temp
}
$dllpath = “$env:temp\Microsoft.Exchange.WebServices.dll”
[void][Reflection.Assembly]::LoadFile($dllpath)
Now I can run the script from a network share. copy the dll from the same folder as the script resides in, and load the dll.
Before running the script, you will need to download the dll
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 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
|
<# .SYNOPSIS Get-Calendar – Gather data on Exchange 2010 calendars. .DESCRIPTION Gathers data from Exchange calendars. These data include: Total hours scheduled, total hours blocked out on the calendar, and total free hours. If the Detailed view is selected, the script will attempt to do a de-duplication, showing total time of an appointment, and effective time. .EXAMPLE Get-Calendar -CalendarName ‘user’s email address’ Description ———– Gets the calendar for the user for the previous 2 weeks. .EXAMPLE Get-Calendar -CalendarName ‘user’s email address’ -detailed Description ———– Gets the calendar for the user for the previous 2 weeks, and displays details. .EXAMPLE Get-Calendar -CalendarName ‘user’s email address’ -StartDate 1/1/2010 Description ———– Gets the calendar for the user for the period of January 1, 2010 through today. .EXAMPLE Get-Calendar -CalendarName ‘user’s email address’ -StartDate (Get-Date).AddDays(-365) Description ———– Gets the calendar for the user for the previous 365 days, through today. .EXAMPLE Get-Calendar -CalendarName ‘Distribution group’ Description ———– Gets the calendar for each user in the distribution group for the previous 2 weeks. .EXAMPLE ‘Distribution group’ | Get-Calendar -Full Description ———– Gets the calendar for each user in the distribution group for the previous 2 weeks, and displays details about all appointments. .EXAMPLE ‘Distribution group’ | Get-Calendar -Discard Description ———– Gets the calendar for each user in the distribution group for the previous 2 weeks, and displays details about all appointments occurring during working hours, including those marked as free, and with the subject of lunch. .EXAMPLE Get-Calendar -CalendarName ‘user’s email address’ -detailed |Select-Object subject, status, “effective time” Description ———– Gets the calendar for the user for the previous 2 weeks, and displays the subject, statues, and ‘effective time’ of each appointment. .NOTES File Name: Get-Calendar.ps1 Author: Karl Mitschke Requires: Exchange Web Services Requires: Powershell V2 Created: 08/01/2010 Modified: 08/13/2010 – handle time periods greater than 42 days Modified: 08/31/2010 – copy dll from network to $env:temp Modified: 09/01/2010 – Properly handle multiple calendars Modified: 09/01/2010 – handle distribution groups Modified: 09/08/2010 – Ignore conflicting appointments (The “How Can You Be In Two Places At Once” option) Modified: 09/09/2010 – Ignore appointments that are 0 minutes in length Modified: 09/09/2010 – Convert StartTime to a separate date and time, and endtime to just time Modified: 09/09/2010 – Added “Effective Time” in detailed view Modified: 09/09/2010 – Added Function “Send-Output” .PARAMETER CalendarName The Calendar(s) to search. .PARAMETER StartDate The Starting date to search from. .PARAMETER EndDate The Ending date to search to. .PARAMETER Detailed Display Appointment Information. .PARAMETER Full Display All Appointments. .PARAMETER Discard Display All Appointments occurring during working hours .INPUTS One or more Calendar names are required. The Starting and Ending dates are optional. If not specified, the script will search the previous two weeks through today. .OUTPUTS This script outputs the work days and hours scheduled for the calendar(s). Optional output includes the times, free busy status and subject of meetings. #>
param( [Parameter( Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = “The calendar name.”, Mandatory = $true )] [string[]]$CalendarName, [Parameter( Position = 1, ValueFromPipelineByPropertyName = $true, HelpMessage = “The Start Date” )] [DateTime]$StartDate, [Parameter( Position = 2, ValueFromPipelineByPropertyName = $true, HelpMessage = “The End Date” )] [DateTime]$EndDate, [Parameter( HelpMessage = “Display Appointment Information” )] [Switch]$Detailed, [Parameter( HelpMessage = “Display All Appointments” )] [Switch]$Full = $false, [Parameter( HelpMessage = “Display All Appointments occurring during working hours, including those marked as free, and with the subject of lunch” )] [Switch]$Discard = $false )
Set-StrictMode -version 1 $EffectiveTime = 0 function Send-Output { if (!$Detailed) { Write-Output $appointmenttime |Select-Object @{label=“Date”;Expression={$appointmenttime.StartTime.Date.ToShortDateString()}},` @{label=“Start”;Expression={$appointmenttime.StartTime.ToShortTimeString()}},` @{label=“End”;Expression={$appointmenttime.EndTime.ToShortTimeString()}},` @{label=“Total Time”;Expression={$AppointmentTotalTime}},@{label=“Status”;Expression={$appointmenttime.FreeBusyStatus}},` @{label=“Subject”;expression = {($Appointment)}},@{label=“Calendar”;Expression = {$Calendar}} } else { Write-Output $appointmenttime |Select-Object @{label=“Date”;Expression={$appointmenttime.StartTime.Date.ToShortDateString()}},` @{label=“Start”;Expression={$appointmenttime.StartTime.ToShortTimeString()}},` @{label=“End”;Expression={$appointmenttime.EndTime.ToShortTimeString()}} ,@{label=“Total Time”;Expression={$AppointmentTotalTime}},` @{label=“Effective Time”;Expression={$EffectiveTime/60}},@{label=“Status”;Expression={$appointmenttime.FreeBusyStatus}},` @{label=“Subject”;expression = {($Appointment)}},@{label=“Calendar”;Expression = {$Calendar}} } } if (!$StartDate) { $StartDate = (Get-Date).AddDays(-14) } if (!$EndDate) { $EndDate = (Get-Date).AddDays(1).Date } if ($EndDate – $StartDate -gt 42) { $TimeSegments = [math]::floor(($EndDate – $StartDate).Days/42) $TimeRemaining = ($EndDate – $StartDate).Days – ($timesegments * 42) } $dll = Split-Path -parent $MyInvocation.MyCommand.Definition $dll += “\Microsoft.Exchange.WebServices.dll” $OutStartDate = $StartDate if (!(Test-Path $env:temp\Microsoft.Exchange.WebServices.dll)) { copy $dll $env:temp } $dllpath = “$env:temp\Microsoft.Exchange.WebServices.dll” [void][Reflection.Assembly]::LoadFile($dllpath) $service = New-Object ` Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010) $attendees = @() $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $sidbind = “LDAP://<SID=” + $windowsIdentity.user.Value.ToString() + “>” $aceuser = [ADSI]$sidbind $service.AutodiscoverUrl($aceuser.mail.ToString()) $Domain = $aceuser.mail.ToString().Split(‘@’)[1] $NewCalendarName = $null foreach ($Calendar in $CalendarName) { try { $NewCalendarName = $service.ExpandGroup($Calendar) |Select-Object Address foreach ($NewName in $NewCalendarName) { $CalendarName += $NewName.Address.split(‘@’)[0] } } catch { } if ($NewCalendarName -ne $null) { $CalendarName = $CalendarName -ne $Calendar } } foreach ($Calendar in $CalendarName) { $loopcheck = $false if (!$Calendar.Split(‘@’)) { $MailboxName = “$Calendar@$Domain” } else { $MailboxName = $Calendar $Calendar = $Calendar.Split(‘@’)[0] } $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName) $TotalUsedTime = 0 do { if (($EndDate – $StartDate).Days -gt 42 ) { $SegmentEndDate = $StartDate.AddDays(42) } else { $SegmentEndDate = $EndDate.AddDays(1) } if ($SegmentEndDate -gt $StartDate) { $timewindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($StartDate.ToShortDateString(), $SegmentEndDate) $AttendeeInfo = New-Object Microsoft.Exchange.WebServices.Data.AttendeeInfo $AttendeeInfo.SmtpAddress = “$Calendar@$Domain” $attendees += $AttendeeInfo $FreeBusy = New-Object Microsoft.Exchange.WebServices.Data.AvailabilityData $Attendeesbatch = [activator]::createinstance(([type]‘System.Collections.Generic.List`1’).makegenerictype([Microsoft.Exchange.WebServices.Data.AttendeeInfo])) $AvailabilityOptions = new-object Microsoft.Exchange.WebServices.Data.AvailabilityOptions $AvailabilityOptions.RequestedFreeBusyView = [Microsoft.Exchange.WebServices.Data.FreeBusyViewType]::DetailedMerged $Attendeesbatch.add(“$Calendar@$Domain”) $availresponse = $service.GetUserAvailability($Attendeesbatch,$timewindow,$FreeBusy,$AvailabilityOptions) $guaRes = $service.GetUserAvailability($Attendeesbatch,$timewindow,$FreeBusy,$AvailabilityOptions) if (!$loopcheck) { Foreach($response in $availresponse.AttendeesAvailability) { Write-Host “$Calendar works” $response.WorkingHours.DaysOfTheWeek “from” $response.WorkingHours.StartTime.ToString() “to” $response.WorkingHours.EndTime.ToString() } } $TotalAvaliableTime = ($timesegments * 240) + ([int]($TimeRemaining /7) *40) #$availresponse.AttendeesAvailability[0].WorkingHours.DaysOfTheWeek.Count * #($availresponse.AttendeesAvailability[0].WorkingHours.EndTime – $availresponse.AttendeesAvailability[0].WorkingHours.StartTime).Hours *2 $TotalUsedTime = 0 if (!$availresponse.AttendeesAvailability[0].CalendarEvents.Count -eq 0) { $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($availresponse.AttendeesAvailability[0].CalendarEvents[0].StartTime).AddMinutes(1),($availresponse.AttendeesAvailability[0].CalendarEvents[0].EndTime).AddMinutes(-1) } foreach ($appointmenttime in $availresponse.AttendeesAvailability[0].CalendarEvents) { if (!$Full -and !$Discard) { if($appointmenttime.Details.Subject -eq $null -or $appointmenttime.Details.Subject.ToLower() -notmatch “lunch”) { if ($response.WorkingHours.DaysOfTheWeek.Contains($appointmenttime.StartTime.DayOfWeek.ToString()) -AND $appointmenttime.FreeBusyStatus -ne “free” ` -AND $appointmenttime.StartTime.TimeOfDay.ToString() -ge ([datetime]$response.WorkingHours.StartTime.ToString()).TimeOfDay.ToString() -and $appointmenttime.StartTime.TimeOfDay.ToString() -lt ([datetime]$response.WorkingHours.EndTime.ToString()).TimeOfDay.ToString()) { if (($AppointmentTimeWindow.StartTime -le $appointmenttime.StartTime -and $AppointmentTimeWindow.EndTime -ge $appointmenttime.EndTime) -or ($appointmenttime.StartTime -eq $appointmenttime.EndTime)) { # Previous Appointment starts before, and ends after this appointment, OR # This appointment is a 0 minute appointment, so Skip it! } elseif ($AppointmentTimeWindow.EndTime -le $appointmenttime.StartTime) { # Previous appointment ends before or at the same time as this appointment starts, so # this meeting counts completely $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours $EffectiveTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalMinutes if ($Detailed) { Send-Output } $TotalUsedTime += $EffectiveTime $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($appointmenttime.StartTime, $appointmenttime.EndTime) } elseif ($AppointmentTimeWindow.StartTime -le $appointmenttime.StartTime -and $AppointmentTimeWindow.EndTime -lt $appointmenttime.EndTime) { # Appointment starts after the previous appointment and ends after the previous appointment, so print it, and add the extra time # extra time = $appointmenttime.EndTime – $AppointmentTimeWindow.EndTime $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours $EffectiveTime = ($appointmenttime.EndTime – $AppointmentTimeWindow.EndTime).TotalMinutes if ($Detailed) { Send-Output } $TotalUsedTime += $EffectiveTime $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($appointmenttime.StartTime, $appointmenttime.EndTime) } elseif ($AppointmentTimeWindow.StartTime -gt $appointmenttime.StartTime -and $AppointmentTimeWindow.EndTime -gt $appointmenttime.EndTime) { # Appointment starts before the previous appointment and ends before the previous appointment, so print it, and add the extra time # extra time = $appointmenttime.StartTime – $AppointmentTimeWindow.StartTime $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours $EffectiveTime = ($appointmenttime.StartTime – $AppointmentTimeWindow.StartTime).TotalMinutes if ($Detailed) { Send-Output } $TotalUsedTime += $EffectiveTime $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($appointmenttime.StartTime, $appointmenttime.EndTime) } elseif ($AppointmentTimeWindow.StartTime -gt $appointmenttime.StartTime -and $AppointmentTimeWindow.EndTime -lt $appointmenttime.EndTime) { # Appointment starts after the previous appointment and ends after the previous appointment, so # this meeting counts completely $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours $EffectiveTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalMinutes if ($Detailed) { Send-Output } $TotalUsedTime += $EffectiveTime $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($appointmenttime.StartTime, $appointmenttime.EndTime) } else { $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours $EffectiveTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalMinutes if ($Detailed) { Send-Output } $TotalUsedTime += $EffectiveTime $AppointmentTimeWindow = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($appointmenttime.StartTime, $appointmenttime.EndTime) } } } } if ($Full) { $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours Send-Output $TotalUsedTime += ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalMinutes } if($Discard) { if ($response.WorkingHours.DaysOfTheWeek.Contains($appointmenttime.StartTime.DayOfWeek.ToString()) -AND $appointmenttime.StartTime.TimeOfDay.ToString()` -ge ([datetime]$response.WorkingHours.StartTime.ToString()).TimeOfDay.ToString() -and $appointmenttime.StartTime.TimeOfDay.ToString() -lt ([datetime]$response.WorkingHours.EndTime.ToString()).TimeOfDay.ToString()) { $Appointment = $appointmenttime.Details.Subject if ($appointmenttime.Details.IsPrivate -eq $true) { $Appointment = “Private” } $AppointmentTotalTime = ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalHours Send-Output $TotalUsedTime += ($appointmenttime.EndTime – $appointmenttime.StartTime).TotalMinutes } } } $loopcheck = $true } $StartDate = $StartDate.AddDays(42) }while($StartDate.ToShortDateString() -lt $EndDate.ToShortDateString()) $date = $StartDate.ToShortDateString().TrimEnd() $TotalUsedTime /=60 $billable = $TotalAvaliableTime – $TotalUsedTime if (!$Full) { $OutString = “Since “ $OutString += $OutStartDate.ToShortDateString() $OutString += “, $Calendar has shown $TotalAvaliableTime available hours with $TotalUsedTime hours booked, and $billable hours available for billing.” Write-Output $OutString } $StartDate = $OutStartDate $loopcheck = $false }
|
Like this:
Like Loading...
Related
#1 by Ross on February 20, 2013 - 07:45
This script looks good, but it’s not running for me. It’s asking for typeName. Are you able to send me a copy of the one you are using?
#2 by Karl Mitschke on February 20, 2013 - 10:24
It’s in the mail…
Karl