-
Notifications
You must be signed in to change notification settings - Fork 1
/
Microsoft.PowerShell_profile.txt
3151 lines (3026 loc) · 125 KB
/
Microsoft.PowerShell_profile.txt
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
#region Parameters
[CmdLetBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
param (
[switch]$Force,
[Alias('DotNet')] [switch]$ShowDotNetVersions,
[Alias('Modules')] [switch]$ShowModules,
[Alias('IModules')] [switch]$InstallModules,
[switch]$ForceModuleInstall,
[ValidateSet('AllUsers','CurrentUser')] [string]$ScopeModule='AllUsers',
[Parameter(ValueFromRemainingArguments=$true)] [string[]]$RemArgs,
[Alias('ClobberAllowed')] [switch]$AllowClobber,
[Alias('SilentlyContinue')] [switch]$Quiet,
[Alias('PSReadlineProfile','ReadlineProfile','psrl')][switch]$PSReadline,
[Alias('ForcePSReadlineProfile','fpsrl')] [switch]$ForcePSReadline,
[switch]$UpdatePackageManager
#[Alias('IAc','IAction','InfoAction')]
#[ValidateSet('SilentlyContinue','')] [switch]$InformationAction
)
If ((Get-Variable Env:NoPSProfile -value -ea Ignore) -or
(Get-Variable Env:SkipPSProfile -value -ea Ignore)) {
Write-Host "Skipping PS Profile due to environment settings" -Fore Yellow -Back DarkRed
return
}
#region Parameters
If ((Get-Item Env:NoProfile -ea Ignore) -and $Env:NoProfile.Trim() -match '^(T|Y|Skip)' ) {
Write-Host " PowerShell skip profile `$Env:NoProfile = [$($Env:NoProfile)]" -fore 'blue' -back 'Green'
ForEach ($Key in $PSBoundParameters.Keys) {
Write-Host " $Key = $($PSBoundParameters.$Key)" -fore 'blue' -back 'Green'
}
Exit
}
$Private:StartTime = Get-Date
$ErrorCount = $Error.Count
If (!(Get-Command Write-Information -ea 0)) { New-Alias Write-Information Write-Host -Scope Global }
remove-item alias:type -force -ea Ignore
new-alias type Get-Content -force -scope Global -ea Ignore
New-Alias -Name LINE -Value Get-CurrentLineNumber -Description 'Returns the current (caller''s) line number in a script.' -force -ea Ignore
New-Alias -Name __LINE__ -Value Get-CurrentLineNumber -Description 'Returns the current (caller''s) line number in a script.' -force -ea Ignore
New-Alias -Name FILE -Value Get-CurrentFileName -Description 'Returns the name of the current script file.' -force -ea Ignore
New-Alias -Name FLINE -Value Get-CurrentFileLine -Description 'Returns the name of the current script file.' -force -ea Ignore
New-Alias -Name FILE1 -Value Get-CurrentFileName1 -Description 'Returns the name of the current script file.' -force -ea Ignore
New-Alias -Name __FILE__ -Value Get-CurrentFileName -Description 'Returns the name of the current script file.' -force -ea Ignore
New-Alias TV Test-Variable -Force -ea Ignore
New-Alias TVN Test-Variable -Force -ea Ignore
Function Get-Defined {
[CmdletBinding()][OutputType([Object])]
Param(
[Parameter(Mandatory)][Alias('VariableName','VN')]
[ValidateNotNullorEmpty()][string]$Name
)
[boolean](Get-Variable $Name -ea Ignore )
}
Function Get-Value {
[CmdletBinding()][OutputType([Object])]
Param(
[Parameter(Mandatory)][Alias('VariableName','VN')]
[ValidateNotNullorEmpty()][string]$Name
)
If (Get-Variable $Name -ea Ignore) {
(Get-Variable $Name -ea Ignore -value)
}
}
Function ConvertFrom-FileTime {
[CmdletBinding()][OutputType([DateTime],[String])]Param(
[Parameter(Mandatory)][Int64]$FileTime, # 131775519645343599
[string]$Format='',
[switch]$Sortable
)
try {
If ($dt = [datetime]::FromFileTime($FileTime) ) {
If ($Sortable) { $Format = 's' }
If ($Format) { $dt = "{0:$Format}" -f $dt }
}
$dt
} catch { } # Just return $Null, no need to do more
}
# $LastLogon = ((nslookup $env:userdnsdomain | select -skip 3 ) -replace '.*\s+([\d.]{7,})?.*','$1').where{$_} | % { get-aduser martinh -Properties * -server $_ } | Select name,@{N='LastLogon';E={ConvertFrom-FileTIme -sort $_.LastLogon}},LastLogonDate,@{N='LastLogonTimeStamp';E={ConvertFrom-FileTIme -sort $_.LastLogonTimeStamp}} 131775519645343599
Function Get-CurrentLineNumber { $MyInvocation.ScriptLineNumber }
remove-item Alias:LINE -ea Ignore -force
New-Alias -Name LINE -Value Get-CurrentLineNumber -Description 'Returns the caller''s current line number'
$Private:Colors = @{ForeGroundColor = 'White'; BackGroundColor = 'DarkGreen'}
Write-Host "$(LINE) $(get-date -f 'yyyy-MM-dd HH:mm:ss') PowerShell $($psversiontable.PSVersion.tostring())" @Private:Colors
Write-Host "$(LINE) Starting error count: $ErrorCount" @Private:Colors
$ProfileDirectory = Split-Path $Profile
$PSProfile = Resolve-Path -ea Ignore $(
If ($MyInvocation.MyCommand) { $MyInvocation.MyCommand } else { $Profile }
)
$PSProfile = If (Get-Value PSProfile) { $PSprofile } else { $Profile }
$PSProfileDirectory = Split-Path $PSProfile
$ProfileLogPath = $Profile -replace '\.ps1$','LOG.txt'
$PSProfileLogPath = $PSProfile -replace '\.ps1$','LOG.txt'
Write-Host "$(LINE) Use `$Profile for path to Profile: $Profile" @Private:Colors
Write-Host "$(LINE) Use `$PSProfile for path to Profile: $PSProfile" @Private:Colors
Write-Host "$(LINE) ProfileLogPath: $ProfileLogPath" @Private:Colors
<#
.Synopsis
Locate pre & post load profiles to run
.Description
Check for ComputerDomain, UserDomain, ComputerName, UserName profiles
to run them either before (pre) or after the main profile (post)
Will generate/locate
$ProfileDirectory\Profile + NAME + Suffix + .ps1
.Parameter Suffix
Usually Pre or Post
Will generate/locate
$ProfileDirectory\Profile + NAME + Suffix + .ps1
#>
Function Get-ExtraProfile {
[CmdletBinding()]param(
[String]$Suffix,
[String[]]$Name = (@((Get-WMIObject win32_computersystem).Domain) +
@((nbtstat -n) -match '(?-i:<00>\s+GROUP\b)' -replace
'^\s*(\S+)\s*(?-i:<00>\s+GROUP\b).*$', '$1') +
$Env:UserDomain + $Env:ComputerName + $Env:UserName | Select-Object -Uniq),
[switch]$PreloadProfile,
[switch]$PostloadProfile
)
If ($PreLoadProfile) { $Name = @($Name) + '' }
If ($PostLoadProfile) { $Name = @('') + $Name }
$Name | Where-Object {
If ($Extra = Join-Path $ProfileDirectory "Profile$($_)$($Suffix).ps1" -ea Ignore -resolve) {
Write-Verbose $Extra
$Extra
}
} | ForEach-Object { $Extra } | Select-Object -uniq
}
Function Get-ProcessFile {
(Get-Process @args).Where{$_.Name -notin 'System','Idle'} |
Sort-Object -unique name,path | Get-Process -FileVersionInfo
}
Function Get-ProcessUser {
$args = $args.Where{'IncludeUserName' -notmatch $_ } |
Get-Process @args -IncludeUserName
}
$UsePreloadProfile = [Boolean](Get-Variable UsePreloadProfile -value -ea Ignore)
Get-ExtraProfile 'Pre' -PreloadProfile:$UsePreloadProfile | ForEach-Object {
try {
$Private:Separator = "`n$('=' * 72)`n"
$Private:Colors = @{ForeGroundColor = 'Blue'; BackGroundColor = 'White'}
$Private:StartTimeProfile = Get-Date -f 'yyyy-MM-dd HH:mm:ss'
$Private:ErrorCountProfile = $Error.Count
Write-Host "$($Private:Separator)$($Private:EndTimeProfile) Extra Profile`n$_$($Private:Separator)" @Private:Colors
. $_
} catch {
Write-Error "ERROR sourcing: $_`n`n$_"
} finally {
$Private:EndTimeProfile = Get-Date -f 'yyyy-MM-dd HH:mm:ss'
$Private:Duration = ((Get-Date $Private:EndTimeProfile) - (Get-Date $Private:StartTimeProfile)).TotalSeconds
Write-Host "$($Private:Separator)$($Private:EndTimeProfile) Duration:$($Private:Duration) seconds Extra Profile`n$_$($Private:Separator)" @Private:Colors
}
}
If ($Host.PrivateData -and ($host.PrivateData.ErrorBackgroundColor -as [string])) {
$host.PrivateData.errorbackgroundcolor = 'Red'
$host.PrivateData.errorForeGroundColor = 'White'
#$host.PrivateData.verbosebackgroundcolor = 'black'
$host.PrivateData.debugbackgroundcolor = 'black'
}
# 'Continue', 'Ignore', 'Inquire', 'SilentlyContinue', 'Stop', 'Suspend'
# Begin adding regions, Add cc, c alias/functions
# Fixed Alt+(,Alt+),Get-DotNetAssembly,Get-RunTime,Add Get-Accelerator,[Accelerators]
# Temporary Fix to Go(works without Jump), Scripts to path,find and run Local*.ps1"
# Fix 6.0 problems, PSGallery, Where.exe output, PSProvider
# Improved Get-ChildItem2, Add-ToolPath,++B,++DosKey,CleanPath,start Get-DirectoryListing,add refs,README.mkdir
# Show-ConsoleColor,Get-Syntax(aliases),++Select-History,++FullHelp,++d cmds, esf (needs *,? support),++Add-ToolPath,Reduce History Saved
# Started Add-Path(crude) -- more ToDo notes
# Used -EA IGNORE for most handled errors
# Added support for local-only PS1 files: ProfileXPre and ProfileXPost.ps1
# 7-Zip http://www.7-zip.org/download.html
# Git https://git-scm.com/download/win
# https://github.com/git-for-windows/git/releases/download/v2.18.0.windows.1/Git-2.18.0-64-bit.exe
# https://github.com/git-tips/tips
# C:\Program Files\Git\mingw64\share\doc\git-doc\giteveryday.html
# Regex http://www.grymoire.com/Unix/Regular.html#uh-12
# http://www.regexlib.com/DisplayPatterns.aspx
# AwkRef http://www.grymoire.com/Unix/AwkRef.html
# Notepad++ https://notepad-plus-plus.org/download/v7.5.4.html
# ArsClip http://www.joejoesoft.com/vcms/97/
# Aria2 https://github.com/aria2/aria2/releases/tag/release-1.33.1
# Deluge http://download.deluge-torrent.org/windows/?C=M;O=D
# Transmission https://transmissionbt.com/download/
# WinMerge http://developeronfire.com/blog/configuration-of-git-on-windows-to-make-life-easy
# NotesProfile See: NotesProfile.txt
# docker https://docs.docker.com/install/windows/docker-ee/#use-a-script-to-install-docker-ee
# https://github.com/wsargent/docker-cheat-sheet
# Wakoopa https://web.appstorm.net/how-to/app-management-howto/how-to-discover-new-apps-with-wakoopa/
# VirusTotal https://www.virustotal.com/#/settings/apikey
# XPDF & Tools PDFToText is the main reason I am adopting this tool:
# GUI Program: https://xpdfreader-dl.s3.amazonaws.com/XpdfReader-win64-4.00.01.exe
# CLI Tools: https://xpdfreader-dl.s3.amazonaws.com/xpdf-tools-win-4.00.zip
# Extra Fonts: https://xpdfreader-dl.s3.amazonaws.com/xpdf-t1fonts.tar.gz
# Source code: https://xpdfreader-dl.s3.amazonaws.com/xpdf-4.00.tar.gz
# https://null-byte.wonderhowto.com/how-to/use-google-hack-googledorks-0163566/
# Add to Scripts, Snippets etc.
# ToDo: Put scripts on path
# ToDo: Move notes out of this file, Use Misc1/Work Misc/Home
# ToDo: Test without Admin privs and skip issues
# ToDo: Add Update-Help as background job?
# ToDo: Updrade PowerShell to 5.1+
# ToDo: Set console colors? DarkGray = 80 80 80?
# ToDo: JOIN-PATH -resolve: NOT Test-Path -resolve , Add Server to Get-WinStaSession
# ToDo: improve go, find alias Version numbers (at least display)
# ToDo: need Notepad++, 7zip, Git, ??? to be on path with shortcuts (improved, not good enough yet)
# ToDo: LogFile was being written, written now, CHECK?
# ToDo: Clean up output -- easier to read, don't use "warnings" (colors?)
# ToDo: Setup website for initial BootStrap scripts to get tools, Profile etc.
# Run scripts from "master" ????
# Download Tools -- as job
# Sync tools -- as job or scheduled job?
# Git, Enable Scripting/Remoting etc.,
# Configure new build, Firewall off,RDP On,No IPv6 etc
# Split out functions etc to "Scripts" directory
# Speed up History loading?
# get-process notepad++ | select name,starttime,productversion,path
# gwmi win32_service -filter 'name = "everything"' | select name,StartMode,State,Status,Processid,StartName,DisplayName,PathName | ft
# Git-Windows Git (new file), previous commit worked on JR 2 machines
# Improve goHash, Books & Dev more general, fix S: T: not found
# Everything? es?
# Add rdir,cdir,mdir aliases
# Close with Set-ProgramAlias
# Add new set-programalias nscp 'C:\Program Files\NSClient++\nscp.exe' -force -scope
# Fix RDP alias, Put 7-zip, Util,Unx in S:\Programs, New program searcher? Better?
# Boottime,ProfilePath moved up,LINE/FILE/Write-LOG,LogFilePath?,7z
# Add/fix BootTime function
# Move $PSProfileDirectory up
# Move utility extract up (LINE, FILE, WRITE-LOG)
# working on LogFilePath
# worked on 7z --
# Jing imagex sharex
# C:\Program Files\ShareX\ & 'C:\Program Files\ShareX\ShareX.exe'
# https://getsharex.com/docs/amazon-s3
# PowerShell Windows Management Framework 5.1 https://www.microsoft.com/en-us/download/details.aspx?id=54616
# W2K12-KB3191565-x64.msu
# Win7AndW2K8R2-KB3191566-x64.zip
# Win7-KB3191566-x86.zip
# Win8.1AndW2K12R2-KB3191564-x64.msu
# Win8.1-KB3191564-x86.msu
# Delete multiple downloads with parenthesis numbers
# dir '*([1-9]).*' | sort name | % { if (Test-Path ($F0=$($_.FullName -replace '\s+\(\d+\)'))) { write-host "Ok: $F0" -fore Green -back 'Black' ; "del $($_.FullName)" } }
# Interact with Symbolic links using improved Item cmdlets
# https://docs.microsoft.com/en-us/powershell/wmf/5.0/feedback_symbolic
# How To Set Up Chocolatey For Organizational/Internal Use
# https://chocolatey.org/docs/how-to-setup-offline-installation
# C:\ProgramData\Ditto\Ditto.exe
# 'C:\Program Files\WinMerge2011\WinMergeU.exe'
#
# "line1","line2" -join (NL)
# "line1","line2" -join [environment]::NewLine
# https://github.com/FriedrichWeinmann/PSReadline-Utilities
# https://github.com/FriedrichWeinmann/functions
# PSFramework
# Install-Module -Scope CurrentUser -Name Assert
# Chrome key mapper? chrome://extensions/configureCommands
# Chrome extensions chrome://extensions/
# DSC_PowerCLISnapShotCheck PowerCLITools PowerCLI.SessionManager PowerRestCLI
# PowerShell CodeManager https://bytecookie.wordpress.com/
# ChocolateyGet
try {
$ProfileScriptDirectories = $ProfileDirectory, $PSProfileDirectory,
"$ProfileDirectory\Scripts*", "$PSProfileDirectory\Scripts*"
Join-Path $ProfileScriptDirectories Local*.ps1 -resolve -ea Ignore 2>$Null |
Select-Object -uniq | ForEach-Object {
try {
. $_ 2>&1
} catch {
write-warning "1: Caught error in loading local profile scripts: $_ "
}
}
} catch {
write-warning "2: Caught error in loading local profile scripts"
}
try {
# Clean the $Env:Path
$Global:Scripts = "$PSScriptRoot\Scripts"
$Global:Tools = "$PSScriptRoot\Tools"
$Script:AddPath = $Tools, $Scripts
$SavePath = (($Env:Path -split ';' -replace '(?<=[\w\)])[\\;\s]*$') + $Script:AddPath |
Where-Object { $_ -and (Test-Path $_) } | Select-Object -uniq) -join ';'
if ($SavePath) { $Env:Path, $SavePath = $SavePath, $Env:Path }
Function Measure-CommandPath {
$env:pathext -split ';' | ForEach-Object {
(Join-Path ($env:path -split ';') "*$_" -resolve -ea 0) |
ForEach-Object { Get-Item -literal $_ }
} | Group-Object DirectoryName -noelement | Sort-Object Count,Name
}
Function Get-PSVersion {"$($psversiontable.psversion.major).$($psversiontable.psversion.minor)"}
Function Test-Administrator {
([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
[Security.Principal.WindowsBuiltInRole] "Administrator")
}
#Function Test-Administrator { (whoami /all | Select-Object -string S-1-16-12288) -ne $null }
#if ((whoami /user /priv | Select-Object -string S-1-16-12288) -ne $null) {'Administrator privileges: ENABLED'} #else {'Administrator privileges: DISABLED'}
if ($AdminEnabled = Test-Administrator) {
Write-Information "$(LINE) Administrator privileges enabled"
} else { Write-Information "$(LINE) Administrator privileges DISABLED"}
write-warning "$(get-date -f 'HH:mm:ss') $(LINE)"
If ($WinMerge = Join-Path -resolve -ea ignore 'C:\Program*\WinMerge*' 'WinMerge*.exe' |
? { $_ -notmatch 'proxy' } | select -first 1) {
new-alias WinMerge $WinMerge -force -scope Global
}
#Clean the $Env:Path
$SavePath = ($Env:Path -split ';' -replace '(?<=[\w\)])[\\;\s]*$' |
Where-Object { $_ -and (Test-Path $_) } |
select -uniq) -join ';'
if ($SavePath) { $Env:Path, $SavePath = $SavePath, $Env:Path }
Function Add-ToolPath {
[CmdLetBinding()]param(
[string[]]$Path
)
ForEach ($TryPath in $Path) {
if (!(where.exe /q PortCheck.exe)) {
Write-Warning "Path is good: $(where.exe PortCheck.exe)"
return
} else {
if (Test-Path (Join-Path $TryPath "Util\PortCheck.exe" -ea ignore)) {
$addpath = ";$TryPath\util;$TryPath\Unx;$\TryPath\Bat"
$Global:Env:Path += $addpath
Write-Warning "Added: $addpath"
$Global:Env:Path >$Null
return
}
}
}
Write-Warning "Unabled to put tools on path: PortCheck.exe"
}
write-warning "$(get-date -f 'HH:mm:ss') $(LINE)"
$PlacesToLook = 'C:\','T:\Programs\Herb','T:\Programs\Tools','T:\Programs',
'S:\Programs\Tools','S:\Programs\Herb''S:\Programs' |
Where-Object { Test-Path $_ -ea ignore }
try { Add-ToolPath $PlacesToLook } catch { Write-Warning "Caught: Add-Path"}
Function DosKey {
param($Pattern='=')
if (!(where.exe 'macros.txt' /q)) {
$macros = where.exe 'macros.txt'
Get-Content $macros | Where-Object { $_ -match $Pattern }
}
}
Function B { if (!$Args) { $args = ,95} DisplayBrightnessConsole @Args }
Remove-Item Alias:C -ea Ignore -Force
New-Alias C Clear-Host -force -scope Global
Function Get-PSHistory {
param(
$UserName = $Env:UserName
)
If ($PSHistory) {
$psh = $PSHistory -replace $Env:UserName, $UserName
If ($psh -and (Test-Path $psh -ea 0)) {
(Resolve-Path $psh -ea ignore).path
} Else {
Write-Warning "PSHistory for $Username not found '$psh'"
}
} Else {
Write-Warning "PSHistory not found"
}
}
function Get-WmiNamespace {
[CmdletBinding()]Param ($Namespace='ROOT')
Get-WmiObject -Namespace $Namespace -Class __NAMESPACE | ForEach-Object {
($ns = '{0}\{1}' -f $_.__NAMESPACE,$_.Name)
Get-WmiNamespace -Namespace $ns
}
}
function Get-WmiClass {
[CmdletBinding()]Param($Pattern='^.')
Get-WmiNamespace | ForEach-Object {
Get-WmiObject -Namespace $_ -List |
ForEach-Object { $_.Path.Path } |
Where-Object { $_ -match $Pattern }
} | Sort-Object -Unique
}
Function Get-SpeechSynthesizer {
[CmdletBinding()]Param(
[Alias('gettype')][switch]$Type
)
If ($SpeechType = Add-Type -AssemblyName System.Speech -passthru) { # | gm
If ($Type) {
Write-Verbose "Returning Synthezizer, try: $SpeechType | gm -static"
$SpeechType
} else {
$SpeechSynthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$SpeechSynthesizer
If ($SpeechSynthesizer) {
Write-Verbose "Speaking now..."
If ($PSBoundParameters.ContainsKey('Verbose')) {
$SpeechSynthesizer.Speak('Hello World!')
}
} else {
Write-Verbose "No synthesizer"
}
}
}
}
<# SpeechType
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False True SRID System.Enum
False False SR System.Object
SpeechType | gm -static
#>
Function Get-MemberType{
[CmdletBinding()][Alias('IsMember','Member?','MemberP')]
Param(
[Parameter(Mandatory)][Object]$InputObject,
[Alias('Name')][string]$MemberName
)
$ChildNames = $MemberName -split '\.'
$Object = $InputObject;
Write-Verbose "ChildNames: $ChildNames"
ForEach ($Name in $ChildNames) {
Write-Verbose "1-Name: $Name $($Object.GetType())"
If (!($Member = Get-Member -Name $Name -InputObject $Object -ea Ignore)) {
Write-Verbose "Returning with no child: $Name"
return $Null # nothing there
}
Write-Verbose "2-Name: $Name Type: $($Object.GetType()) MemberType $($Member.MemberType)"
$Object = $Object.$Name
If ($Member.MemberType -notmatch 'Property') { break } # Function, etc.
}
$Object.GetType()
}
Function Set-StreamColor {
[CmdletBinding()][Alias('SSC')]Param(
[string]$StreamName = 'Error',
[string]$BackGroundColor = 'DarkRed',
[string]$ForeGroundColor = 'White'
)
If (Get-MemberType $Host "PrivateData.$($StreamName)BackgroundColor") {
$host.PrivateData."$($StreamName)BackGroundColor" = $BackGroundColor
$host.PrivateData."$($StreamName)ForeGroundColor" = $ForeGroundColor
# $host.PrivateData.debugbackgroundcolor = 'black'
}
}
Function Get-NewLine { [environment]::NewLine }; new-alias NL Get-NewLine -force
if (! (Get-Command write-log -type Function,cmdlet,alias -ea ignore)) {
new-alias write-log write-verbose -force -scope Global -ea ignore
}
#(dir C:\Util\*64.???).fullname | Where { $_ -replace '64(?=\.)' | dir -name -ea ignore } | ForEach-Object { New-Alias $($Name -replace '\.exe') $_ -force -Scope Global }
new-alias em C:\emacs\bin\runemacs.exe -force -scope Global -ea ignore
new-alias kp 'C:\Program Files (x86)\KeePass2\KeePass.exe' -force -scope Global -ea ignore
new-alias KeePass 'C:\Program Files (x86)\KeePass2\KeePass.exe' -force -scope Global -ea ignore
new-alias rdir Remove-Item -force -scope Global -ea ignore
new-alias cdir cd -force -scope Global -ea ignore
new-alias mdir mkdir -force -scope Global -ea ignore
new-alias mvdir move-item -force -scope Global -ea ignore
new-alias modir more -force -scope Global -ea ignore
new-alias moredir more -force -scope Global -ea ignore
new-alias tdir Get-Content -force -scope Global -ea ignore
new-alias typedir Get-Content -force -scope Global -ea ignore
new-alias ldir less -force -scope Global -ea ignore
new-alias lessdir less -force -scope Global -ea ignore
new-alias l less -force -scope Global -ea ignore
new-alias iv 'C:\Program Files\IrfanView\i_view64.exe' -scope Global -force -ea Ignore
<#
.Synopsis
Start Emacs using server, start server if not running
.Notes
;; This makes Emacs ignore the "-e (make-frame-visible)"
;; that it gets passed when started by emacsclientw.
;;
;(add-to-list 'command-switch-alist '("(make-frame-visible)" .
; (lambda (s))))
-V, --version Just print version info and return
-H, --help Print this usage information message
-nw, -t, --tty Open a new Emacs frame on the current terminal
-c, --create-frame Create a new frame instead of trying to
use the current Emacs frame
-F ALIST, --frame-parameters=ALIST
Set the parameters of a new frame
-e, --eval Evaluate the FILE arguments as ELisp expressions
-n, --no-wait Don't wait for the server to return
-q, --quiet Don't display messages on success
-d DISPLAY, --display=DISPLAY
Visit the file in the given display
--parent-id=ID Open in parent window ID, via XEmbed
-f SERVER, --server-file=SERVER
Set filename of the TCP authentication file
-a EDITOR, --alternate-editor=EDITOR
Editor to fallback to if the server is not running
If EDITOR is the empty string, start Emacs in daemon
mode and try connecting again
#>
Function remacs {
[CmdletBinding(DefaultParameterSetName='Path', SupportsShouldProcess, SupportsTransactions)]
[Alias('emacs','em','e')]param(
[Parameter(Position=0, ParameterSetName='Path',
ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string[]]$Path=@(),
[Parameter(Position=0, ParameterSetName='LiteralPath', Mandatory=$true,
ValueFromPipelineByPropertyName=$true)][Alias('PSPath')][string[]]$LiteralPath,
[string]$Filter = '',
[string]$Include = '',
[string]$Exclude = '',
[parameter(ValueFromRemainingArguments=$true)]$Remaining,
[Alias('H')][switch]$Help = $False,
[Alias('V')][switch]$Version = $False,
[switch]$Test = $False
)
Begin {
Set-StrictMode -Version Latest
$Verbose = $PSBoundParameters.ContainsKey('Verbose') -and $PSBoundParameters.Verbose
If ($PSBoundParameters.ContainsKey('Verbose')) { $PSBoundParameters.Remove('Verbose') }
$Process = $True
$EmacsPath = "c:\emacs\bin"
$EmacsClient = "$EmacsPath\emacsclientw.exe"
$EmacsCLI = "$EmacsPath\emacsclient.exe"
$EmacsServer = "$EmacsPath\runemacs.exe"
$ServerOptions = '-n', "--alternate-editor=$EmacsServer"
Write-Verbose "Property set: $($PSCmdlet.ParameterSetName)"
}
Process {
If ($Help) {
$Process = $False
& $EmacsCLI --help
& $EmacsCLI --version
} ElseIf ($Version) {
$Process = $False
& $EmacsCLI --version
} ElseIf ($Process) {
If ($PSBoundParameters.ContainsKey('LiteralPath')) {
$Path = @($PSBoundParameters.LiteralPath)
}
$Files = @(ForEach ($Item in $Path) {
If ($Item -match '(.*):?(\+\d+(?::\d+)?$)') {
$Matches[2]
If ($Matches[1]) {
$Matches[1].trim(';: ')
} Else {
$ForEach.MoveNext()
$ForEach.Current
}
} ElseIf (Test-Path $Item) {
$Parms = If ($Filter ) { @{Filter = $Filter } } Else { @{} }
$Parms += If ($Exclude) { @{Exclude = $Exclude} } Else { @{} }
$Parms += If ($Include) { @{Include = $Include} } Else { @{} }
Get-ChildItem $Item -ea Ignore @Parms
}
Else { $Item }
})
$Parameters = @() + $Remaining + $Files + $ServerOptions
Write-Verbose "& $EmacsClient $Parameters"
If ($Test) {
& 'echoargs' @Parameters
} Else {
If ($Verbose) {
& 'echoargs' @Parameters
}
& $EmacsClient @Parameters
}
}
}
End {}
}
Function Get-Line {
[CmdletBinding()][Alias('lines','clean')]
param(
[Alias('strings','lines')][Parameter(ValueFromPipeline)]
[string[]]$InputObject = (Get-ClipBoard),
[Alias('SplitOn')] [string]$Pattern = '[\r\n]+',
[Alias('Ignore')] [string[]]$Exclude = @(''),
[Alias('OnlyIf')] [string[]]$Include = @(''),
[Alias('Blanks','AllowBlanks')] [switch]$AllowBlankLines = $False
)
Begin {
If ($Exclude) { $Exclude = '(' + ($Exclude -join ')|(') + ')' }
If ($Include) { $Include = '(' + ($Include -join ')|(') + ')' }
}
Process {
($InputObject -split $Pattern).trim().where{
($_ -or $AllowBlankLines) -and
(!$Exclude -or ($_ -notmatch $Exclude)) -and
(!$Include -or ($_ -match $Include))
}
}
End {}
}
Function Set-ItemTime {
[CmdletBinding(DefaultParameterSetName='Path', SupportsShouldProcess, SupportsTransactions)]
param(
[Parameter(ParameterSetName='Path',Position=0,
ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string[]]$Path=@(Get-ChildItem | Where-Object PSIsContainer -eq $False),
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath')][string[]]$LiteralPath,
[Alias('WriteTime','Time','DateTime')]
[Parameter(Position=1)][DateTime]$Date=(Get-Date),
[string[]]$Property = @('LastWriteTime'),
[switch]$PassThru,
[string]$Filter = '',
[string[]]$Include = '',
[string[]]$Exclude = ''
#[switch]${Force},
#[Parameter(ValueFromPipelineByPropertyName=$true)]
#[pscredential]
#[System.Management.Automation.CredentialAttribute()]
#${Credential})
)
Begin {
$DateString = Get-Date $Date -f 'yyyy-MM-dd HH:mm:ss'
Set-StrictMode -Version Latest
Write-Verbose "Property set: $($PSCmdlet.ParameterSetName)"
}
Process {
If ($PSBoundParameters.ContainsKey('LiteralPath')) {
$Path = @($PSBoundParameters.LiteralPath)
}
ForEach ($Item in $Path) {
$ShouldProcess = $True
If (!(Test-Path $Item -ea Ignore)) {
$NewMessage = "Create $Item to set $($Property -join ', ') to $DateString"
If ($ShouldProcess = $PSCmdlet.ShouldProcess($Item, $NewMessage)) {
Write-Verbose "Creating item: $Item - ShouldNew: [$ShouldProcess]"
New-Item $Item
$ItemPath = Resolve-Path $Item
Write-Verbose "Created new item: $ItemPath"
} else {
$ItemPath = $Item
Write-Warning "ShouldNew: [$ShouldProcess]"
Write-Verbose "Skipped Creation of new item: $ItemPath"
$ShouldProcess = $False
}
} else {
$ItemPath = Resolve-Path $Item
}
$SetMessage = "Set $($Property -join ', ') to $DateString"
If ($ShouldProcess -and ($ShouldProcess2 = $PSCmdlet.ShouldProcess($Item, $SetMessage))) {
Write-Verbose "Setting itemproperty: $ItemPath"
ForEach ($Prop in $Property) {
Set-ItemProperty $ItemPath -Name $Prop -Value $Date
}
If ($PassThru) { Get-Item $ItemPath }
} else {
Write-Verbose "Skipped Setting itemproperty: $ItemPath"
}
}
}
End { }
}
write-warning "$(get-date -f 'HH:mm:ss') $(LINE)"
$LogFilePath = 'Microsoft.PowerShell_profile-Log.txt'
$UtilityModule = 'PSUtility' # (Join-Path $ProfileDirectory Utility.psm1)
$LoadUtilityFile = $True
If ($True -and (Get-Module $UtilityModule -list -ea ignore)) {
try {
Write-Warning "Import Utility Module: $UtilityModule"
Import-Module $UtilityModule -force
Write-Warning "$(FLINE) Imported: $UtilityModule COMPLETE"
$LoadUtilityFile = $False
} catch {
Write-Warning "No FLINE: Caught utility module error: $UtilityModule"
}
}
If ($LoadUtilityFile) {
try {
$TryPath = $PSProfileDirectory,$ProfileDirectory,'C:\Bat','.'
Write-Warning "$(get-date -f 'HH:mm:ss') $(LINE) Try Utility path: $($TryPath -join '; ')"
If ($Util=(Join-Path $TryPath 'utility.ps1' -ea ignore | Select -First 1)) {
Write-Warning "Utility: $Util"
. $Util
Get-Command Write-Log -syntax
Write-Log "$(LINE) Using Write-Log from Utility.ps1"
}
} catch { # just ignore and take care of below
Write-Log "$(LINE) Failed loading Utility.ps1 $Util"
} finally {}
}
write-warning "$(get-date -f 'HH:mm:ss') $(LINE) ##338"
if ((Get-Command 'Write-Log' -type Function,CmdLet -ea ignore)) {
Remove-Item alias:write-log -force -ea ignore
} else {
New-Alias Write-Log Write-Verbose -ea ignore
Write-Warning "$(LINE) Utility.ps1 not found. Defined alias for Write-Log"
}
Write-Information "Profile loaded: $($MyInvocation.MyCommand.Path) ##464"
$PSVersionNumber = "$($psversiontable.psversion.major).$($psversiontable.psversion.minor)" -as [double]
Write-Information "$(LINE) PowerShell version PSVersionNumber: [$PSVersionNumber]"
$ForceModuleInstall = [boolean]$ForceModuleInstall
$AllowClobber = [boolean]$AllowClobber
$Confirm = [boolean]$Confirm
Write-Warning "$(get-date -f 'HH:mm:ss') $(LINE) Before Set-ProgramAlias"
Function Set-ProgramAlias {
param(
[Alias('Alias')] $Name,
[Alias('Program')]$Command,
[string[]]$Path,
[string[]]$Preferred,
[switch]$FirstPath,
[switch]$IgnoreAlias
)
$Old = Get-Alias $Name -ea Ignore
if ($IgnoreAlias) { remove-item Alias:$Name -force -ea Ignore }
$SearchPath = if ($FirstPath) {
$cmdnames = @(If ($cmd = @(get-command $Name -all -ea Ignore)) {
$cmd.definition
})
$WhereFound = If (where.exe $Command /q) {@()} else {@(where.exe $Command)}
$Path + $WhereFound + $cmdnames
} else {
@(get-command $Name -all -ea Ignore).definition +
(where.exe $Command 2>$Null) + $Path
}
Remove-Item Alias:$Name -force -ea Ignore
ForEach ($Location in $SearchPath) {
if ($Location -and (Test-Path $Location -pathType Leaf -ea Ignore)) {
new-alias $Name $Location -force -scope Global
break
} elseif ( $Location -and $Command -and
($Location = Join-Path $Location $Command -ea Ignore) -and
(Test-Path $Location -pathType Leaf)) {
new-alias $Name (Join-Path $Location $Command) -force -scope Global
break
}
}
if (Get-Command $Name -commandtype alias -ea Ignore) {
write-warning "$(LINE) $Name found: $Location [$((Get-Alias $Name -ea Ignore).definition)]"
} else {
write-warning "$(LINE) $Name NOT found on path or in: $($SearchPath -join '; ')"
}
}
Set-ProgramAlias np notepad++.exe @('C:\Util\notepad++.exe',
'C:\ProgramData\chocolatey\bin\notepad++.exe',
'S:\Programs\Notepad++\app\Notepad++\notepad++.exe'
'S:\Programs\Notepad++\notepad++portable.exe',
'T:\Programs\Notepad++\app\Notepad++\notepad++.exe',
'T:\Programs\Portable\Notepad++portable.exe',
'S:\Programs\Herb\util\notepad++.exe','T:\Programs\Herb\util\notepad++.exe',
'D:\wintools\Tools\hm\notepad++.exe') -FirstPath
Set-ProgramAlias nscp nscp.exe 'C:\Program Files\NSClient++\nscp.exe' -FirstPath
Set-ProgramAlias 7z 7z.exe @('C:Util\7-Zip\app\7-Zip64\7z.exe',
'C:\ProgramData\chocolatey\bin\7z.exe',
'S:\Programs\7-Zip\app\7-Zip64\7z.exe'
) -FirstPath
Write-Warning "$(get-date -f 'HH:mm:ss') $(LINE) After Set-ProgramAlias"
# gwmi Win32_logicaldisk -filter 'drivetype = 3 or drivetype = 4'
Join-Path 'C:\Program Files*\Microsoft VS Code*' Code*.exe -resolve | Select -first 1
# 'Thu, 08 Feb 2018 07:47:42 -0800 (PST)' -replace '[^\d]+$' -as [datetime] 13:47:42 -0800 (PST)'
# 'Thu, 08 Feb 2018 07:47:42 -0800 (PST)' -replace '[^\d]+$' -as [datetime] 13:47:42 -0800 (PST)'
#$raw = 'Thu, 08 Feb 2018 13:47:42 -0800 (PST)'
#$pattern = 'ddd, dd MMM yyyy Get-History:mm:ss zzz \(PST)'
#[DateTime]::ParseExact($raw, $pattern, $null)
if ($MyInvocation.HistoryID -eq 1) {
if (Get-Command Write-Information -type cmdlet,Function -ea ignore) {
$InformationPreference = 'Continue'
Remove-Item alias:Write-Information -ea ignore
$global:informationpreference = $warningpreference
} else {
write-warning '$(LINE) Use write-warning for information if Write-Information not available'
new-alias Write-Information write-warning -force -ea Ignore
}
}
if ($Quiet -and $global:informationpreference) {
$informationpreferenceSave = $global:informationpreference
$global:informationpreference = 'SilentlyContinue'
$script:informationpreference = 'SilentlyContinue'
Write-Information "SHOULD NOT WRITE"
}
If ([Environment]::OSVersion.Version -gt [version]'6.1') {
$Script:ImmersiveShell = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\ImmersiveShell'
Set-ItemProperty -path $ImmersiveShell -Name DisableCharmsHint -type DWORD -value 1 -force -ea Ignore
Set-ItemProperty -path $ImmersiveShell -Name DisableTLCorner -type DWORD -value 1 -force -ea Ignore
}
# If (Get-ItemProperty 'HKCU:\CONTROL PANEL\DESKTOP' -name WindowArrangementActive -ea Ignore |
# Select-Object WindowArrangementActive | Format-List | findstr "WindowArrangementActive") {
# Set-ItemProperty 'HKCU:\CONTROL PANEL\DESKTOP' -name WindowArrangementActive -value 0 -type dword -force
# }
Function Set-PropertyForce {
[CmdletBinding()]Param(
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string[]]$Path = '',
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string[]]$Name = $Null,
$Value = $Null,
[switch]$Force = $False
)
Begin {
$Force = $PSBoundParameters.ContainsKey('Force') -and $Force
}
Process {
If (!($Prop = (Get-ItemProperty -Path $Path -Name $Name -ea Ignore |
Select $Name))) {
If (!(Test-Path $Path -ea ignore) -and $Force) {
Write-Warning "Creating path: $Path"
MkDir $Path -Force -ea Ignore
}
Write-Warning "Set property: $Name"
Set-ItemProperty -Path $Path -Name $Name -value 1 -Force:$Force -ea Ignore
}
}
}
$Script:RegistryConfiguration = @(
,@('HKCU:\Test', 'TestingScript', 99, $True)
## @('HKCU:\CONTROL PANEL\DESKTOP', 'WindowArrangementActive', 0, $True)
## ,@('HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced', '1', 0, $True)
# ,@('', '', 0, $True)
# ,@('', '', 0, $True)
)
ForEach ($Entry in $Script:RegistryConfiguration) {
$Path, $Name, $Value, $Force = $Entry
Write-Warning "Set Property: [$Path] [$Name] [$Value] [$Force]"
# Set-PropertyForce -Path $Path -Name $Name -Value $Value -Force:$Force
}
# If (!(($Current = Get-ItemProperty $Path -name $Name -ea Ignore) -and
# ($Current.$Value -eq $Value))) {
# Select-Object WindowArrangementActive | Format-List | findstr "WindowArrangementActive") {
# # If (!(Test-Path $Path))
# Set-ItemProperty 'HKCU:\CONTROL PANEL\DESKTOP' -name WindowArrangementActive -value 0 -type dword -force
# }
# }
# https://onedrive.live.com?invref=b8eb411511e1610e&invscr=90 Free one drive space
Function Get-CurrentIPAddress {(ipconfig) -split "`n" | Where-Object {
$_ -match 'IPv4' } | ForEach-Object { $_ -replace '^.*\s+' }
}
Function Get-RegKey {
[Alias('grk','get-reg','get-key','grk','hkey')]
param(
[string[]]$Key,
[switch]$Double = $Null,
[switch]$Single = $Null,
[Alias('DosOnly','RegOnly')][switch]$CmdOnly = $Null,
[switch]$PSOnly = $Null,
[Alias('QO')] [switch]$QuoteOnly = $Null,
[switch]$NoQuote = $Null,
[switch]$Quote = $Null
)
Begin {
$Keys = New-Object System.Collections.ArrayList
If ($QuoteOnly) { $Quote = $True }
If ($Double -or $Single) { $Quote = $True }
}
Process {
If (!$Key) {
$Key = @(((Get-ClipBoard) -split "`n").trim('\s\\''"').Where{$_ -and $_ -match '^HK'})
}
ForEach ($K in $key) {
$K2 = $K -replace 'HK\w*_(.)\w*_(.)\w*:?','HK$1$2:'
If (!$CmdOnly) { [Void]$Keys.Add($K2) }
$K1 = $K2 -replace ':'
If (!$PSOnly) { [Void]$Keys.Add($K1) }
If ($Keys) {
ForEach ($K3 in $Keys) {
If ($Quote) {
If (!$Double) { "'$K3'" }
If (!$Single) { "`"$K3`"" }
} ElseIf (!$NoQuote -and ($K3 -match '\s')) {
"'$K3'"
}
If (!$QuoteOnly) { $K3 }
}
}
}
}
End {}
}
Function Get-WhoAmI { "[$PID]",(whoami),(hostname) + (Get-CurrentIPAddress) -join ' ' }
Function Get-WhoAmI {
[CmdletBinding()]param(
[ValidatePattern('^(P|G|U|F|L|G|P|A)')][string]$Show = '',
[switch]$UPN = $False,
[switch]$FQDN = $False,
[switch]$User = $False,
[switch]$LoginID = $False,
[switch]$Groups = $False,
[switch]$Privileges = $False,
[switch]$All = $False
)
$Switches = 'UPN', 'FQDN', 'USER', 'LOGONID', 'GROUPS', 'PRIV', 'ALL'
$SwitchKey = If ($Show -match '^(P|G|UP|US|F|L|G|P|A)') {
$Matches[1]
} Else { 'xxx' }
Write-Verbose "Show: $Show Switchkey: $Switchkey"
# $Args = "$Switch"
$Switch = If ($Switches) { $Switches -match "^$SwitchKey" | Select -first 1 }
If ($Switch -in 'GROUPS', 'PRIV', 'ALL') {
Write-Verbose "WhoAmI /$Switch /fo csv | convertfrom-csv"
WhoAmI "/$Switch" /fo csv | convertfrom-csv
} ElseIf ($Switch) {
Write-Verbose "WhoAmI /$Switch | % { [PSCustomObject]@{ $Switch = `$_ } }"
WhoAmI "/$Switch" | ForEach-Object { [PSCustomObject]@{ $Switch = $_ } }
} Else {
WhoAmI
}
}
Function Get-DotNetVersion {
[CmdletBinding()]param(
[version]$MinimumVersion='0.0.0.0',
[version]$MaximumVersion='999.9.9.9'
)
# $MinimumVersion = $MinimumVersion
Write-Information '[Information] .NET dotnet versions installed'
$DotNetKey = @('HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP',
'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4')
@(foreach ($key in $DotNetKey) { Get-ChildItem $key }) |
Get-ItemProperty -ea ignore |
Select-Object @{N='Name';E={$_.pspath -replace '.*\\([^\\]+)$','$1'}},version,
InstallPath,@{N='Path';E={($_.pspath -replace '^[^:]*::') -replace '^HKEY[^\\]*','HKLM:'}} |
Where-Object { $MaximumVersion -ge $_.Version -and $MinimumVersion -le $_.Version }
}
If ($ShowDotNetVersions) { Get-DotNetVersion }
Write-Warning "$(get-date -f 'HH:mm:ss') $(LINE) After ShowDotNetVersions"
$DefaultConsoleTitle = 'Windows PowerShell'
Function Update-PackageManager {
If (Test-Administrator) {
$DefaultConsoleTitle = 'Administrator: Windows PowerShell'
# https://github.com/PowerShell/PowerShellGet/archive/1.6.0.zip
try {
if ((Get-PSVersion) -lt 6.0) {
If (Get-Package 'Nuget' -ea ignore) {
write-warning "$(get-date -f 'HH:mm:ss') $(LINE)"
} else {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
}
}
$PSGallery = Get-PSRepository PSGallery -ea ignore
if ($PSGallery) {
#$PSGallery
if ($PSGallery.InstallationPolicy -ne 'Trusted') {
Set-PSRepository -name 'PSGallery' -InstallationPolicy 'Trusted' -ea ignore
$PSGallery = Get-PSRepository -name 'PSGallery' -ea ignore
}
If ($PSBoundParameters['Verbose'] -and $Verbose) { $PSGallery | Format-Table }
}
} catch {
Write-Information "$(LINE) Problem with PSRepository"
}
}
}
If ($UpdatePackageManager) { Update-PackageManager }
$PSVersionNumber = "$($psversiontable.psversion.major).$($psversiontable.psversion.minor)" -as [double]
$CurrentWindowTitle = $Host.ui.RawUI.WindowTitle
if ($CurrentWindowTitle -match 'Windows PowerShell([\(\)\s\d]*)$') {
$Host.ui.RawUI.WindowTitle += " $(Get-WhoAmI) OS:" +
(Get-WMIObject win32_operatingsystem).version + "PS: $PSVersionNumber"
}
write-warning "$(get-date -f 'HH:mm:ss') $(LINE) Before Show-Module "
# Get .Net Constructor parameters
# ([type]"Net.Sockets.TCPClient").GetConstructors() | ForEach-Object { $_.GetParameters() } | Select-Object Name,ParameterType
Function Get-Constructor {
param([Alias('Name')][string[]]$TypeName)
ForEach ($Name in $TypeName) {
([type]$Name).GetConstructors() | ForEach-Object {
write-host "$_"; $_.GetParameters()
} | Select-Object -Object Name, ParameterType
}
}
# [Net.Sockets.TCPClient]::New
# Check TCP connection (New-Object Net.Sockets.TcpClient).Connect("<remote machine>",<port>)
# Check UDP conection (New-Object Net.Sockets.UdpClient).Connect("<remote machine>",<port>)
Function Test-TCP {
[CmdletBinding()]Param($ComputerName='www.google.com',$Port=80)
try {
(New-Object Net.Sockets.TcpClient).Connect($ComputerName,$Port)
$True
} Catch { $False }
}