-
Notifications
You must be signed in to change notification settings - Fork 41
/
Helpers.ps1
1047 lines (853 loc) · 36.5 KB
/
Helpers.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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) Microsoft Corporation. All rights reserved.
function Initialize-HelpersGlobalVariables
{
<#
.SYNOPSIS
Initializes the global variables that are "owned" by the Helpers script file.
.DESCRIPTION
Initializes the global variables that are "owned" by the Helpers script file.
Global variables are used sparingly to enables users a way to control certain extensibility
points with this module.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.NOTES
Internal-only helper method.
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
which can only be applied to functions. Otherwise, we would have just had the relevant
initialization code directly above the function that references the variable.
We call this immediately after the declaration so that the variables are available for
reference in any function below.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="We are initializing multiple variables.")]
# Note, this doesn't currently work due to https://github.com/PowerShell/PSScriptAnalyzer/issues/698
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignment", "", Justification="These are global variables and so are used elsewhere.")]
param()
# We only set their values if they don't already have values defined.
# We use -ErrorAction Ignore during the Get-Variable check since it throws an exception
# by default if the variable we're getting doesn't exist, and we just want the bool result.
# SilentlyContinue would cause it to go into the global $Error array, Ignore prevents that as well.
if (!(Get-Variable -Name SBLoggingEnabled -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBLoggingEnabled = $true
}
if (!(Get-Variable -Name SBLogPath -Scope Global -ValueOnly -ErrorAction Ignore))
{
$documentsFolder = [System.Environment]::GetFolderPath('MyDocuments')
if (-not [System.String]::IsNullOrEmpty($documentsFolder))
{
$global:SBLogPath = Join-Path -Path $documentsFolder -ChildPath 'StoreBroker.log'
}
else
{
$global:SBLoggingEnabled = $false
}
}
if (!(Get-Variable -Name SBShouldLogPid -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBShouldLogPid = $false
}
if (!(Get-Variable -Name SBNotifyDefaultDomain -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBNotifyDefaultDomain = $null
}
if (!(Get-Variable -Name SBNotifySmtpServer -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBNotifySmtpServer = $null
}
if (!(Get-Variable -Name SBNotifyDefaultFrom -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBNotifyDefaultFrom = $env:username
}
if (!(Get-Variable -Name SBNotifyCredential -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBNotifyCredential = [PSCredential]$null
}
if (!(Get-Variable -Name SBUseUTC -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBUseUTC = $false
}
if (!(Get-Variable -Name SBWebRequestTimeoutSec -Scope Global -ValueOnly -ErrorAction Ignore))
{
$global:SBWebRequestTimeoutSec = 0
}
}
# We need to be sure to call this explicitly so that the global variables get initialized.
Initialize-HelpersGlobalVariables
function Wait-JobWithAnimation
{
<#
.SYNOPSIS
Waits for a background job to complete by showing a cursor and elapsed time.
.DESCRIPTION
Waits for a background job to complete by showing a cursor and elapsed time.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER jobName
The name of the job that we are waiting to complete.
.EXAMPLE
Wait-JobWithAnimation Job1
Waits for a job named "Job1" to exit the "Running" state. While waiting, shows
a waiting cursor and the elapsed time.
.NOTES
This is not a stand-in replacement for Wait-Job. It does not provide the full
set of configuration options that Wait-Job does.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[string] $JobName,
[string] $Description = ""
)
$animationFrames = '|','/','-','\'
$framesPerSecond = 9
# We'll wrap the description (if provided) in brackets for display purposes.
if ($Description -ne "")
{
$Description = "[$Description]"
}
$iteration = 0
while (((Get-Job -Name $JobName).state -eq 'Running'))
{
Write-InteractiveHost "`r$($animationFrames[$($iteration % $($animationFrames.Length))]) Elapsed: $([int]($iteration / $framesPerSecond)) second(s) $Description" -NoNewline -f Yellow
Start-Sleep -Milliseconds ([int](1000/$framesPerSecond))
$iteration++
}
if ((Get-Job -Name $JobName).state -eq 'Completed')
{
Write-InteractiveHost "`rDONE - Operation took $([int]($iteration / $framesPerSecond)) second(s) $Description" -NoNewline -f Green
# We forcibly set Verbose to false here since we don't need it printed to the screen, since we just did above -- we just need to log it.
Write-Log -Message "DONE - Operation took $([int]($iteration / $framesPerSecond)) second(s) $Description" -Level Verbose -Verbose:$false
}
else
{
Write-InteractiveHost "`rDONE (FAILED) - Operation took $([int]($iteration / $framesPerSecond)) second(s) $Description" -NoNewline -f Red
# We forcibly set Verbose to false here since we don't need it printed to the screen, since we just did above -- we just need to log it.
Write-Log -Message "DONE (FAILED) - Operation took $([int]($iteration / $framesPerSecond)) second(s) $Description" -Level Verbose -Verbose:$false
}
Write-InteractiveHost ""
}
function Format-SimpleTableString
{
<#
.SYNOPSIS
Gets a string representation of the provided object as a table, with some
additional formatting applied to make it easier to append to existing
string output.
.DESCRIPTION
Gets a string representation of the provided object as a table, with some
additional formatting applied to make it easier to append to existing
string output.
Will remove any leading or trailing empty lines, and adds the ability to
ident all of the content the indicated number of spaces.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER Object
The object to be formatted as a table.
.PARAMETER IndentationLevel
The number of spaces that this should be indented.
Defaults to 0.
.EXAMPLE
Format-SimpleTableString @{"Name" = "Foo"; "Value" = "Bar"}
Formats to a table with no indentation, and no leading or trailing empty lines.
.EXAMPLE
Format-SimpleTableString @{"Name" = "Foo"; "Value" = "Bar"} -IndentationLevel 5
Formats to a table with no leading or trailing empty lines, and every line is indented
with 5 spaces.
.EXAMPLE
@{"Name" = "Foo"; "Value" = "Bar"} | Format-SimpleTableString
Formats to a table with no indentation, and no leading or trailing empty lines.
This works due to pipeline input.
.INPUTS
Hashtables (generally), but can also be arrays as well.
.OUTPUTS
System.String
.NOTES
Because this uses pipeline input, if you pass an array via $Object, PowerShell
will unwrap it so that each element is processed individually. That doesn't
work well when we're trying to then pass the array once again to Format-Table.
So, we'll simply re-create an array from the individual elements, and then send
that on to Format-Table.
#>
[CmdletBinding()]
Param(
[Parameter(
ValueFromPipeline,
Mandatory)]
$Object,
[ValidateRange(1,30)]
[Int16] $IndentationLevel = 0
)
Begin
{
$objects = @()
}
Process
{
$objects += $Object
}
End
{
if ($objects.count -gt 0)
{
Write-Output "$(" " * $IndentationLevel)$(($objects | Format-Table | Out-String).TrimStart($([Environment]::NewLine)).TrimEnd([Environment]::NewLine).Replace([Environment]::NewLine, "$([Environment]::NewLine)$(" " * $IndentationLevel)"))"
}
}
}
function DeepCopy-Object
<#
.SYNOPSIS
Creates a deep copy of a serializable object.
.DESCRIPTION
Creates a deep copy of a serializable object.
By default, PowerShell performs shallow copies (simple references)
when assigning objects from one variable to another. This will
create full exact copies of the provided object so that they
can be manipulated independently of each other, provided that the
object being copied is serializable.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER Object
The object that is to be copied. This must be serializable or this will fail.
.EXAMPLE
$bar = DeepCopy-Object $foo
Assuming that $foo is serializable, $bar will now be an exact copy of $foo, but
any changes that you make to one will not affect the other.
.RETURNS
An exact copy of the PSObject that was just deep copied.
#>
{
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification="Intentional. This isn't exported, and needed to be explicit relative to Copy-Object.")]
param(
[Parameter(Mandatory)]
[PSCustomObject] $Object
)
$serialData = [System.Management.Automation.PSSerializer]::Serialize($Object, 64)
return [System.Management.Automation.PSSerializer]::Deserialize($serialData)
}
function Get-SHA512Hash
{
<#
.SYNOPSIS
Gets the SHA512 hash of the requested string.
.DESCRIPTION
Gets the SHA512 hash of the requested string.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER PlainText
The plain text that you want the SHA512 hash for.
.EXAMPLE
Get-SHA512Hash -PlainText "Hello World"
Returns back the string "2C74FD17EDAFD80E8447B0D46741EE243B7EB74DD2149A0AB1B9246FB30382F27E853D8585719E0E67CBDA0DAA8F51671064615D645AE27ACB15BFB1447F459B"
which represents the SHA512 hash of "Hello World"
.OUTPUTS
System.String - A SHA512 hash of the provided string
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[AllowNull()]
[AllowEmptyString()]
[string] $PlainText
)
$sha512= New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
return [System.BitConverter]::ToString($sha512.ComputeHash($utf8.GetBytes($PlainText))) -replace '-', ''
}
function ConvertTo-Array
{
<#
.SYNOPSIS
Converts a value (or pipeline input) into an array.
.DESCRIPTION
Converts a value (or pipeline input) into an array.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER Value
The value to convert into an array
.EXAMPLE
$foo = @{ "a" = 1; "b" = 2}; $foo.Keys | ConvertTo-Array
Returns back an array of the keys (as opposed to a KeyCollection)
.OUTPUTS
[Object[]]
#>
param(
[Parameter(
Mandatory,
ValueFromPipeline)]
[Object] $Value
)
Begin
{
$output = @();
}
Process
{
$output += $_;
}
End
{
return ,$output;
}
}
function Write-Log
{
<#
.SYNOPSIS
Writes logging information to screen and log file simultaneously.
.DESCRIPTION
Writes logging information to screen and log file simultaneously.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER Message
The message(s) to be logged. Each element of the array will be written to a separate line.
This parameter supports pipelining but there are no
performance benefits to doing so. For more information, see the .NOTES for this
cmdlet.
.PARAMETER Level
The type of message to be logged.
.PARAMETER Indent
The number of spaces to indent the line in the log file.
.PARAMETER Path
The log file path.
Defaults to $env:USERPROFILE\Documents\StoreBroker.log
.PARAMETER Exception
If present, the exception information will be logged after the messages provided.
The actual string that is logged is obtained by passing this object to Out-String.
.EXAMPLE
Write-Log -Message "Everything worked." -Path C:\Debug.log
Writes the message "Everything worked." to the screen as well as to a log file at "c:\Debug.log",
with the caller's username and a date/time stamp prepended to the message.
.EXAMPLE
Write-Log -Message ("Everything worked.", "No cause for alarm.") -Path C:\Debug.log
Writes the following message to the screen as well as to a log file at "c:\Debug.log",
with the caller's username and a date/time stamp prepended to the message:
Everything worked.
No cause for alarm.
.EXAMPLE
Write-Log -Message "There may be a problem..." -Level Warning -Indent 2
Writes the message "There may be a problem..." to the warning pipeline indented two spaces,
as well as to the default log file with the caller's username and a date/time stamp
prepended to the message.
.EXAMPLE
try { $null.Do() }
catch { Write-Log -Message ("There was a problem.", "Here is the exception information:") -Exception $_ -Level Error }
Logs the message:
Write-Log : 2018-01-23 12:57:37 : dabelc : There was a problem.
Here is the exception information:
You cannot call a method on a null-valued expression.
At line:1 char:7
+ try { $null.Do() } catch { Write-Log -Message ("There was a problem." ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
.INPUTS
System.String
.NOTES
$global:SBLogPath indicates where the log file will be created.
$global:SBLoggingEnabled determines if log entries will be made to the log file.
If $false, log entries will ONLY go to the relevant output pipeline.
Note that, although this function supports pipeline input to the -Message parameter,
there is NO performance benefit to using the pipeline. This is because the pipeline
input is simply accumulated and not acted upon until all input has been received.
This behavior is intentional, in order for a statement like:
"Multiple", "messages" | Write-Log -Exception $ex -Level Error
to make sense. In this case, the cmdlet should accumulate the messages and, at the end,
include the exception information.
#>
[CmdletBinding(SupportsShouldProcess)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "", Justification="Methods called within here make use of PSShouldProcess, and the switch is passed on to them inherently.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
param(
[Parameter(ValueFromPipeline)]
[AllowEmptyCollection()]
[AllowEmptyString()]
[AllowNull()]
[string[]] $Message = @(),
[ValidateSet('Error', 'Warning', 'Info', 'Verbose', 'Debug')]
[string] $Level = 'Info',
[ValidateRange(1, 30)]
[Int16] $Indent = 0,
[IO.FileInfo] $Path = "$global:SBLogPath",
[System.Management.Automation.ErrorRecord] $Exception
)
Begin
{
# Accumulate the list of Messages, whether by pipeline or parameter.
$messages = @()
}
Process
{
foreach ($m in $Message)
{
$messages += $m
}
}
End
{
if ($null -ne $Exception)
{
# If we have an exception, add it after the accumulated messages.
$messages += Out-String -InputObject $Exception
}
elseif ($messages.Count -eq 0)
{
# If no exception and no messages, we should early return.
return
}
# Finalize the string to be logged.
$finalMessage = $messages -join [Environment]::NewLine
# Build the console and log-specific messages.
$date = Get-Date
$dateString = $date.ToString("yyyy-MM-dd HH:mm:ss")
if ($global:SBUseUTC)
{
$dateString = $date.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ssZ")
}
$consoleMessage = '{0}{1} : {2} : {3}' -f
(" " * $Indent),
$dateString,
$env:username,
$finalMessage
if ($global:SBShouldLogPid)
{
$maxPidDigits = 10 # This is an estimate (see https://stackoverflow.com/questions/17868218/what-is-the-maximum-process-id-on-windows)
$pidColumnLength = $maxPidDigits + "[]".Length
$logFileMessage = "{0}{1} : {2, -$pidColumnLength} : {3} : {4} : {5}" -f
(" " * $Indent),
$dateString,
"[$global:PID]",
$env:username,
$Level.ToUpper(),
$finalMessage
}
else
{
$logFileMessage = '{0}{1} : {2} : {3} : {4}' -f
(" " * $Indent),
$dateString,
$env:username,
$Level.ToUpper(),
$finalMessage
}
# Write the message to screen/log.
# Note that the below logic could easily be moved to a separate helper function, but a concious
# decision was made to leave it here. When this cmdlet is called with -Level Error, Write-Error
# will generate a WriteErrorException with the origin being Write-Log. If this call is moved to
# a helper function, the origin of the WriteErrorException will be the helper function, which
# could confuse an end user.
switch ($Level)
{
'Error' { Write-Error $consoleMessage }
'Warning' { Write-Warning $consoleMessage }
'Verbose' { Write-Verbose $consoleMessage }
'Debug' { Write-Debug $consoleMessage }
'Info' {
# We'd prefer to use Write-Information to enable users to redirect that pipe if
# they want, unfortunately it's only available on v5 and above. We'll fallback to
# using Write-Host for earlier versions (since we still need to support v4).
if ($PSVersionTable.PSVersion.Major -ge 5)
{
Write-Information $consoleMessage -InformationAction Continue
}
else
{
Write-InteractiveHost $consoleMessage
}
}
}
try
{
if ($global:SBLoggingEnabled)
{
$logFileMessage | Out-File -FilePath $Path -Append
}
}
catch
{
$output = @()
$output += "Failed to add log entry to [$Path]. The error was:"
$output += Out-String -InputObject $_
if (Test-Path -Path $Path -PathType Leaf)
{
# The file exists, but likely is being held open by another process.
# Let's do best effort here and if we can't log something, just report
# it and move on.
$output += "This is non-fatal, and your command will continue. Your log file will be missing this entry:"
$output += $consoleMessage
Write-Warning ($output -join [Environment]::NewLine)
}
else
{
# If the file doesn't exist and couldn't be created, it likely will never
# be valid. In that instance, let's stop everything so that the user can
# fix the problem, since they have indicated that they want this logging to
# occur.
throw ($output -join [Environment]::NewLine)
}
}
}
}
function New-TemporaryDirectory
{
<#
.SYNOPSIS
Creates a new subdirectory within the users's temporary directory and returns the path.
.DESCRIPTION
Creates a new subdirectory within the users's temporary directory and returns the path.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.EXAMPLE
New-TemporaryDirectory
Creates a new directory with a GUID under $env:TEMP
.OUTPUTS
System.String - The path to the newly created temporary directory
#>
[CmdletBinding(SupportsShouldProcess)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "", Justification="Methods called within here make use of PSShouldProcess, and the switch is passed on to them inherently.")]
param()
$guid = [System.GUID]::NewGuid()
while (Test-Path -PathType Container (Join-Path -Path $env:TEMP -ChildPath $guid))
{
$guid = [System.GUID]::NewGuid()
}
$tempFolderPath = Join-Path -Path $env:TEMP -ChildPath $guid
Write-Log -Message "Creating temporary directory: $tempFolderPath" -Level Verbose
New-Item -ItemType directory -Path $tempFolderPath
}
function Send-SBMailMessage
{
<#
.SYNOPSIS
Sends an email message.
.DESCRIPTION
A StoreBroker wrapper around Send-MailMessage.
This will automatically CC the sender if they aren't in the receipient list already.
This will automatically add a default domain name to any incomplete email address.
Users can configure a number of global variables to change the behavior of this method.
These variables are given default values upon module load
$global:SBNotifyDefaultDomain - The default domain name to append to any incomplete email address
[defaults to $null]
$global:SBNotifyDefaultFrom - The default sender's email address
[defaults to the logged-in user's username]
$global:SBNotifySmtpServer - The SMTP Server to be used
[defaults to $null]
$global:SBNotifyCredential - The credentials needed to send mail through that SMTP Server
[defaults to $null]
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER Subject
The subject of the email message.
.PARAMETER Body
The body of the email message.
.PARAMETER To
This can be a single email address, or a list of email address to send the email to.
.EXAMPLE
Send-SBMailMessage -Subject "Test" -Body "Hello"
Assuming the user hasn't modified the global SBNotify* global variables, this will send
a new email message with the subject "Test" and body "Hello" from $($env:username)@microsoft.com,
and To that same email address, using Microsoft's internal SMTP server that doesn't require
additional authentication information beyond logged-in user domain credentials.
#>
[CmdletBinding(SupportsShouldProcess)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
param(
[string] $Subject,
[string] $Body,
[string[]] $To = $global:SBNotifyDefaultFrom
)
# Normalize all the "To" email addresses and make sure that they have a domain name attached to them
$fixedTo = @()
$To | ForEach-Object {
if ($_ -like "*@*")
{
$fixedTo += $_
}
else
{
$fixedTo += "$_@$global:SBNotifyDefaultDomain"
}
}
# Do the same for the "From" email address
$fixedFrom = $global:SBNotifyDefaultFrom
if ($fixedFrom -notlike "*@*")
{
$fixedFrom = "$fixedFrom@$global:SBNotifyDefaultDomain"
}
$params = @{}
$params.Add("To", $fixedTo)
$params.Add("From", $fixedFrom)
$params.Add("Subject", $Subject)
$params.Add("Body", $Body)
$params.Add("SmtpServer", $global:SBNotifySmtpServer)
# We'll always CC the sender if they're not already sending the mail to themselves
if (-not $fixedTo.Contains($fixedFrom))
{
$params.Add("CC", $fixedFrom)
}
# Only add the Credential if the user had to specify it
if ($null -ne $global:SBNotifyCredential)
{
$params.Add("Credential", $global:SBNotifyCredential)
}
if ($PSCmdlet.ShouldProcess($Params, "Send-MailMessage"))
{
$maxRetries = 5; # Some SMTP servers are flakey, so we'll allow for retrying on failure.
$retryBackoffSeconds = 30; # When we do retry, how much time will we wait before trying again?
$remainingAttempts = $maxRetries
while ($remainingAttempts -gt 0)
{
$remainingAttempts--
Write-Log -Message "Sending email to $($fixedTo -join ', ')" -Level Verbose
try
{
Send-MailMessage @Params
$remainingAttempts = 0
}
catch
{
if ($remainingAttempts -gt 0)
{
Write-Log -Message "Exception trying to send mail. Will try again in $retryBackoffSeconds seconds." -Exception $_ -Level Warning
Start-Sleep -Seconds $retryBackoffSeconds
}
else
{
Write-Log -Message "Exception trying to send mail. Retry attempts exhausted. Unable to send email." -Exception $_ -Level Error
}
}
}
}
}
$script:alwaysRedactParametersForLogging = @(
'AccessToken' # Would be a security issue
)
$script:alwaysExcludeParametersForLogging = @(
'NoStatus'
)
function Write-InvocationLog
{
<#
.SYNOPSIS
Writes a log entry for the invoke command.
.DESCRIPTION
Writes a log entry for the invoke command.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER InvocationInfo
The '$MyInvocation' object from the calling function.
No need to explicitly provide this if you're trying to log the immediate function this is
being called from.
.PARAMETER RedactParameter
An optional array of parameter names that should be logged, but their values redacted.
.PARAMETER ExcludeParameter
An optional array of parameter names that should simply not be logged.
.EXAMPLE
Write-InvocationLog -Invocation $MyInvocation
.EXAMPLE
Write-InvocationLog -Invocation $MyInvocation -ExcludeParameter @('Properties', 'Metrics')
.NOTES
The actual invocation line will not be _completely_ accurate as converted parameters will
be in JSON format as opposed to PowerShell format. However, it should be sufficient enough
for debugging purposes.
ExcludeParamater will always take precedence over RedactParameter.
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Management.Automation.InvocationInfo] $Invocation = (Get-Variable -Name MyInvocation -Scope 1 -ValueOnly),
[string[]] $RedactParameter,
[string[]] $ExcludeParameter
)
$jsonConversionDepth = 20 # Seems like it should be more than sufficient
# Build up the invoked line, being sure to exclude and/or redact any values necessary
$params = @()
foreach ($param in $Invocation.BoundParameters.GetEnumerator())
{
if ($param.Key -in ($script:alwaysExcludeParametersForLogging + $ExcludeParameter))
{
continue
}
if ($param.Key -in ($script:alwaysRedactParametersForLogging + $RedactParameter))
{
$params += "-$($param.Key) <redacted>"
}
else
{
if ($param.Value -is [switch])
{
$params += "-$($param.Key):`$$($param.Value.ToBool().ToString().ToLower())"
}
else
{
$params += "-$($param.Key) $($param.Value | ConvertTo-Json -Depth $jsonConversionDepth -Compress)"
}
}
}
Write-Log -Message "[$($Invocation.MyCommand.Module.Version)] Executing: $($Invocation.MyCommand) $($params -join ' ')" -Level Verbose
}
function Write-InteractiveHost
{
<#
.SYNOPSIS
Forwards to Write-Host only if the host is interactive, else does nothing.
.DESCRIPTION
A proxy function around Write-Host that detects if the host is interactive
before calling Write-Host. Use this instead of Write-Host to avoid failures in
non-interactive hosts.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.EXAMPLE
Write-InteractiveHost "Test"
Write-InteractiveHost "Test" -NoNewline -f Yellow
.NOTES
Boilerplate is generated using these commands:
# $Metadata = New-Object System.Management.Automation.CommandMetaData (Get-Command Write-Host)
# [System.Management.Automation.ProxyCommand]::Create($Metadata) | Out-File temp
#>
[CmdletBinding(
HelpUri='http://go.microsoft.com/fwlink/?LinkID=113426',
RemotingCapability='None')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification="This provides a wrapper around Write-Host. In general, we'd like to use Write-Information, but it's not supported on PS 4.0 which we need to support.")]
param(
[Parameter(
Position=0,
ValueFromPipeline,
ValueFromRemainingArguments)]
[System.Object] $Object,
[switch] $NoNewline,
[System.Object] $Separator,
[System.ConsoleColor] $ForegroundColor,
[System.ConsoleColor] $BackgroundColor
)
# Determine if the host is interactive
if ([Environment]::UserInteractive -and `
![Bool]([Environment]::GetCommandLineArgs() -like '-noni*') -and `
(Get-Host).Name -ne 'Default Host')
{
# Special handling for OutBuffer (generated for the proxy function)
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
Write-Host @PSBoundParameters
}
}
function Resolve-UnverifiedPath
{
<#
.SYNOPSIS
A wrapper around Resolve-Path that works for paths that exist as well
as for paths that don't (Resolve-Path normally throws an exception if
the path doesn't exist.)
.DESCRIPTION
A wrapper around Resolve-Path that works for paths that exist as well
as for paths that don't (Resolve-Path normally throws an exception if
the path doesn't exist.)
The Git repo for this module can be found here: https://aka.ms/StoreBroker
.EXAMPLE
Resolve-UnverifiedPath -Path 'c:\windows\notepad.exe'
Returns the string 'c:\windows\notepad.exe'.
.EXAMPLE
Resolve-UnverifiedPath -Path '..\notepad.exe'
Returns the string 'c:\windows\notepad.exe', assuming that it's executed from
within 'c:\windows\system32' or some other sub-directory.
.EXAMPLE
Resolve-UnverifiedPath -Path '..\foo.exe'
Returns the string 'c:\windows\foo.exe', assuming that it's executed from
within 'c:\windows\system32' or some other sub-directory, even though this
file doesn't exist.
.OUTPUTS
[string] - The fully resolved path
#>
[CmdletBinding()]
param(
[Parameter(
Position=0,
ValueFromPipeline)]
[string] $Path
)
$resolvedPath = Resolve-Path -Path $Path -ErrorVariable resolvePathError -ErrorAction SilentlyContinue
if ($null -eq $resolvedPath)
{
return $resolvePathError[0].TargetObject
}
else
{
return $resolvedPath.ProviderPath
}
}
function Ensure-Directory
{
<#
.SYNOPSIS
A utility function for ensuring a given directory exists.
.DESCRIPTION
A utility function for ensuring a given directory exists.
If the directory does not already exist, it will be created.
.PARAMETER Path
A full or relative path to the directory that should exist when the function exits.
.NOTES
Uses the Resolve-UnverifiedPath function to resolve relative paths.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification = "Unable to find a standard verb that satisfies describing the purpose of this internal helper method.")]
param(
[Parameter(Mandatory)]
[string] $Path
)
try
{
$Path = Resolve-UnverifiedPath -Path $Path
if (-not (Test-Path -PathType Container -Path $Path))
{
Write-Log -Message "Creating directory: [$Path]" -Level Verbose
New-Item -ItemType Directory -Path $Path | Out-Null
}
}
catch
{
Write-Log -Message "Could not ensure directory: [$Path]" -Level Error
throw
}
}
function Get-HttpWebResponseContent
{
<#
.SYNOPSIS
Returns the content that may be contained within an HttpWebResponse object.
.DESCRIPTION
Returns the content that may be contained within an HttpWebResponse object.
This would commonly be used when trying to get the potential content
returned within a failing WebResponse. Normally, when you call