-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNew-TimeScrobble.ps1
362 lines (326 loc) · 13.6 KB
/
New-TimeScrobble.ps1
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
Function Get-OutlookInBox {
Add-type -assembly 'Microsoft.Office.Interop.Outlook' | out-null
$olFolders = 'Microsoft.Office.Interop.Outlook.olDefaultFolders' -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace('MAPI')
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items |
Select-Object -Property Subject, ReceivedTime, Importance, SenderName
}
Function Get-OutlookSent {
Add-type -assembly 'Microsoft.Office.Interop.Outlook' | out-null
$olFolders = 'Microsoft.Office.Interop.Outlook.olDefaultFolders' -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace('MAPI')
$folder = $namespace.getDefaultFolder($olFolders::olFolderSentMail)
$folder.items |
Select-Object -Property Subject, SentOn, Importance, To
}
Function Get-OutlookCalendar {
Add-type -assembly 'Microsoft.Office.Interop.Outlook' | out-null
$olFolders = 'Microsoft.Office.Interop.Outlook.OlDefaultFolders' -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace('MAPI')
$folder = $namespace.getDefaultFolder($olFolders::olFolderCalendar)
$folder.items |
Select-Object -Property Subject, Start, Duration, Location
}
Function New-HTMLTable {
param(
$inputObj,
$headerText
)
$outputArr = @()
$outputArr += ('<h2>',$headerText,'</h2>' -join '')
$outputArr += $inputObj | ConvertTo-HTML -Fragment
return $outputArr
}
Function Set-Folder {
# Function to check if a folder exists, and create it if not.
param($path)
If (!(Test-Path "filesystem::$path" -ErrorAction SilentlyContinue)) {
New-Item $path -Type Directory -Force | Out-Null
}
}
Function Import-ConfigFile {
# Quick function to read in simple plaintext config files
# Evaluate switch will expand any powershell variables (e.g. $test) in the imported strings before setting the value
param(
$Path,
[switch]$Evaluate
)
$importConfig = Get-Content $path | Where-Object {($_ -notlike '#*') -and ($_)}
$importConfig | ForEach {
$splitVar = $_.Split('=')
If ($splitVar[1] -like '*,*') {
[array]$value = $splitVar[1].Split(',').Trim()
If ($evaluate) {
$evals = @()
$value | ForEach {
$evals += $ExecutionContext.InvokeCommand.ExpandString("$_")
}
$value = $evals
}
}
Else {
[string]$value = $splitvar[1].Trim()
If ($evaluate) {
$value = $ExecutionContext.InvokeCommand.ExpandString("$value")
}
}
Set-Variable -Scope Script -Name $splitVar[0].Trim() -Value $value
}
}
$reportHeader = @"
<link rel="stylesheet" src="https://necolas.github.io/normalize.css/latest/normalize.css">
<style>
body {
color: #222;
font-family: sans-serif;
font-size: 14px;
margin: 2% 0;
}
h1 {
font-size: 2em;
font-weight: normal;
padding: 0 2%;
}
h3 {
font-size: 1.25em;
font-weight: normal;
padding: 0 2%;
}
table {
border-collapse: collapse;
width: 100%;
}
tr:nth-child(even) {
background: #ADD8E6;
}
tr:nth-child(odd) {
background: #E0FFFF;
}
tr:first-child {
background: #EEE;
}
th {
border-bottom: 1px solid #999;
font-weight: bold;
text-align: left;
}
td,
th {
padding: .25em;
}
td:first-child,
th:first-child {
padding-left: 2%;
}
td:last-child,
th:last-child {
padding-left: 2%;
}
h2 {
font-size: 1.5em;
font-weight: normal;
margin: 1 0 .5%;
padding: 0 2%;
}
</style>
"@
Write-Output "`r`nTimeScrobbler v1.0 - 2016-08-18 - https://github.com/Kittzus/TimeScrobbler`r`n"
# Work out path
$scriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent
# Read in the User.conf and turn into live variables
Import-ConfigFile -Path $scriptPath\User.conf
# Import PSSlack if a token has been provided
If (!$slackToken) {
Write-Output 'No Slack user token found in User.conf file. Enter here, or [Return] to skip'
$slackToken = Read-Host 'Slack User Token'
}
If ($slackToken) {
$modCheck = Get-Module -ListAvailable PSSlack
If (!$modCheck) {
Write-Error 'PSSlack module not found in $PSModulePath folders. Please install this from https://github.com/RamblingCookieMonster/PSSlack and relaunch TimeScrobbler to enable Slack support!'
Clear-Variable slackToken
}
Else{
Import-Module PSSlack -Force | Out-Null
}
}
# Create the output folder if it doesn't already exist
Set-Folder $outputFld
While (!$doneFlag) {
Clear-Variable moreFlag,runFlag -ErrorAction SilentlyContinue
Write-Output "`r`nPlease set the date-range you`'d like to TimeScrobble"
Write-Output "IMPORTANT: Date's must be in the unambiguous sortable date format yyyy-MM-dd e.g. 2016-08-13 for 13th August 2016"
Write-Output "[q] to Exit`r`n"
While ($runFlag -ne 'y') {
Clear-Variable validTimeSpan -ErrorAction SilentlyContinue
While (!$validTimeSpan) {
Clear-Variable validStart,validEnd -ErrorAction SilentlyContinue
While (!$validStart) {
$startDate = Read-Host 'Start Date'
Switch ($startDate) {
'q' {
exit
}
default {
Try {
$validStart = Get-Date $startDate -ErrorAction Stop
}
Catch {
Write-Error "Invalid date entered. Format must be yyyy-MM-dd.`r`n"
}
}
}
}
While (!$validEnd) {
$endDate = Read-Host 'End Date'
Switch ($endDate) {
'q' {
exit
}
default {
Try {
$validEnd = Get-Date $endDate -ErrorAction Stop
}
Catch {
Write-Error "Invalid date entered. Format must be yyyy-MM-dd.`r`n"
}
}
}
}
$validTimeSpan = New-TimeSpan -Start $validStart -End $validEnd
If ($validTimeSpan -like '-*') {
Write-Error "Invalid time period entered. Start Date must be BEFORE the End Date.`r`n"
Clear-Variable validTimeSpan
}
}
# Build our array of dates
$days = [Math]::Ceiling($validTimeSpan.TotalDays)+1
$dateArr = @()
1..$days | ForEach-Object {
$dateArr += $validStart
$validStart = $validStart.AddDays(1)
}
Write-Output "`r`nAbout to TimeScrobble $($dateArr.Count) days.`r`n"
Write-Output "Start Date: $($dateArr[0])"
Write-Output "End Date: $($validStart)"
While(@('y','n') -notcontains $runFlag) {
$runFlag = Read-Host "`r`nBegin? [y/n]"
If (@('y','n') -notcontains $runFlag) {
Write-Error "Invalid Entry!`r`n"
}
}
}
$folderArr += [Environment]::GetFolderPath('Desktop')
$folderArr += [Environment]::GetFolderPath('Desktop')
$downloadPath = Get-ItemProperty 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' | Select-Object -ExpandProperty '{374DE290-123F-4565-9164-39C4925E467B}'
# Build out the data sources for the reports if they don't yet exist
If (!$inboxArr) {
Write-Output 'Getting Outlook Inbox - This may take some time... No, seriously. Make a sandwich.'
$inboxArr = Get-OutlookInbox
}
If (!$sentArr) {
Write-Output 'Getting Outlook Sent Items - Could be a while...'
$sentArr = Get-OutlookSent
}
If (!$calArr) {
Write-Output 'Getting Outlook Calendar - Hopefully wont take too long...'
$calArr = Get-OutlookCalendar
}
If (!$folderFiles) {
Write-Output 'Getting Local Files - So how many files you got?'
$folderFiles = Get-ChildItem -Path $folderArr -Recurse -File
$downloadFiles = Get-ChildItem -Path $downloadPath -Recurse -File
}
Write-Output "`r`nBuilding Reports...`r`n"
ForEach ($day in $dateArr) {
$dateStr = $day.ToString('yyyy-MM-dd')
Write-Output "TimeScrobbling $dateStr..."
$outPath = "$outputFld\$dateStr-TimeScrobble.htm"
$tomorrow = $day.AddDays(1)
$fileSortProp1 = @{Expression='DirectoryName';Descending = $true}
$fileSortProp2 = @{Expression='LastWriteTime';Ascending = $true}
$folderObj = $folderFiles | Where-Object {($_.CreationTime -ge $day -and $_.CreationTime -lt $tomorrow) -or ($_.LastWriteTime -ge $day -and $_.LastWriteTime -lt $tomorrow)} | Select-Object Name, DirectoryName, CreationTime, LastWriteTime | Sort-Object $fileSortProp1,$fileSortProp2
$downloadObj = $downloadFiles | Where-Object {($_.CreationTime -ge $day -and $_.CreationTime -lt $tomorrow) -or ($_.LastWriteTime -ge $day -and $_.LastWriteTime -lt $tomorrow)} | Select-Object Name, CreationTime, LastWriteTime | Sort-Object lastWriteTime
$inboxObj = $inboxArr | Where-Object {$_.ReceivedTime -ge $day -and $_.ReceivedTime -lt $tomorrow} | Select-Object ReceivedTime, SenderName, Subject, Importance
$sentObj = $sentArr | Where-Object {$_.SentOn -ge $day -and $_.SentOn -lt $tomorrow} | Select-Object SentOn, To, Subject, Importance
$calObj = $calArr | Where-Object {$_.Start -ge $day -and $_.Start -lt $tomorrow} | Select-Object Start, Subject, Duration, Location
If ($slackToken) {
$slackUsers = Get-SlackUser -Token $slackToken -Presence
$slackObj = @()
ForEach ($channel in $slackChannels) {
$channelMsgs = Get-SlackChannel -Token $slackToken -Name $channel | Get-SlackHistory -Token $slackToken -After $day -Before $tomorrow
$channelMsgs | ForEach {$_ | Add-Member -MemberType NoteProperty -Name 'Channel' -Value $channel}
$slackObj += $channelMsgs
}
ForEach ($group in $slackGroups) {
$groupMsgs = Get-SlackGroup -Token $slackToken -Name $group | Get-SlackGroupHistory -Token $slackToken -After $day -Before $tomorrow
$groupMsgs | ForEach {$_ | Add-Member -MemberType NoteProperty -Name 'Channel' -Value $group}
$slackObj += $groupMsgs
}
$slackFiles = @()
$slackFileObj = @()
ForEach ($message in $slackObj) {
$message.Username = ($slackUsers | Where-Object {$_.ID -eq $message.User} | Select-Object -ExpandProperty Name)
If ($message.File) {
$slackFiles += $message
}
}
If ($slackFiles.count -ne 0) {
ForEach ($file in $slackFiles) {
$SlackFileObj += [PSCustomObject] @{
Channel = $file.Channel
Timestamp = $file.Timestamp
Username = $file.Username
Title = $file.File.title
Filename = $file.File.name
Permalink = $file.File.permalink
}
}
$slackObj = $slackObj | Where-Object {$slackFiles -notcontains $_}
}
$slackSortProp1 = @{Expression='Channel'; Descending=$true}
$slackSortProp2 = @{Expression='Timestamp'; Ascending=$true}
$slackObj = $slackObj | Select-Object Channel,Timestamp,Username,Text | Sort-Object $slackSortProp1, $slackSortProp2
}
$outBody = @()
If ($folderObj) {
$outBody += New-HTMLTable -inputObj $folderObj -headerText 'Personal Files Created/Modified'
}
If ($downloadObj) {
$outBody += New-HTMLTable -inputObj $downloadObj -headerText 'Downloaded Files'
}
If ($inboxObj) {
$outBody += New-HTMLTable -inputObj $inboxObj -headerText 'Received Emails'
}
If ($sentObj) {
$outBody += New-HTMLTable -inputObj $sentObj -headerText 'Sent Emails'
}
If ($calObj) {
$outBody += New-HTMLTable -inputObj $calObj -headerText 'Calendar Entries'
}
If ($slackObj) {
$outBody += New-HTMLTable -inputObj $slackObj -headerText 'Slack Messages'
}
If ($slackFileObj) {
$outBody += New-HTMLTable -inputObj $slackFileObj -headerText 'Slack Files'
}
[array]$outBody = "<h1>TimeScrobbler Run for $dateStr</h1>" + $outBody + "<br><h3>Report generated at $((Get-Date).ToString('yyyy-MM-dd'))</h3>"
$outHTM = ConvertTo-Html -Head $reportHeader -Body $outBody
$outHTM | Out-File $outPath -Force
}
Write-Output "`r`nTimeScrobble complete. Reports available at $outputFld`r`n"
While(!$doneFlag -and !$moreFlag) {
$doneTest = Read-Host 'TimeScrobble another range? [y/n]'
switch ($doneTest) {
'n' {$doneFlag = $true}
'y' {$moreFlag = $true}
default {Write-Output "Invalid Entry!`r`n"}
}
}
}
Write-Output "`r`nPress any key to exit.."
$x = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')