-
Notifications
You must be signed in to change notification settings - Fork 33
/
PowerShellCookbook.psm1
8275 lines (6544 loc) · 503 KB
/
PowerShellCookbook.psm1
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
function Add-ExtendedFileProperties
{
##############################################################################
##
## Add-ExtendedFileProperties
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Add the extended file properties normally shown in Exlorer's
"File Properties" tab.
.EXAMPLE
PS > Get-ChildItem | Add-ExtendedFileProperties.ps1 | Format-Table Name,"Bit Rate"
#>
begin
{
Set-StrictMode -Version 3
## Create the Shell.Application COM object that provides this
## functionality
$shellObject = New-Object -Com Shell.Application
## Remember the column property mappings
$columnMappings = @{}
}
process
{
## Store the property names and identifiers for all of the shell
## properties
$itemProperties = @{}
## Get the file from the input pipeline. If it is just a filename
## (rather than a real file,) piping it to the Get-Item cmdlet will
## get the file it represents.
$fileItem = $_ | Get-Item
## Don't process directories
if($fileItem.PsIsContainer)
{
$fileItem
return
}
## Extract the file name and directory name
$directoryName = $fileItem.DirectoryName
$filename = $fileItem.Name
## Create the folder object and shell item from the COM object
$folderObject = $shellObject.NameSpace($directoryName)
$item = $folderObject.ParseName($filename)
## Populate the item properties
$counter = 0
$columnName = ""
do
{
if(-not $columnMappings[$counter])
{
$columnMappings[$counter] = $folderObject.GetDetailsOf(
$folderObject.Items, $counter)
}
$columnName = $columnMappings[$counter]
if($columnName)
{
$itemProperties[$columnName] =
$folderObject.GetDetailsOf($item, $counter)
}
$counter++
} while($columnName)
## Process extended properties
foreach($name in
$item.ExtendedProperty('System.PropList.FullDetails').Split(';'))
{
$name = $name.Replace("*","")
$itemProperties[$name] = $item.ExtendedProperty($name)
}
## Now, go through each property and add its information as a
## property to the file we are about to return
foreach($itemProperty in $itemProperties.Keys)
{
$value = $itemProperties[$itemProperty]
if($value)
{
$fileItem | Add-Member NoteProperty $itemProperty `
$value -ErrorAction `
SilentlyContinue
}
}
## Finally, return the file with the extra shell information
$fileItem
}
}
function Add-FormatData
{
##############################################################################
##
## Add-FormatData
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Adds a table formatting definition for the specified type name.
.EXAMPLE
PS > $r = [PSCustomObject] @{
Name = "Lee";
Phone = "555-1212";
SSN = "123-12-1212"
}
PS > $r.PSTypeNames.Add("AddressRecord")
PS > Add-FormatData -TypeName AddressRecord -TableColumns Name, Phone
PS > $r
Name Phone
---- -----
Lee 555-1212
#>
param(
## The type name (or PSTypeName) that the table definition should
## apply to.
$TypeName,
## The columns to be displayed by default
[string[]] $TableColumns
)
Set-StrictMode -Version 3
## Define the columns within a table control row
$rowDefinition = New-Object Management.Automation.TableControlRow
## Create left-aligned columns for each provided column name
foreach($column in $TableColumns)
{
$rowDefinition.Columns.Add(
(New-Object Management.Automation.TableControlColumn "Left",
(New-Object Management.Automation.DisplayEntry $column,"Property")))
}
$tableControl = New-Object Management.Automation.TableControl
$tableControl.Rows.Add($rowDefinition)
## And then assign the table control to a new format view,
## which we then add to an extended type definition. Define this view for the
## supplied custom type name.
$formatViewDefinition = New-Object Management.Automation.FormatViewDefinition "TableView",$tableControl
$extendedTypeDefinition = New-Object Management.Automation.ExtendedTypeDefinition $TypeName
$extendedTypeDefinition.FormatViewDefinition.Add($formatViewDefinition)
## Add the definition to the session, and refresh the format data
[Runspace]::DefaultRunspace.InitialSessionState.Formats.Add($extendedTypeDefinition)
Update-FormatData
}
function Add-FormatTableIndexParameter
{
##############################################################################
##
## Add-FormatTableIndexParameter
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Adds a new -IncludeIndex switch parameter to the Format-Table command
to help with array indexing.
.NOTES
This commands builds on New-CommandWrapper, also included in the Windows
PowerShell Cookbook.
.EXAMPLE
PS > $items = dir
PS > $items | Format-Table -IncludeIndex
PS > $items[4]
#>
Set-StrictMode -Version 3
New-CommandWrapper Format-Table `
-AddParameter @{
@{
Name = 'IncludeIndex';
Attributes = "[Switch]"
} = {
function Add-IndexParameter {
begin
{
$psIndex = 0
}
process
{
## If this is the Format-Table header
if($_.GetType().FullName -eq `
"Microsoft.PowerShell.Commands.Internal." +
"Format.FormatStartData")
{
## Take the first column and create a copy of it
$formatStartType =
$_.shapeInfo.tableColumnInfoList[0].GetType()
$clone =
$formatStartType.GetConstructors()[0].Invoke($null)
## Add a PSIndex property
$clone.PropertyName = "PSIndex"
$clone.Width = $clone.PropertyName.Length
## And add its information to the header information
$_.shapeInfo.tableColumnInfoList.Insert(0, $clone)
}
## If this is a Format-Table entry
if($_.GetType().FullName -eq `
"Microsoft.PowerShell.Commands.Internal." +
"Format.FormatEntryData")
{
## Take the first property and create a copy of it
$firstField =
$_.formatEntryInfo.formatPropertyFieldList[0]
$formatFieldType = $firstField.GetType()
$clone =
$formatFieldType.GetConstructors()[0].Invoke($null)
## Set the PSIndex property value
$clone.PropertyValue = $psIndex
$psIndex++
## And add its information to the entry information
$_.formatEntryInfo.formatPropertyFieldList.Insert(
0, $clone)
}
$_
}
}
$newPipeline = { __ORIGINAL_COMMAND__ | Add-IndexParameter }
}
}
}
function Add-ObjectCollector
{
##############################################################################
##
## Add-ObjectCollector
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Adds a new Out-Default command wrapper to store up to 500 elements from
the previous command. This wrapper stores output in the $ll variable.
.EXAMPLE
PS > Get-Command $pshome\powershell.exe
CommandType Name Definition
----------- ---- ----------
Application powershell.exe C:\Windows\System32\Windo...
PS > $ll.Definition
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
.NOTES
This command builds on New-CommandWrapper, also included in the Windows
PowerShell Cookbook.
#>
Set-StrictMode -Version 3
New-CommandWrapper Out-Default `
-Begin {
$cachedOutput = New-Object System.Collections.ArrayList
} `
-Process {
## If we get an input object, add it to our list of objects
if($_ -ne $null) { $null = $cachedOutput.Add($_) }
while($cachedOutput.Count -gt 500) { $cachedOutput.RemoveAt(0) }
} `
-End {
## Be sure we got objects that were not just errors (
## so that we don't wipe out the saved output when we get errors
## trying to work with it.)
## Also don't caputre formatting information, as those objects
## can't be worked with.
$uniqueOutput = $cachedOutput | Foreach-Object {
$_.GetType().FullName } | Select -Unique
$containsInterestingTypes = ($uniqueOutput -notcontains `
"System.Management.Automation.ErrorRecord") -and
($uniqueOutput -notlike `
"Microsoft.PowerShell.Commands.Internal.Format.*")
## If we actually had output, and it was interesting information,
## save the output into the $ll variable
if(($cachedOutput.Count -gt 0) -and $containsInterestingTypes)
{
$GLOBAL:ll = $cachedOutput | % { $_ }
}
}
}
function Add-RelativePathCapture
{
##############################################################################
##
## Add-RelativePathCapture
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Adds a new CommandNotFound handler that captures relative path
navigation without having to explicitly call 'Set-Location'
.EXAMPLE
PS C:\Users\Lee\Documents>..
PS C:\Users\Lee>...
PS C:\>
#>
Set-StrictMode -Version 3
$executionContext.SessionState.InvokeCommand.CommandNotFoundAction = {
param($CommandName, $CommandLookupEventArgs)
## If the command is only dots
if($CommandName -match '^\.+$')
{
## Associate a new command that should be invoked instead
$CommandLookupEventArgs.CommandScriptBlock = {
## Count the number of dots, and run "Set-Location .." one
## less time.
for($counter = 0; $counter -lt $CommandName.Length - 1; $counter++)
{
Set-Location ..
}
## We call GetNewClosure() so that the reference to $CommandName can
## be used in the new command.
}.GetNewClosure()
## Stop going through the command resolution process. This isn't
## strictly required in the CommandNotFoundAction.
$CommandLookupEventArgs.StopSearch = $true
}
}
}
function Compare-Property
{
##############################################################################
##
## Compare-Property
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Compare the property you provide against the input supplied to the script.
This provides the functionality of simple Where-Object comparisons without
the syntax required for that cmdlet.
.EXAMPLE
PS Get-Process | Compare-Property Handles gt 1000
.EXAMPLE
PS > Set-Alias ?? Compare-Property
PS > dir | ?? PsIsContainer
#>
param(
## The property to compare
$Property,
## The operator to use in the comparison
$Operator = "eq",
## The value to compare with
$MatchText = "$true"
)
Begin { $expression = "`$_.$property -$operator `"$matchText`"" }
Process { if(Invoke-Expression $expression) { $_ } }
}
function Connect-WebService
{
##############################################################################
##
## Connect-WebService
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Connect to a given web service, and create a type that allows you to
## interact with that web service. In PowerShell version two, use the
## New-WebserviceProxy cmdlet.
##
## Example:
##
## $wsdl = "http://www.terraserver-usa.com/TerraService2.asmx?WSDL"
## $terraServer = Connect-WebService $wsdl
## $place = New-Object Place
## $place.City = "Redmond"
## $place.State = "WA"
## $place.Country = "USA"
## $facts = $terraserver.GetPlaceFacts($place)
## $facts.Center
##
##############################################################################
param(
## The URL that contains the WSDL
[string] $WsdlLocation = $(throw "Please specify a WSDL location"),
## The namespace to use to contain the web service proxy
[string] $Namespace,
## Switch to identify web services that require authentication
[Switch] $RequiresAuthentication
)
## Create the web service cache, if it doesn't already exist
if(-not (Test-Path Variable:\Lee.Holmes.WebServiceCache))
{
${GLOBAL:Lee.Holmes.WebServiceCache} = @{}
}
## Check if there was an instance from a previous connection to
## this web service. If so, return that instead.
$oldInstance = ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation]
if($oldInstance)
{
$oldInstance
return
}
## Load the required Web Services DLL
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web.Services")
## Download the WSDL for the service, and create a service description from
## it.
$wc = New-Object System.Net.WebClient
if($requiresAuthentication)
{
$wc.UseDefaultCredentials = $true
}
$wsdlStream = $wc.OpenRead($wsdlLocation)
## Ensure that we were able to fetch the WSDL
if(-not (Test-Path Variable:\wsdlStream))
{
return
}
$serviceDescription =
[Web.Services.Description.ServiceDescription]::Read($wsdlStream)
$wsdlStream.Close()
## Ensure that we were able to read the WSDL into a service description
if(-not (Test-Path Variable:\serviceDescription))
{
return
}
## Import the web service into a CodeDom
$serviceNamespace = New-Object System.CodeDom.CodeNamespace
if($namespace)
{
$serviceNamespace.Name = $namespace
}
$codeCompileUnit = New-Object System.CodeDom.CodeCompileUnit
$serviceDescriptionImporter =
New-Object Web.Services.Description.ServiceDescriptionImporter
$serviceDescriptionImporter.AddServiceDescription(
$serviceDescription, $null, $null)
[void] $codeCompileUnit.Namespaces.Add($serviceNamespace)
[void] $serviceDescriptionImporter.Import(
$serviceNamespace, $codeCompileUnit)
## Generate the code from that CodeDom into a string
$generatedCode = New-Object Text.StringBuilder
$stringWriter = New-Object IO.StringWriter $generatedCode
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$provider.GenerateCodeFromCompileUnit($codeCompileUnit, $stringWriter, $null)
## Compile the source code.
$references = @("System.dll", "System.Web.Services.dll", "System.Xml.dll")
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compilerParameters.ReferencedAssemblies.AddRange($references)
$compilerParameters.GenerateInMemory = $true
$compilerResults =
$provider.CompileAssemblyFromSource($compilerParameters, $generatedCode)
## Write any errors if generated.
if($compilerResults.Errors.Count -gt 0)
{
$errorLines = ""
foreach($error in $compilerResults.Errors)
{
$errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText
}
Write-Error $errorLines
return
}
## There were no errors. Create the webservice object and return it.
else
{
## Get the assembly that we just compiled
$assembly = $compilerResults.CompiledAssembly
## Find the type that had the WebServiceBindingAttribute.
## There may be other "helper types" in this file, but they will
## not have this attribute
$type = $assembly.GetTypes() |
Where-Object { $_.GetCustomAttributes(
[System.Web.Services.WebServiceBindingAttribute], $false) }
if(-not $type)
{
Write-Error "Could not generate web service proxy."
return
}
## Create an instance of the type, store it in the cache,
## and return it to the user.
$instance = $assembly.CreateInstance($type)
## Many services that support authentication also require it on the
## resulting objects
if($requiresAuthentication)
{
if(@($instance.PsObject.Properties |
where { $_.Name -eq "UseDefaultCredentials" }).Count -eq 1)
{
$instance.UseDefaultCredentials = $true
}
}
${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation] = $instance
$instance
}
}
function Convert-TextObject
{
##############################################################################
##
## Convert-TextObject
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Convert a simple string into a custom PowerShell object.
.EXAMPLE
PS > "Hello World" | Convert-TextObject
Generates an Object with "P1=Hello" and "P2=World"
.EXAMPLE
PS > "Hello World" | Convert-TextObject -Delimiter "ll"
Generates an Object with "P1=He" and "P2=o World"
.EXAMPLE
PS > "Hello World" | Convert-TextObject -Pattern "He(ll.*o)r(ld)"
Generates an Object with "P1=llo Wo" and "P2=ld"
.EXAMPLE
PS > "Hello World" | Convert-TextObject -PropertyName FirstWord,SecondWord
Generates an Object with "FirstWord=Hello" and "SecondWord=World
.EXAMPLE
PS > "123 456" | Convert-TextObject -PropertyType $([string],[int])
Generates an Object with "Property1=123" and "Property2=456"
The second property is an integer, as opposed to a string
.EXAMPLE
PS > $ipAddress = (ipconfig | Convert-TextObject -Delim ": ")[2].P2
PS > $ipAddress
192.168.1.104
#>
[CmdletBinding(DefaultParameterSetName = "ByDelimiter")]
param(
## If specified, gives the .NET Regular Expression with which to
## split the string. The script generates properties for the
## resulting object out of the elements resulting from this split.
## If not specified, defaults to splitting on the maximum amount
## of whitespace: "\s+", as long as Pattern is not
## specified either.
[Parameter(ParameterSetName = "ByDelimiter", Position = 0)]
[string] $Delimiter = "\s+",
## If specified, gives the .NET Regular Expression with which to
## parse the string. The script generates properties for the
## resulting object out of the groups captured by this regular
## expression.
[Parameter(Mandatory = $true,
ParameterSetName = "ByPattern",
Position = 0)]
[string] $Pattern,
## If specified, the script will pair the names from this object
## definition with the elements from the parsed string. If not
## specified (or the generated object contains more properties
## than you specify,) the script uses property names in the
## pattern of P1,P2,...,PN
[Parameter(Position = 1)]
[Alias("PN")]
[string[]] $PropertyName = @(),
## If specified, the script will pair the types from this list with
## the properties from the parsed string. If not specified (or the
## generated object contains more properties than you specify,) the
## script sets the properties to be of type [string]
[Parameter(Position = 2)]
[Alias("PT")]
[type[]] $PropertyType = @(),
## The input object to process
[Parameter(ValueFromPipeline = $true)]
[string] $InputObject
)
begin {
Set-StrictMode -Version 3
}
process {
$returnObject = New-Object PSObject
$matches = $null
$matchCount = 0
if($PSBoundParameters["Pattern"])
{
## Verify that the input contains the pattern
## Populates the matches variable by default
if(-not ($InputObject -match $pattern))
{
return
}
$matchCount = $matches.Count
$startIndex = 1
}
else
{
## Verify that the input contains the delimiter
if(-not ($InputObject -match $delimiter))
{
return
}
## If so, split the input on that delimiter
$matches = $InputObject -split $delimiter
$matchCount = $matches.Length
$startIndex = 0
}
## Go through all of the matches, and add them as notes to the output
## object.
for($counter = $startIndex; $counter -lt $matchCount; $counter++)
{
$currentPropertyName = "P$($counter - $startIndex + 1)"
$currentPropertyType = [string]
## Get the property name
if($counter -lt $propertyName.Length)
{
if($propertyName[$counter])
{
$currentPropertyName = $propertyName[$counter - 1]
}
}
## Get the property value
if($counter -lt $propertyType.Length)
{
if($propertyType[$counter])
{
$currentPropertyType = $propertyType[$counter - 1]
}
}
Add-Member -InputObject $returnObject NoteProperty `
-Name $currentPropertyName `
-Value ($matches[$counter].Trim() -as $currentPropertyType)
}
$returnObject
}
}
function ConvertFrom-FahrenheitWithFunction
{
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
param([double] $Fahrenheit)
Set-StrictMode -Version 3
## Convert Fahrenheit to Celsius
function ConvertFahrenheitToCelsius([double] $fahrenheit)
{
$celsius = $fahrenheit - 32
$celsius = $celsius / 1.8
$celsius
}
$celsius = ConvertFahrenheitToCelsius $fahrenheit
## Output the answer
"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
}
function ConvertFrom-FahrenheitWithoutFunction
{
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
param([double] $Fahrenheit)
Set-StrictMode -Version 3
## Convert it to Celsius
$celsius = $fahrenheit - 32
$celsius = $celsius / 1.8
## Output the answer
"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
}
function Copy-History
{
##############################################################################
##
## Copy-History
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Copy selected commands from the history buffer into the clipboard as a script.
.EXAMPLE
PS > Copy-History
Copies the entire contents of the history buffer into the clipboard.
.EXAMPLE
PS > Copy-History -5
Copies the last five commands into the clipboard.
.EXAMPLE
PS > Copy-History 2,5,8,4
Copies commands 2,5,8, and 4.
.EXAMPLE
PS > Copy-History (1..10+5+6)
Copies commands 1 through 10, then 5, then 6, using PowerShell's array
slicing syntax.
#>
param(
## The range of history IDs to copy
[int[]] $Range
)
Set-StrictMode -Version 3
$history = @()
## If they haven't specified a range, assume it's everything
if((-not $range) -or ($range.Count -eq 0))
{
$history = @(Get-History -Count ([Int16]::MaxValue))
}
## If it's a negative number, copy only that many
elseif(($range.Count -eq 1) -and ($range[0] -lt 0))
{
$count = [Math]::Abs($range[0])
$history = (Get-History -Count $count)
}
## Otherwise, go through each history ID in the given range
## and add it to our history list.
else
{
foreach($commandId in $range)
{
if($commandId -eq -1) { $history += Get-History -Count 1 }
else { $history += Get-History -Id $commandId }
}
}
## Finally, export the history to the clipboard.
$history | Foreach-Object { $_.CommandLine } | clip.exe
}
function Enable-BreakOnError
{
#############################################################################
##
## Enable-BreakOnError
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Creates a breakpoint that only fires when PowerShell encounters an error
.EXAMPLE
PS > Enable-BreakOnError
ID Script Line Command Variable Action
-- ------ ---- ------- -------- ------
0 Out-Default ...
PS > 1/0
Entering debug mode. Use h or ? for help.
Hit Command breakpoint on 'Out-Default'
PS > $error
Attempted to divide by zero.
#>
Set-StrictMode -Version 3
## Store the current number of errors seen in the session so far
$GLOBAL:EnableBreakOnErrorLastErrorCount = $error.Count
Set-PSBreakpoint -Command Out-Default -Action {
## If we're generating output, and the error count has increased,
## break into the debugger.
if($error.Count -ne $EnableBreakOnErrorLastErrorCount)
{
$GLOBAL:EnableBreakOnErrorLastErrorCount = $error.Count
break
}
}
}
function Enable-HistoryPersistence
{
##############################################################################
##
## Enable-HistoryPersistence
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Reloads any previously saved command history, and registers for the
PowerShell.Exiting engine event to save new history when the shell
exits.
#>
Set-StrictMode -Version 3
## Load our previous history
$GLOBAL:maximumHistoryCount = 32767
$historyFile = (Join-Path (Split-Path $profile) "commandHistory.clixml")
if(Test-Path $historyFile)
{
Import-CliXml $historyFile | Add-History
}
## Register for the engine shutdown event
$null = Register-EngineEvent -SourceIdentifier `
([System.Management.Automation.PsEngineEvent]::Exiting) -Action {
## Save our history
$historyFile = (Join-Path (Split-Path $profile) "commandHistory.clixml")
$maximumHistoryCount = 1kb
## Get the previous history items
$oldEntries = @()
if(Test-Path $historyFile)
{
$oldEntries = Import-CliXml $historyFile -ErrorAction SilentlyContinue
}
## And merge them with our changes
$currentEntries = Get-History -Count $maximumHistoryCount
$additions = Compare-Object $oldEntries $currentEntries `
-Property CommandLine | Where-Object { $_.SideIndicator -eq "=>" } |
Foreach-Object { $_.CommandLine }
$newEntries = $currentEntries | ? { $additions -contains $_.CommandLine }
## Keep only unique command lines. First sort by CommandLine in
## descending order (so that we keep the newest entries,) and then
## re-sort by StartExecutionTime.
$history = @($oldEntries + $newEntries) |
Sort -Unique -Descending CommandLine | Sort StartExecutionTime