forked from Nick2bad4u/UserStyles
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
2896 lines (2472 loc) · 88 KB
/
Microsoft.PowerShell_profile.ps1
File metadata and controls
2896 lines (2472 loc) · 88 KB
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
#f45873b3-b655-43a6-b217-97c00aa0db58 PowerToys CommandNotFound module
Import-Module -Name Microsoft.WinGet.CommandNotFound
#f45873b3-b655-43a6-b217-97c00aa0db58
# Alias section
New-Alias boottime BootDate
New-Alias upsince BootDate
New-Alias starttime BootDate
New-Alias initdate BootDate
New-Alias poweron BootDate
New-Alias startup BootDate
New-Alias bootup BootDate
New-Alias systemstart BootDate
New-Alias poweruptime BootDate
New-Alias fixwindows Repair-All
New-Alias repairwindows Repair-All
New-Alias unfuckwindows Repair-All
New-Alias repairall Repair-All
New-Alias dismrestore Repair-All
New-Alias dismfix Repair-All
New-Alias wingetupdateall WingetUpdate
New-Alias wgu WingetUpdate
New-Alias beautifyps Edit-DTWBeautifyScript
New-Alias psbeautify Edit-DTWBeautifyScript
New-Alias powershellbeautify Edit-DTWBeautifyScript
New-Alias fixpowershellscript Edit-DTWBeautifyScript
New-Alias fixpowershellformatting Edit-DTWBeautifyScript
New-Alias fixpowershell Edit-DTWBeautifyScript
New-Alias PSBeauty Edit-DTWBeautifyScript
New-Alias beautifyscript Edit-DTWBeautifyScript
New-Alias formatpowershell Edit-DTWBeautifyScript
New-Alias formatps Edit-DTWBeautifyScript
New-Alias formatpsscript Edit-DTWBeautifyScript
New-Alias beautifypsscript Edit-DTWBeautifyScript
New-Alias psformat Edit-DTWBeautifyScript
New-Alias beautifyformat Edit-DTWBeautifyScript
New-Alias beautifycode Edit-DTWBeautifyScript
New-Alias psbeautifycode Edit-DTWBeautifyScript
New-Alias beautifyformatps Edit-DTWBeautifyScript
New-Alias prettynow pretty
New-Alias runpretty pretty
New-Alias runprettynow pretty
New-Alias prettyfiles pretty
New-Alias makepretty pretty
New-Alias beautifyfiles pretty
New-Alias prettifyfiles pretty
New-Alias makeitpretty pretty
New-Alias prettyrun pretty
New-Alias prettifyrun pretty
New-Alias beautifyrun pretty
New-Alias prettyrunfiles pretty
New-Alias notepadprofile editprofile
New-Alias editpsprofile editprofile
New-Alias editpowershellprofile editprofile
New-Alias psprofileedit editprofile
New-Alias profileedit editprofile
New-Alias profileeditor editprofile
New-Alias editprofileps editprofile
New-Alias editprofilepowershell editprofile
New-Alias profilepsedit editprofile
New-Alias profilepowershelledit editprofile
New-Alias openprofile editprofile
New-Alias editpsprofilefile editprofile
New-Alias editpowershellprofilefile editprofile
New-Alias editprofilefile editprofile
# Functions in profile:
# Remove-Images: Deletes all image files (JPG, PNG, GIF, BMP) in a specified directory.
# Clear-Temp: Clears the temporary files in $env:TEMP.
# Get-LastRun: Retrieves the last logged run of a script from a specified log file.
# Get-IPAddress: Fetches the public IP using an external API.
# Get-DiskUsage: Displays disk usage for a specified drive.
# Restart-Service: Restarts a specified Windows service.
# Show-FileSize: Shows the size of a specified file in MB.
# Convert-Size: Converts bytes to a readable format (KB, MB, GB).
# Find-ProcessByName: Lists processes that match a specified name.
# Start-Task: Starts a new task or application by command.
# Get-ProcessInfo: Lists all processes with CPU and memory information.
# Clear-EventLogs: Clears all Windows event logs.
# Get-ComputerInfo: Displays basic computer information like manufacturer, model, RAM, and OS.
# Find-LargestFiles: Finds the largest files in a specified path.
# Get-UserAccount: Retrieves a list of local user accounts.
# Export-ProcessList: Exports the list of processes to a CSV file.
# Check-ServiceStatus: Checks the status of a specified service.
# Start-ProcessAsAdmin: Runs a specified process with administrator privileges.
# Get-FileHash: Calculates the hash of a specified file.
# Schedule-Task: Creates a scheduled task with a specified time trigger.
# Get-InstalledSoftware: Lists installed software.
# Get-NetworkInfo: Displays information about network adapters.
# Show-DiskSpace: Shows disk space usage per drive.
# Kill-ProcessByName: Terminates a process by name.
# Convert-ToHtml: Creates an HTML report of files in a directory.
# Get-SystemUptime: Displays system uptime in days, hours, and minutes.
# Test-Port: Checks if a specified port is open on a host.
# Get-ProcessCPUUsage: Lists CPU usage for a specified process by name.
# Export-EventLogs: Exports specified Windows event logs to a file.
# Send-Email: Sends an email via an SMTP server.
# Repair-All: Performs a series of DISM and SFC scans to check and repair system health.
# BootDate: Retrieves the system's last boot time.
# WingetUpdate: Updates all packages using winget, including unknown ones, and displays a success message.
# pretty: Runs Prettier on all files in the current directory to format code and outputs a completion message.
# Clear-Clipboard: Clears the clipboard content.
# Get-RegistryValue: Retrieves a specified registry value and shows it if found.
# Show-DirectorySize: Calculates and displays the total size of a specified directory in MB.
# Get-Services: Lists all services on the system, showing their display names and statuses.
# Get-SystemInfo: Retrieves system information, including computer name, OS architecture, Windows version, and build.
# Get-EnvironmentVariables: Displays all environment variables with their names and values.
# Backup-Files: Copies files from a source directory to a specified destination directory for backup.
# Get-InstalledSoftware: Retrieves a list of installed software, displaying names and versions.
# Schedule-Task: Schedules a task to run a command at a specified time with system privileges.
# Get-FileHash: Computes and displays the hash of a specified file if it exists.
# editprofile: Opens the PowerShell profile in Notepad++ for editing.
# notepad++: Opens Notepad++.
function Remove-Images {
param(
[string]$Path = (Get-Location) # Default to current directory if no path is provided
)
Write-Host "Removing images from path: $Path" -ForegroundColor Yellow
# Ensure the path exists
if (-not (Test-Path $Path)) {
Write-Host "The specified path does not exist: $Path" -ForegroundColor Red
return
}
# Remove image files recursively from the specified path
Write-Host 'Searching for image files to remove...' -ForegroundColor Yellow
Get-ChildItem -Path $Path -Recurse -File -Include *.jpg, *.jpeg, *.png, *.gif, *.bmp | Remove-Item -Force
Write-Host 'Image files removed.' -ForegroundColor Green
}
function Clear-Temp {
param(
[switch]$Force
)
$tempPath = "$env:TEMP\*"
Write-Host "Clearing temporary files from: $env:TEMP" -ForegroundColor Yellow
# Prompt for confirmation if -Force is not specified
if (-not $Force) {
$confirmation = Read-Host "Are you sure you want to delete all files in $env:TEMP? (y/n)"
if ($confirmation -ne 'y') {
Write-Host 'Operation cancelled by user.' -ForegroundColor Cyan
return
}
}
try {
Remove-Item -Path $tempPath -Recurse -Force -ErrorAction Stop
Write-Host "Temporary files cleared from $env:TEMP." -ForegroundColor Green
}
catch {
Write-Host "An error occurred while clearing temporary files: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# Clear-Temp
# Clear-Temp -Force
function Get-LastRun {
param(
[Parameter(Mandatory = $true)]
[string]$ScriptName,
[string]$LogFilePath
)
# Prompt for log file location if not provided
if (-not $LogFilePath) {
$LogFilePath = Read-Host 'Enter log file location'
}
# Check if the log file exists
if (-not (Test-Path $LogFilePath)) {
Write-Host "Log file not found: $LogFilePath" -ForegroundColor Red
return
}
Write-Host "Retrieving last run information for script: $ScriptName from log file: $LogFilePath" -ForegroundColor Yellow
try {
# Retrieve the last run information
$lastRunInfo = Get-Content $LogFilePath | Select-String $ScriptName | Select-Object -Last 1
if ($lastRunInfo) {
Write-Host "Last run information: $lastRunInfo" -ForegroundColor Green
}
else {
Write-Host "No run information found for script: $ScriptName" -ForegroundColor Red
}
}
catch {
Write-Host "An error occurred while retrieving the last run information: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# Get-LastRun -ScriptName 'MyScript.ps1' -LogFilePath 'C:\Path\To\Your\LogFile.log'
<#
.SYNOPSIS
Retrieves the public IP address using an external API.
.DESCRIPTION
The Get-IPAddress function fetches the public IP address of the system by making a request to an external API.
.EXAMPLE
Get-IPAddress
Displays the public IP address of the system.
.NOTES
If the API request fails, an error message is displayed.
#>
function Get-IPAddress {
Write-Host 'Retrieving public IP address...' -ForegroundColor Yellow
try {
$ip = $null
$ip = Invoke-RestMethod -Uri 'https://api.ipify.org'
Write-Host "Your public IP address is: $ip" -ForegroundColor Cyan
}
catch {
Write-Host 'Network error occurred while retrieving IP address.' -ForegroundColor Red
}
}
function Get-DiskUsage {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[ValidatePattern('^[A-Za-z]:$')]
[string]$Drive = 'C:'
)
try {
$driveInfo = Get-PSDrive -Name $Drive -ErrorAction Stop
}
catch {
Write-Error "Drive $Drive does not exist or usage information could not be retrieved."
return
}
if (-not $driveInfo) {
Write-Error "No usage information available for drive $Drive."
return
}
$usedGB = [math]::Round($driveInfo.Used / 1GB, 2)
$sizeGB = [math]::Round($driveInfo.Size / 1GB, 2)
Write-Host "$Drive Drive Usage: $usedGB GB used out of $sizeGB GB." -ForegroundColor Green
}
function Restart-Service {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ServiceName
)
Write-Verbose "Attempting to restart service: $ServiceName"
try {
# Retrieve the service to verify it exists.
$service = Get-Service -Name $ServiceName -ErrorAction Stop
# Inform if the service is not running before attempting to start or restart.
if ($service.Status -ne 'Running') {
Write-Host "Service '$ServiceName' is not running. Attempting to start it..." -ForegroundColor Yellow
}
else {
Write-Host "Restarting service: $ServiceName" -ForegroundColor Yellow
}
# Use the fully qualified cmdlet name to avoid recursive function call.
Microsoft.PowerShell.Management\Restart-Service -Name $ServiceName -Force -ErrorAction Stop
Write-Host "Service '$ServiceName' restarted successfully." -ForegroundColor Green
}
catch {
Write-Host "Failed to restart service '$ServiceName'. Error: $_" -ForegroundColor Red
}
}
function Show-FileSize {
param(
[string]$FilePath
)
Write-Host "Checking file size for: $FilePath" -ForegroundColor Yellow
if (Test-Path $FilePath) {
$size = (Get-Item $FilePath).Length
$sizeMB = [math]::Round($size / 1MB, 2)
Write-Host ('Size of {0}: {1} MB' -f $FilePath, $sizeMB) -ForegroundColor Cyan
}
else {
Write-Host ('File not found: {0}' -f $FilePath) -ForegroundColor Red
}
}
function Convert-Size {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[long]$Bytes
)
# Determine the proper unit and format accordingly.
if ($Bytes -lt 1KB) {
return "$Bytes Bytes"
}
elseif ($Bytes -lt 1MB) {
return '{0:N2} KB' -f ($Bytes / 1KB)
}
elseif ($Bytes -lt 1GB) {
return '{0:N2} MB' -f ($Bytes / 1MB)
}
else {
return '{0:N2} GB' -f ($Bytes / 1GB)
}
}
function Find-ProcessByName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$ProcessName
)
Write-Host "Finding processes by name: $ProcessName" -ForegroundColor Yellow
try {
$processes = Get-Process -Name $ProcessName -ErrorAction Stop
if ($processes) {
$processes | Format-Table -AutoSize `
Id,
Name,
@{Label = 'Path'; Expression = {
try { $_.Path } catch { 'N/A' }
}
}
}
}
catch {
Write-Host "No process found with name: $ProcessName" -ForegroundColor Red
}
}
function Start-Task {
param(
[string]$Command
)
Write-Host "Starting task: $Command" -ForegroundColor Yellow
Start-Process -FilePath $Command
Write-Host "Started task: $Command" -ForegroundColor Green
}
function Get-ProcessInfo {
[CmdletBinding()]
param(
# Optional parameter to filter processes by name(s)
[string[]]$ProcessName
)
Write-Host 'Retrieving process information...' -ForegroundColor Yellow
# Retrieve processes, optionally filtered by provided process names
$processes = if ($ProcessName) {
Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
}
else {
Get-Process
}
if ($null -eq $processes) {
Write-Host 'No matching processes found.' -ForegroundColor Red
return
}
# Select and format process information, handling potential null CPU value
$processes |
Select-Object Name,
Id,
@{ Name = 'CPU (s)'; Expression = {
if ($_.CPU) { [math]::Round([double]$_.CPU, 2) }
else { 'N/A' }
}
},
@{ Name = 'Memory (MB)'; Expression = { [math]::Round($_.WorkingSet64 / 1MB, 2) } } |
Format-Table -AutoSize
}
function Clear-EventLogs {
try {
Write-Verbose 'Starting to clear all event logs...'
Get-EventLog -List | ForEach-Object {
Write-Verbose "Clearing event log: $($_.Log)"
Clear-EventLog -LogName $_.Log -ErrorAction Stop
}
Write-Output 'All event logs have been cleared.'
}
catch {
Write-Error "Failed to clear event logs. Error: $_"
}
}
function Get-ComputerInfo {
try {
Write-Verbose 'Retrieving computer information...'
$cs = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop
[pscustomobject]@{
Manufacturer = $cs.Manufacturer
Model = $cs.Model
'RAM (GB)' = [math]::Round($cs.TotalPhysicalMemory / 1GB, 2)
OS = $os.Caption
}
}
catch {
Write-Error "Error retrieving computer info: $_"
}
}
function Find-LargestFiles {
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[int]$Count = 10
)
if (-not (Test-Path $Path)) {
Write-Error "The specified path does not exist: $Path"
return
}
try {
Write-Verbose "Finding top $Count largest files in path: $Path"
Get-ChildItem -Path $Path -Recurse -File -ErrorAction Stop |
Sort-Object -Property Length -Descending |
Select-Object -First $Count |
Format-Table Name, @{ Name = 'Size (MB)'; Expression = { [math]::Round($_.Length / 1MB, 2) } } -AutoSize
}
catch {
Write-Error "Error finding largest files: $_"
}
}
function Get-UserAccount {
try {
Write-Verbose 'Retrieving user account information...'
Get-LocalUser -ErrorAction Stop |
Select-Object Name, Enabled, LastLogon |
Format-Table -AutoSize
}
catch {
Write-Error "Failed to retrieve local user accounts: $_"
}
}
function Export-ProcessList {
param(
[string]$FilePath = 'C:\Path\To\Your\Processes.csv'
)
Write-Host "Exporting process list to: $FilePath" -ForegroundColor Yellow
Get-Process | Export-Csv -Path $FilePath -NoTypeInformation
Write-Host "Process list exported to $FilePath" -ForegroundColor Green
}
function Get-ServiceStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ServiceName
)
Write-Verbose "Retrieving status for service: $ServiceName"
try {
$service = Get-Service -Name $ServiceName -ErrorAction Stop
Write-Host "Service: $($service.Name) is currently $($service.Status)." -ForegroundColor Cyan
# Return a custom object with the service's details
[pscustomobject]@{
Name = $service.Name
Status = $service.Status
}
}
catch {
Write-Host "Error: Service '$ServiceName' not found or cannot be queried." -ForegroundColor Red
}
}
function Start-ProcessAsAdmin {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$FilePath
)
if (-not (Test-Path $FilePath)) {
Write-Host "Error: File path '$FilePath' does not exist." -ForegroundColor Red
return
}
Write-Host "Starting '$FilePath' as administrator..." -ForegroundColor Yellow
try {
Start-Process -FilePath $FilePath -Verb RunAs -ErrorAction Stop
Write-Host "Successfully started '$FilePath' as administrator." -ForegroundColor Green
}
catch {
Write-Host "Failed to start '$FilePath' as administrator. Error: $_" -ForegroundColor Red
}
}
function Get-FileHash {
param(
[string]$FilePath
)
Write-Host "Calculating file hash for: $FilePath" -ForegroundColor Yellow
if (Test-Path $FilePath) {
Get-FileHash -Path $FilePath | Format-Table Algorithm, Hash
}
else {
Write-Host "File not found: $FilePath" -ForegroundColor Red
}
}
function Register-Task {
param(
[string]$TaskName,
[string]$Command,
[string]$TriggerTime
)
Write-Host "Scheduling task '$TaskName' to run '$Command' at $TriggerTime" -ForegroundColor Yellow
$action = New-ScheduledTaskAction -Execute $Command
$trigger = New-ScheduledTaskTrigger -At $TriggerTime
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $TaskName -User 'SYSTEM' -RunLevel Highest
Write-Host "Scheduled task '$TaskName' created to run '$Command' at $TriggerTime." -ForegroundColor Green
}
function Get-InstalledSoftware {
Write-Host 'Retrieving installed software list...' -ForegroundColor Yellow
Get-WmiObject -Class Win32_Product | Select-Object Name, Version, InstallDate | Format-Table -AutoSize
}
function Get-NetworkInfo {
Get-NetAdapter | Select-Object Name, Status, MacAddress, LinkSpeed | Format-Table -AutoSize
}
function Show-DiskSpace {
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{ Name = 'Used (GB)'; Expression = { [math]::Round($_.Used / 1GB, 2) } }, @{ Name = 'Free (GB)'; Expression = { [math]::Round($_.Free / 1GB, 2) } }, @{ Name = 'Total (GB)'; Expression = { [math]::Round($_.Used / 1GB + $_.Free / 1GB, 2) } } | Format-Table -AutoSize
}
<#
.SYNOPSIS
Stops a process by its name.
.DESCRIPTION
The Stop-ProcessByName function stops a process by its name. It takes a process name as input and attempts to stop the process. If the process is not found, it writes a verbose message indicating that no process was found with the specified name.
.PARAMETER ProcessName
The name of the process to stop. This parameter is mandatory and accepts input from the pipeline.
.EXAMPLE
Stop-ProcessByName -ProcessName "notepad"
Stops the process named "notepad".
.EXAMPLE
"notepad" | Stop-ProcessByName
Stops the process named "notepad" using pipeline input.
.NOTES
If the process cannot be stopped, an error message is displayed in red.
#>
function Stop-ProcessByName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$ProcessName
)
process {
# Ensure the ProcessName is not empty or null
if (![string]::IsNullOrWhiteSpace($ProcessName)) {
try {
$process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
if ($process) {
$process | Stop-Process -Force
Write-Verbose "Stopped process: $ProcessName" -Verbose
}
else {
Write-Verbose "No process found with name: $ProcessName" -Verbose
}
}
catch {
Write-Host "Error occurred while stopping the process: $ProcessName" -ForegroundColor Red
}
}
else {
Write-Host 'Invalid process name provided.' -ForegroundColor Red
}
}
}
function Convert-ToHtml {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[string]$OutputFile = 'FileList.html'
)
# Check if the specified path exists
if (-not (Test-Path $Path)) {
Write-Verbose "Path not found: $Path" -Verbose
return
}
try {
# Retrieve only files from the specified path
$files = Get-ChildItem -Path $Path -File -ErrorAction Stop
# Check if there are any files in the specified path
if (-not $files) {
Write-Verbose "No files found in the path: $Path" -Verbose
return
}
# Convert the file list to HTML format with a heading
$html = $files | ConvertTo-Html -Property Name, Length, LastWriteTime `
-Title 'File List' -PreContent "<h1>File List for $Path</h1>"
# Save the HTML content to the specified output file using UTF8 encoding
$html | Out-File -FilePath $OutputFile -Encoding UTF8
Write-Verbose "HTML report created: $OutputFile" -Verbose
}
catch {
Write-Verbose 'Error: Unable to retrieve files from the specified path. Please check the path and permissions.' -Verbose
}
}
<#
.SYNOPSIS
Retrieves and displays the system uptime.
.DESCRIPTION
The Get-SystemUptime function calculates and displays the system uptime by retrieving the last boot time and calculating the duration from the boot time to the current time.
.EXAMPLE
Get-SystemUptime
Displays the system uptime in days, hours, and minutes.
.NOTES
If an error occurs while retrieving the system uptime, an error message is displayed.
#>
function Get-SystemUptime {
[CmdletBinding()]
param()
try {
# Retrieve the last boot time
$bootTime = (Get-CimInstance -Class Win32_OperatingSystem).LastBootUpTime
# Calculate the uptime duration
$uptimeDuration = New-TimeSpan -Start $bootTime -End (Get-Date)
# Display the uptime duration
Write-Verbose "System uptime: $($uptimeDuration.Days) days, $($uptimeDuration.Hours) hours, $($uptimeDuration.Minutes) minutes."
# Output the uptime duration
return $uptimeDuration
}
catch {
Write-Verbose 'Error: Unable to retrieve system uptime.'
}
}
# Example usage:
# Get-SystemUptime -Verbose
function Test-PortOld {
param(
[string]$TargetHost,
[int]$Port
)
$tcpConnection = Test-NetConnection -ComputerName $Host -Port $Port
if ($tcpConnection.TcpTestSucceeded) {
Write-Host "Port $Port on $Host is open." -ForegroundColor Green
}
else {
Write-Host "Port $Port on $Host is closed." -ForegroundColor Red
}
}
function Get-ProcessCPUUsage {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ProcessName
)
try {
# Get all processes and perform a fuzzy search for the process name
$processes = Get-Process -Name $ProcessName -ErrorAction Stop | Where-Object { $_.Name -like "*$ProcessName*" }
if ($processes) {
foreach ($process in $processes) {
$cpuUsage = $process | Measure-Object -Property CPU -Sum
Write-Verbose "CPU Usage for $($process.Name): $($cpuUsage.Sum) seconds" -Verbose
}
}
else {
Write-Verbose "Process not found: $ProcessName" -Verbose
}
}
catch {
Write-Verbose "Error occurred while retrieving CPU usage for process: $ProcessName" -Verbose
}
}
function Export-EventLogs {
param(
[Parameter(Mandatory = $true)]
[string]$LogName,
[Parameter(Mandatory = $true)]
[string]$FilePath
)
try {
# Validate the log name
if (-not (Get-WinEvent -ListLog $LogName -ErrorAction SilentlyContinue)) {
Write-Host "Invalid log name: $LogName" -ForegroundColor Red
return
}
# Export the event logs
Write-Host "Exporting $LogName logs to $FilePath..." -ForegroundColor Yellow
wevtutil.exe export-log $LogName $FilePath /format:evtx
if ($?) {
Write-Host "Exported $LogName logs to $FilePath successfully." -ForegroundColor Green
}
else {
Write-Host "Failed to export $LogName logs to $FilePath." -ForegroundColor Red
}
}
catch {
Write-Host "An error occurred while exporting the logs: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# Export-EventLogs -LogName 'Application' -FilePath 'C:\Path\To\Your\EventLogs.evtx'
# Example usage:
# Export-EventLogs -LogName 'Application' -FilePath 'C:\Path\To\Your\EventLogs.evtx'
function Send-Email {
param(
[Parameter(Mandatory = $true)]
[string]$To,
[Parameter(Mandatory = $true)]
[string]$Subject,
[Parameter(Mandatory = $true)]
[string]$Body,
[Parameter(Mandatory = $true)]
[string]$SmtpServer,
[Parameter(Mandatory = $true)]
[string]$From,
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]$Credential
)
try {
$message = New-Object System.Net.Mail.MailMessage
$message.From = $From
$message.To.Add($To)
$message.Subject = $Subject
$message.Body = $Body
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer)
$smtp.Credentials = $Credential.GetNetworkCredential()
$smtp.EnableSsl = $true
$smtp.Send($message)
Write-Host "Email sent to $To" -ForegroundColor Green
}
catch {
Write-Host "An error occurred while sending the email: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# $SecurePassword = Read-Host -AsSecureString 'Enter your password'
# $Credential = New-Object System.Management.Automation.PSCredential ('yourUsername', $SecurePassword)
# Send-Email -To '[email protected]' -Subject 'Test Email' -Body 'This is a test email.' -SmtpServer 'smtp.yourserver.com' -From '[email protected]' -Credential $Credential
function Repair-All {
try {
Write-Host 'Starting the system repair process...' -ForegroundColor Yellow
# Run the DISM commands to check, scan, and restore the health of the image
Write-Host 'Checking health of the image...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /CheckHealth
Write-Host 'Health check completed.' -ForegroundColor Green
Write-Host 'Scanning the health of the image...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /ScanHealth
Write-Host 'Health scan completed.' -ForegroundColor Green
Write-Host 'Restoring the health of the image...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /RestoreHealth
Write-Host 'Health restoration completed.' -ForegroundColor Green
Write-Host 'Running System File Checker (SFC)...' -ForegroundColor Yellow
sfc /scannow
Write-Host 'SFC scan completed.' -ForegroundColor Green
# Repeat the process to ensure thoroughness
Write-Host 'Repeating the health check...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /CheckHealth
Write-Host 'Health check repeated.' -ForegroundColor Green
Write-Host 'Scanning the health of the image again...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /ScanHealth
Write-Host 'Health scan repeated.' -ForegroundColor Green
Write-Host 'Restoring the health of the image again...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /RestoreHealth
Write-Host 'Health restoration repeated.' -ForegroundColor Green
Write-Host 'Running System File Checker (SFC) again...' -ForegroundColor Yellow
sfc /scannow
Write-Host 'SFC scan repeated.' -ForegroundColor Green
# Final health checks
Write-Host 'Final health check...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /CheckHealth
Write-Host 'Final health check completed.' -ForegroundColor Green
Write-Host 'Final scan for health...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /ScanHealth
Write-Host 'Final health scan completed.' -ForegroundColor Green
Write-Host 'Final restoration of health...' -ForegroundColor Yellow
DISM /Online /Cleanup-Image /RestoreHealth
Write-Host 'Final health restoration completed.' -ForegroundColor Green
Write-Host 'Final System File Checker (SFC) run...' -ForegroundColor Yellow
sfc /scannow
Write-Host 'Final SFC scan completed.' -ForegroundColor Green
Write-Host 'System repair process completed successfully.' -ForegroundColor Green
}
catch {
Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# Repair-All
# Function to display the system boot time
function BootDate {
try {
Write-Host 'Retrieving system boot time...' -ForegroundColor Yellow
# Check if the command 'systeminfo' is available
if (Get-Command systeminfo -ErrorAction SilentlyContinue) {
# Use systeminfo to get boot time
$bootTime = systeminfo | Select-String 'System Boot Time'
}
else {
# Use CIM cmdlets as a fallback (works on Windows systems)
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$bootTime = $os.LastBootUpTime
}
if ($bootTime) {
Write-Host "System boot time: $bootTime" -ForegroundColor Cyan
}
else {
Write-Host 'System boot time could not be retrieved.' -ForegroundColor Red
}
Write-Host 'System boot time retrieved.' -ForegroundColor Green
}
catch {
Write-Host "An error occurred while retrieving the system boot time: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# BootDate
# Function to update packages using winget, including unknown packages
function WingetUpdate {
try {
Write-Host 'Updating packages using winget, including unknown packages...' -ForegroundColor Yellow
# Check if winget is installed
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Write-Host 'winget is not installed. Please install winget first.' -ForegroundColor Red
return
}
# Run winget update
winget update --include-unknown
Write-Host 'Packages updated successfully.' -ForegroundColor Green
}
catch {
Write-Host "An error occurred while updating packages: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# WingetUpdate
# Function to run prettier on all files in the current directory
function pretty {
try {
Write-Host 'Running Prettier on all files in the current directory.' -ForegroundColor Yellow
# Check if Prettier is installed
if (-not (Get-Command prettier -ErrorAction SilentlyContinue)) {
Write-Host 'Prettier is not installed. Please install Prettier first.' -ForegroundColor Red
return
}
# Run Prettier
prettier --write .
Write-Host 'Finished running Prettier on all files.' -ForegroundColor Green
}
catch {
Write-Host "An error occurred while running Prettier: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# pretty
# Function to clear the clipboard
function Clear-Clipboard {
try {
Write-Host 'Clearing clipboard...' -ForegroundColor Yellow
# Clear the clipboard
Set-Clipboard -Value $null
Write-Host 'Clipboard cleared.' -ForegroundColor Green
}
catch {
Write-Host "An error occurred while clearing the clipboard: $($_.Exception.Message)" -ForegroundColor Red
}
}
# Example usage:
# Clear-Clipboard
# Function to retrieve a registry value
function Get-RegistryValue {
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Name
)
try {
Write-Host "Retrieving registry value from path: $Path, name: $Name" -ForegroundColor Yellow
# Retrieve the registry value
$value = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue
if ($value) {
Write-Host "Registry value: $($value.$Name)" -ForegroundColor Cyan
}
else {
Write-Host 'Registry value not found.' -ForegroundColor Red