-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
570 lines (487 loc) · 19.8 KB
/
Copy pathMicrosoft.PowerShell_profile.ps1
File metadata and controls
570 lines (487 loc) · 19.8 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
# Suppress progress bars
$ProgressPreference = 'SilentlyContinue'
# -----------------------------
# Module Helper
# -----------------------------
function Ensure-Module($name) {
if (-not (Get-Module -ListAvailable -Name $name)) {
try {
Install-Module -Name $name -Scope CurrentUser -Force -ErrorAction Stop
} catch {
Write-Warning ("Failed to install " + $name + ": " + $_)
}
}
Import-Module -Name $name -ErrorAction SilentlyContinue
}
Ensure-Module "Terminal-Icons"
Ensure-Module "Z"
# -----------------------------
# Font Installer
# -----------------------------
function Install-Font {
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Warning "Font installation requires admin privileges. Run as admin and try again."
return
}
$fontNames = @('FiraCode Nerd Font')
$fontUrl = 'https://github.com/ryanoasis/nerd-fonts/releases/download/v3.3.0/FiraCode.zip'
$installedFonts = (New-Object System.Drawing.Text.InstalledFontCollection).Families.Name
$fontsMissing = $fontNames | Where-Object { $_ -notin $installedFonts }
if ($fontsMissing.Count -gt 0) {
try {
$zipPath = "$env:TEMP\FiraCode.zip"
$extractPath = "$env:TEMP\FiraCodeFonts"
Invoke-WebRequest -Uri $fontUrl -OutFile $zipPath -UseBasicParsing
New-Item -ItemType Directory -Path $extractPath -Force | Out-Null
Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
Get-ChildItem -Path $extractPath -Filter "*.ttf" -Recurse | ForEach-Object {
$fontPath = $_.FullName
$shell = New-Object -ComObject Shell.Application
$fontsFolder = $shell.Namespace(0x14) # Fonts folder
$fontsFolder.CopyHere($fontPath)
}
Remove-Item -Path $zipPath -Force
Remove-Item -Path $extractPath -Recurse -Force
Write-Host "Fonts installed successfully: $($fontsMissing -join ', ')"
} catch {
Write-Warning "Font installation failed: $_"
}
} else {
Write-Host "All specified fonts are already installed."
}
}
# -----------------------------
# PowerShell Update
# -----------------------------
function Update-PowerShell {
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Write-Warning "winget is not installed. Skipping PowerShell update."
return
}
if (-not (Test-NetConnection -ComputerName github.com -InformationLevel Quiet)) {
Write-Host "Skipping PowerShell update check (GitHub unreachable)." -ForegroundColor Yellow
return
}
try {
Write-Host "Checking for PowerShell updates..." -ForegroundColor Cyan
$currentVersion = [Version]$PSVersionTable.PSVersion
$gitHubApiUrl = "https://api.github.com/repos/PowerShell/PowerShell/releases/latest"
$latestReleaseInfo = Invoke-RestMethod -Uri $gitHubApiUrl
$latestVersion = [Version]$latestReleaseInfo.tag_name.Trim('v')
if ($currentVersion -lt $latestVersion) {
Write-Host "Updating PowerShell from $currentVersion to $latestVersion..." -ForegroundColor Yellow
winget install --id Microsoft.Powershell --source winget --accept-package-agreements --accept-source-agreements
Write-Host "PowerShell updated. Restart your shell." -ForegroundColor Magenta
} else {
Write-Host "PowerShell $currentVersion is up to date." -ForegroundColor Green
}
} catch {
Write-Error "Failed to check/update PowerShell: $_"
}
}
# -----------------------------
# Admin Check and Prompt
# -----------------------------
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
function prompt {
if ($isAdmin) {
"[" + (Get-Location) + "] # "
} else {
"[" + (Get-Location) + "] $ "
}
}
$adminSuffix = if ($isAdmin) { " [ADMIN]" } else { "" }
$Host.UI.RawUI.WindowTitle = "PowerShell {0}$adminSuffix" -f $PSVersionTable.PSVersion.ToString()
# -----------------------------
# Oh-My-Posh
# -----------------------------
if (Test-Path ~/termTheme.json) {
Invoke-Expression (oh-my-posh --init --shell pwsh --config ~/termTheme.json)
} else {
Write-Warning "Oh-My-Posh theme file not found at ~/termTheme.json"
}
# -----------------------------
# Paths
# -----------------------------
$rust = "$env:USERPROFILE\OneDrive - HSO\Desktop\My Files\Rust"
$repos = "$env:USERPROFILE\source\repos"
$work = "$env:USERPROFILE\OneDrive - HSO\Desktop\HSO"
$myfiles = "$env:USERPROFILE\OneDrive - HSO\Desktop\My Files"
$desktop = "$env:USERPROFILE\OneDrive - HSO\Desktop"
$downloads= "$env:USERPROFILE\Downloads"
$settings = "$env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
$nvim = "$env:USERPROFILE\AppData\Local\nvim\"
$wez = "$env:USERPROFILE\.wezterm.lua"
$glaze = "$env:USERPROFILE\.glzr\glazewm\config.yaml"
$billz = "$myfiles\billz.md"
$yasb = "$env:USERPROFILE\.config\yasb"
$todo = "$env:USERPROFILE\OneDrive - HSO\Desktop\My Files\todo.md"
$projects = "$env:USERPROFILE\OneDrive - HSO\Desktop\My Files\projects"
$tmp = "$env:USERPROFILE\tmp"
# -----------------------------
# Add-ToPath Helper
# -----------------------------
function Add-ToPath($path) {
if (-not ($env:Path.Split(';') -contains $path)) {
$env:Path += ";$path"
}
}
Add-ToPath "$env:USERPROFILE\.cargo\bin"
Add-ToPath "$env:USERPROFILE\OneDrive - HSO\Desktop\My Files\CodemerxDecompilex64"
Add-ToPath "C:\Python312\Scripts"
Add-ToPath "C:\Program Files\GitHub CLI"
Add-ToPath "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin"
# -----------------------------
# Utility Functions
# -----------------------------
function sysinfo { Get-ComputerInfo }
function resetnetwork {
if (-not $isAdmin) {
Write-Warning "Network reset requires admin privileges. Run as admin and try again."
return
}
ipconfig /release | Out-Null
ipconfig /flushdns | Out-Null
Clear-DnsClientCache | Out-Null
ipconfig /renew | Out-Null
Write-Host "Network has been reset" -ForegroundColor Green
}
function flushdns {
Clear-DnsClientCache
Write-Host "DNS has been flushed"
}
function weather($loc) {
try { Invoke-RestMethod "https://wttr.in/$loc" -ErrorAction Stop }
catch { Write-Warning "Failed to fetch weather for '$loc': $_" }
}
function text { Start-Process "https://messages.google.com/web" }
function def($s) { wikit $s }
function whereis($c) { Get-Command -Name $c -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue }
function qr($s) {
try { Invoke-RestMethod "https://qrenco.de/$s" -ErrorAction Stop }
catch { Write-Warning "Failed to generate QR code: $_" }
}
function fcd {
if (-not (Get-Command fzf -ErrorAction SilentlyContinue)) {
Write-Warning "fzf is not installed. Please install it to use fcd."
return
}
# Use fzf to pick a file or folder
$path = fzf
if ($path) {
# If a file is selected, get its directory; if a folder, use it directly
if (Test-Path $path -PathType Leaf) {
Set-Location (Split-Path $path)
} else {
Set-Location $path
}
}
}
function nfcd {
if (-not (Get-Command fzf -ErrorAction SilentlyContinue)) {
Write-Warning "fzf is not installed. Please install it to use fcd."
return
}
# Use fzf to pick a file or folder
$path = fzf
if ($path) {
# If a file is selected, get its directory; if a folder, use it directly
if (Test-Path $path -PathType Leaf) {
nvim (Split-Path $path)
} else {
nvim $path
}
}
}
function profile { nvim $profile }
function downloads { Set-Location $downloads }
function gpro { nvim $glaze }
function wpro { nvim $wez }
function billz { nvim $billz }
function rust { nvim $rust }
function npro { Set-Location $nvim; nvim .}
function repos { Set-Location $repos; nvim .}
function work { Set-Location $work }
function desktop { Set-Location $desktop }
function myfiles { Set-Location $myfiles }
function home { Set-Location ~ }
function yasb { nvim $yasb }
function todo { nvim $todo }
function tmp { nvim $tmp }
function projects { Set-Location $projects; nvim . }
function mkcd($dir) { mkdir $dir -Force; Set-Location $dir }
function la { Get-ChildItem -Force | Format-Table -AutoSize }
function ll { Get-ChildItem -Force -Hidden | Format-Table -AutoSize }
function gs { git status }
function ga { git add . }
function gc($m) { git commit -m "$m" }
function gp { git push }
function gcl { git clone "$args" }
function gcom { git add .; git commit -m "$args" }
function lazyg { git add .; git commit -m "$args"; git push }
function cpy { Set-Clipboard $args[0] }
function pst { Get-Clipboard }
function df { Get-Volume }
function touch($file) { "" | Out-File $file -Encoding ASCII }
function ff($n) { Get-ChildItem -Recurse -Filter "${n}" -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } }
function Get-PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content }
function admin { Start-Process wt -Verb runAs }
function arch
{
wsl -d archlinux
}
function netlist {
[CmdletBinding()]
param (
[string]$Subnet,
[switch]$PingOnly,
[int]$TimeoutMs = 1000
)
# Check if nmap is available
if (-not (Get-Command nmap -ErrorAction SilentlyContinue)) {
Write-Error "Nmap is not installed or not in PATH. Download from https://nmap.org/download.html"
return
}
# Get Wi-Fi IP configuration only
$wifiIPs = Get-NetIPAddress -AddressFamily IPv4 |
Where-Object {
$_.IPAddress -notlike "127.*" -and
$_.IPAddress -notlike "169.254.*" -and
(Get-NetAdapter -InterfaceIndex $_.InterfaceIndex).InterfaceDescription -like "*Wi*"
}
if (-not $Subnet -and $wifiIPs) {
$wifiIP = $wifiIPs[0].IPAddress
$subnetParts = ($wifiIP -split '\.') | Select-Object -First 3
$base = $subnetParts -join '.'
$Subnet = "$base.0/24"
Write-Host "Auto-detected Wi-Fi subnet: $Subnet" -ForegroundColor Cyan
Write-Host "Wi-Fi Interface: $($wifiIPs[0].InterfaceAlias) - $($wifiIPs[0].IPAddress)" -ForegroundColor Cyan
} elseif (-not $Subnet) {
Write-Warning "Could not determine Wi-Fi subnet. Please specify -Subnet parameter (e.g., '192.168.1.0/24')."
return
}
Write-Host "Scanning $Subnet with Nmap (host discovery + DNS resolution)..." -ForegroundColor Yellow
# Run nmap: -sn (ping scan/host discovery), -R (always resolve DNS), -T4 (fast timing), --host-timeout for speed
$nmapArgs = @('-sn', '-R', '-T4', '--host-timeout', '5s', '--stats-every', '10s', $Subnet)
$nmapOutput = & nmap $nmapArgs 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Error "Nmap scan failed. Output: $nmapOutput"
return
}
# Parse Nmap output for hosts
$results = @()
$currentHost = $null
$inHostBlock = $false
foreach ($line in $nmapOutput) {
if ($line -match 'Nmap scan report for\s+(.+?)\s+\((.+?)\)') {
# New host block starts
$inHostBlock = $true
$hostname = $matches[1].Trim()
$ip = $matches[2].Trim()
if ($hostname -eq $ip) { $hostname = "Unknown" }
$currentHost = [PSCustomObject]@{
IPAddress = $ip
Hostname = $hostname
MACAddress = "N/A"
Status = "Up"
}
} elseif ($inHostBlock -and $line -match 'MAC Address:\s+([0-9A-Fa-f:]{17})') {
# MAC from ARP (local networks)
$currentHost.MACAddress = $matches[1]
} elseif ($line -match '^Host is up') {
$currentHost.Status = "Up"
} elseif ($line -match '^Host seems down') {
# Skip down hosts for concise output
continue
} elseif ($line -match '^Nmap done:') {
# End of scan
$inHostBlock = $false
if ($currentHost -and $currentHost.Status -eq "Up") {
$results += $currentHost
}
} elseif ($inHostBlock -and $line.Trim() -eq "") {
# End of host block
if ($currentHost -and $currentHost.Status -eq "Up") {
$results += $currentHost
}
$currentHost = $null
$inHostBlock = $false
}
}
# Add local Wi-Fi machine info if not already in results
if ($wifiIPs) {
$localIP = $wifiIPs[0].IPAddress
$wifiAdapter = Get-NetAdapter -InterfaceIndex $wifiIPs[0].InterfaceIndex
$localMAC = $wifiAdapter.MacAddress
if (-not $localMAC) { $localMAC = "N/A" }
$localResult = [PSCustomObject]@{
IPAddress = $localIP
Hostname = $env:COMPUTERNAME
MACAddress = $localMAC
Status = "Up (Local Wi-Fi)"
}
if (-not ($results | Where-Object { $_.IPAddress -eq $localIP })) {
$results = @($localResult) + $results
}
}
# Display concise results
$results | Sort-Object IPAddress |
Format-Table IPAddress, Hostname, MACAddress, Status -AutoSize -Wrap
Write-Host "`nNmap scan completed. Found $($results.Count) hosts up on $Subnet." -ForegroundColor Green
return $results
}
# Simpler ARP-based function as backup
function Get-NetDevices-Arp {
[CmdletBinding()]
param([string]$InterfacePrefix)
if (-not $InterfacePrefix) {
$localIP = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -notlike "127.*" -and $_.IPAddress -notlike "169.254.*" } | Select-Object -First 1).IPAddress
$InterfacePrefix = ($localIP -split '\.') | Select-Object -First 3 | Join-String -Separator '.'
}
Write-Host "Scanning ARP cache for $InterfacePrefix.* devices..." -ForegroundColor Yellow
$arpDevices = @()
$inInterface = $false
arp -a | ForEach-Object {
if ($_ -match "^Interface:\s+$InterfacePrefix") {
$inInterface = $true
} elseif ($_ -match "^Interface:") {
$inInterface = $false
} elseif ($inInterface -and $_ -match "^\s*($InterfacePrefix[0-9]{1,3})\s+([0-9A-Fa-f-]{17})") {
$ip = $matches[1]
$mac = $matches[2].ToUpper()
# Check if device responds to ping
$ping = Test-Connection -ComputerName $ip -Count 1 -Quiet -ErrorAction SilentlyContinue
$hostname = if ($ping) {
try {
$dns = [System.Net.Dns]::GetHostEntry($ip)
$dns.HostName
} catch { "Unknown" }
} else { "Offline" }
$arpDevices += [PSCustomObject]@{
IPAddress = $ip
MACAddress = $mac
Hostname = $hostname
Status = if ($ping) { "Online" } else { "ARP Cache" }
}
}
}
$arpDevices | Sort-Object IPAddress | Format-Table -AutoSize
return $arpDevices
}
function apples
{
$url = "https://www.netify.ai/resources/macs/brands/apple"
try
{
$pageContent = Invoke-WebRequest -Uri $url -UseBasicParsing
$appleOuis = [regex]::Matches($pageContent.Content, "(?:[0-9A-Fa-f]{2}:){2}[0-9A-Fa-f]{2}") |
ForEach-Object { $_.Value.ToUpper() } | Sort-Object -Unique
} catch
{
Write-Output "Failed to fetch MAC prefix list from the website."
return
}
arp -a | ForEach-Object {
if ($_ -match "^\s*([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\s+([0-9A-F-]+)")
{
$ipAddress = $matches[1]
$macAddress = $matches[2].ToUpper() -replace "-", ":"
$isAppleDevice = $appleOuis | ForEach-Object { $macAddress.StartsWith($_) } | Where-Object { $_ -eq $true }
if ($isAppleDevice)
{
$hostname = ""
try
{
$hostname = (Resolve-DnsName -Name $ipAddress -ErrorAction Stop).NameHost
} catch
{
$hostname = "Not resolved"
}
[PSCustomObject]@{
IPAddress = $ipAddress
MACAddress = $macAddress
Hostname = $hostname
DeviceType = "Apple"
}
}
}
} | Format-Table -AutoSize
}
function Count-Lines {
param(
[string]$Path = "."
)
# File types to include
$extensions = @("*.js", "*.jsx", "*.ts", "*.tsx", "*.css", "*.scss", "*.py", "*.html", "*.json")
# Directories to exclude
$excludedDirs = @("node_modules", "output_files")
Write-Host "Counting lines in $Path ..." -ForegroundColor Cyan
$totalLines = 0
$totalFiles = 0
# Get all files recursively, excluding unwanted directories
$files = Get-ChildItem -Path $Path -Recurse -Include $extensions -File -ErrorAction SilentlyContinue |
Where-Object {
foreach ($exclude in $excludedDirs) {
if ($_.FullName -match "(\\|/)$exclude(\\|/|$)") { return $false }
if ($_.FullName -match "(\\|/)$exclude\\b") { return $false }
}
return $true
}
foreach ($file in $files) {
try {
$lineCount = (Get-Content -Path $file.FullName -ErrorAction Stop).Count
$totalLines += $lineCount
$totalFiles++
Write-Host ("{0,8} {1}" -f $lineCount, $file.FullName)
} catch {
Write-Warning "Could not read file: $($file.FullName)"
}
}
Write-Host "`nTotal files: $totalFiles" -ForegroundColor Yellow
Write-Host "Total lines: $totalLines" -ForegroundColor Green
}
function notes {
$date = Get-Date -Format "MMddyyyy"
$filename = "notes-$date.md"
$filepath = Join-Path -Path (Get-Location) -ChildPath $filename
if (Test-Path $filepath) {
Write-Host "Note file already exists: $filename" -ForegroundColor Yellow
} else {
$header = "# Notes - $(Get-Date -Format 'MMMM dd, yyyy')
## TODO
- [ ] Task 1
- [ ] Task 2
---
"
Set-Content -Path $filepath -Value $header -Encoding UTF8
Write-Host "Created: $filename" -ForegroundColor Green
}
if (Get-Command nvim -ErrorAction SilentlyContinue) {
nvim $filepath
Write-Host "Opened in Neovim: $filename" -ForegroundColor Cyan
} elseif (Get-Command vim -ErrorAction SilentlyContinue) {
vim $filepath
Write-Host "Opened in Vim: $filename" -ForegroundColor Cyan
} else {
Write-Host "Neovim/Vim not found. File ready at: $filepath" -ForegroundColor Red
Write-Host "Install with: winget install Neovim.Neovim" -ForegroundColor Yellow
}
}
Set-Alias countlines Count-Lines
Set-Alias neocrypt "C:\Users\AddisonFischer\OneDrive - HSO\Desktop\My Files\Useful Scripts\powershell\neocrypt.ps1"
Set-Alias su admin
# -----------------------------
# PSReadLine Config
# -----------------------------
Import-Module PSReadLine
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineOption -Colors @{ Command='Yellow'; Parameter='Green'; String='DarkCyan' }
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
dotnet complete --position $cursorPosition $commandAst.ToString() |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
Clear-Host
echo " 💪(.‿. )💪"