forked from ChrisTitusTech/powershell-profile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Microsoft.PowerShell_profile.ps1
433 lines (336 loc) · 14.4 KB
/
Microsoft.PowerShell_profile.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
### PowerShell Profile Refactor
### Version 1.03 - Refactored
#################################################################################################################################
############ ############
############ !!! WARNING: !!! ############
############ ############
############ DO NOT MODIFY THIS FILE. THIS FILE IS HASHED AND UPDATED AUTOMATICALLY. ############
############ ANY CHANGES MADE TO THIS FILE WILL BE OVERWRITTEN BY COMMITS TO ############
############ https://github.com/ChrisTitusTech/powershell-profile.git. ############
############ ############
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
############ ############
############ IF YOU WANT TO MAKE CHANGES, USE THE Edit-Profile FUNCTION ############
############ AND SAVE YOUR CHANGES IN THE FILE CREATED. ############
############ ############
#################################################################################################################################
# Initial GitHub.com connectivity check with 1 second timeout
$canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1
# Import Modules and External Profiles
# Ensure Terminal-Icons module is installed before importing
if (-not (Get-Module -ListAvailable -Name Terminal-Icons)) {
Install-Module -Name Terminal-Icons -Scope CurrentUser -Force -SkipPublisherCheck
}
Import-Module -Name Terminal-Icons
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
# Check for Profile Updates
function Update-Profile {
if (-not $global:canConnectToGitHub) {
Write-Host "Skipping profile update check due to GitHub.com not responding within 1 second." -ForegroundColor Yellow
return
}
try {
$url = "https://raw.githubusercontent.com/ChrisTitusTech/powershell-profile/main/Microsoft.PowerShell_profile.ps1"
$oldhash = Get-FileHash $PROFILE
Invoke-RestMethod $url -OutFile "$env:temp/Microsoft.PowerShell_profile.ps1"
$newhash = Get-FileHash "$env:temp/Microsoft.PowerShell_profile.ps1"
if ($newhash.Hash -ne $oldhash.Hash) {
Copy-Item -Path "$env:temp/Microsoft.PowerShell_profile.ps1" -Destination $PROFILE -Force
Write-Host "Profile has been updated. Please restart your shell to reflect changes" -ForegroundColor Magenta
}
} catch {
Write-Error "Unable to check for `$profile updates"
} finally {
Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue
}
}
Update-Profile
function Update-PowerShell {
if (-not $global:canConnectToGitHub) {
Write-Host "Skipping PowerShell update check due to GitHub.com not responding within 1 second." -ForegroundColor Yellow
return
}
try {
Write-Host "Checking for PowerShell updates..." -ForegroundColor Cyan
$updateNeeded = $false
$currentVersion = $PSVersionTable.PSVersion.ToString()
$gitHubApiUrl = "https://api.github.com/repos/PowerShell/PowerShell/releases/latest"
$latestReleaseInfo = Invoke-RestMethod -Uri $gitHubApiUrl
$latestVersion = $latestReleaseInfo.tag_name.Trim('v')
if ($currentVersion -lt $latestVersion) {
$updateNeeded = $true
}
if ($updateNeeded) {
Write-Host "Updating PowerShell..." -ForegroundColor Yellow
winget upgrade "Microsoft.PowerShell" --accept-source-agreements --accept-package-agreements
Write-Host "PowerShell has been updated. Please restart your shell to reflect changes" -ForegroundColor Magenta
} else {
Write-Host "Your PowerShell is up to date." -ForegroundColor Green
}
} catch {
Write-Error "Failed to update PowerShell. Error: $_"
}
}
Update-PowerShell
# Admin Check and Prompt Customization
$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()
# Utility Functions
function Test-CommandExists {
param($command)
$exists = $null -ne (Get-Command $command -ErrorAction SilentlyContinue)
return $exists
}
# Editor Configuration
$EDITOR = if (Test-CommandExists nvim) { 'nvim' }
elseif (Test-CommandExists pvim) { 'pvim' }
elseif (Test-CommandExists vim) { 'vim' }
elseif (Test-CommandExists vi) { 'vi' }
elseif (Test-CommandExists code) { 'code' }
elseif (Test-CommandExists notepad++) { 'notepad++' }
elseif (Test-CommandExists sublime_text) { 'sublime_text' }
else { 'notepad' }
Set-Alias -Name vim -Value $EDITOR
function Edit-Profile {
vim $PROFILE.CurrentUserAllHosts
}
function touch($file) { "" | Out-File $file -Encoding ASCII }
function ff($name) {
Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object {
Write-Output "$($_.FullName)"
}
}
# Network Utilities
function Get-PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content }
# Open WinUtil
function winutil {
iwr -useb https://christitus.com/win | iex
}
# System Utilities
function admin {
if ($args.Count -gt 0) {
$argList = "& '$args'"
Start-Process wt -Verb runAs -ArgumentList "pwsh.exe -NoExit -Command $argList"
} else {
Start-Process wt -Verb runAs
}
}
# Set UNIX-like aliases for the admin command, so sudo <command> will run the command with elevated rights.
Set-Alias -Name su -Value admin
function uptime {
if ($PSVersionTable.PSVersion.Major -eq 5) {
Get-WmiObject win32_operatingsystem | Select-Object @{Name='LastBootUpTime'; Expression={$_.ConverttoDateTime($_.lastbootuptime)}} | Format-Table -HideTableHeaders
} else {
net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') }
}
}
function reload-profile {
& $profile
}
function unzip ($file) {
Write-Output("Extracting", $file, "to", $pwd)
$fullFile = Get-ChildItem -Path $pwd -Filter $file | ForEach-Object { $_.FullName }
Expand-Archive -Path $fullFile -DestinationPath $pwd
}
function hb {
if ($args.Length -eq 0) {
Write-Error "No file path specified."
return
}
$FilePath = $args[0]
if (Test-Path $FilePath) {
$Content = Get-Content $FilePath -Raw
} else {
Write-Error "File path does not exist."
return
}
$uri = "http://bin.christitus.com/documents"
try {
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $Content -ErrorAction Stop
$hasteKey = $response.key
$url = "http://bin.christitus.com/$hasteKey"
Write-Output $url
} catch {
Write-Error "Failed to upload the document. Error: $_"
}
}
function grep($regex, $dir) {
if ( $dir ) {
Get-ChildItem $dir | select-string $regex
return
}
$input | select-string $regex
}
function df {
get-volume
}
function sed($file, $find, $replace) {
(Get-Content $file).replace("$find", $replace) | Set-Content $file
}
function which($name) {
Get-Command $name | Select-Object -ExpandProperty Definition
}
function export($name, $value) {
set-item -force -path "env:$name" -value $value;
}
function pkill($name) {
Get-Process $name -ErrorAction SilentlyContinue | Stop-Process
}
function pgrep($name) {
Get-Process $name
}
function head {
param($Path, $n = 10)
Get-Content $Path -Head $n
}
function tail {
param($Path, $n = 10, [switch]$f = $false)
Get-Content $Path -Tail $n -Wait:$f
}
# Quick File Creation
function nf { param($name) New-Item -ItemType "file" -Path . -Name $name }
# Directory Management
function mkcd { param($dir) mkdir $dir -Force; Set-Location $dir }
### Quality of Life Aliases
# Navigation Shortcuts
function docs { Set-Location -Path $HOME\Documents }
function dtop { Set-Location -Path $HOME\Desktop }
# Quick Access to Editing the Profile
function ep { vim $PROFILE }
# Simplified Process Management
function k9 { Stop-Process -Name $args[0] }
# Enhanced Listing
function la { Get-ChildItem -Path . -Force | Format-Table -AutoSize }
function ll { Get-ChildItem -Path . -Force -Hidden | Format-Table -AutoSize }
# Git Shortcuts
function gs { git status }
function ga { git add . }
function gc { param($m) git commit -m "$m" }
function gp { git push }
function g { z Github }
function gcl { git clone "$args" }
function gcom {
git add .
git commit -m "$args"
}
function lazyg {
git add .
git commit -m "$args"
git push
}
# Quick Access to System Information
function sysinfo { Get-ComputerInfo }
# Networking Utilities
function flushdns {
Clear-DnsClientCache
Write-Host "DNS has been flushed"
}
# Clipboard Utilities
function cpy { Set-Clipboard $args[0] }
function pst { Get-Clipboard }
# Enhanced PowerShell Experience
Set-PSReadLineOption -Colors @{
Command = 'Yellow'
Parameter = 'Green'
String = 'DarkCyan'
}
$PSROptions = @{
ContinuationPrompt = ' '
Colors = @{
Parameter = $PSStyle.Foreground.Magenta
Selection = $PSStyle.Background.Black
InLinePrediction = $PSStyle.Foreground.BrightYellow + $PSStyle.Background.BrightBlack
}
}
Set-PSReadLineOption @PSROptions
Set-PSReadLineKeyHandler -Chord 'Ctrl+f' -Function ForwardWord
Set-PSReadLineKeyHandler -Chord 'Enter' -Function ValidateAndAcceptLine
$scriptblock = {
param($wordToComplete, $commandAst, $cursorPosition)
dotnet complete --position $cursorPosition $commandAst.ToString() |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock
# Get theme from profile.ps1 or use a default theme
function Get-Theme {
if (Test-Path -Path $PROFILE.CurrentUserAllHosts -PathType leaf) {
$existingTheme = Select-String -Raw -Path $PROFILE.CurrentUserAllHosts -Pattern "oh-my-posh init pwsh --config"
if ($null -ne $existingTheme) {
Invoke-Expression $existingTheme
return
}
} else {
oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression
}
}
## Final Line to set prompt
Get-Theme
if (Get-Command zoxide -ErrorAction SilentlyContinue) {
Invoke-Expression (& { (zoxide init --cmd cd powershell | Out-String) })
} else {
Write-Host "zoxide command not found. Attempting to install via winget..."
try {
winget install -e --id ajeetdsouza.zoxide
Write-Host "zoxide installed successfully. Initializing..."
Invoke-Expression (& { (zoxide init powershell | Out-String) })
} catch {
Write-Error "Failed to install zoxide. Error: $_"
}
}
# Help Function
function Show-Help {
@"
PowerShell Profile Help
=======================
Update-Profile - Checks for profile updates from a remote repository and updates if necessary.
Update-PowerShell - Checks for the latest PowerShell release and updates if a new version is available.
Edit-Profile - Opens the current user's profile for editing using the configured editor.
touch <file> - Creates a new empty file.
ff <name> - Finds files recursively with the specified name.
Get-PubIP - Retrieves the public IP address of the machine.
winutil - Runs the WinUtil script from Chris Titus Tech.
uptime - Displays the system uptime.
reload-profile - Reloads the current user's PowerShell profile.
unzip <file> - Extracts a zip file to the current directory.
hb <file> - Uploads the specified file's content to a hastebin-like service and returns the URL.
grep <regex> [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input.
df - Displays information about volumes.
sed <file> <find> <replace> - Replaces text in a file.
which <name> - Shows the path of the command.
export <name> <value> - Sets an environment variable.
pkill <name> - Kills processes by name.
pgrep <name> - Lists processes by name.
head <path> [n] - Displays the first n lines of a file (default 10).
tail <path> [n] - Displays the last n lines of a file (default 10).
nf <name> - Creates a new file with the specified name.
mkcd <dir> - Creates and changes to a new directory.
docs - Changes the current directory to the user's Documents folder.
dtop - Changes the current directory to the user's Desktop folder.
ep - Opens the profile for editing.
k9 <name> - Kills a process by name.
la - Lists all files in the current directory with detailed formatting.
ll - Lists all files, including hidden, in the current directory with detailed formatting.
gs - Shortcut for 'git status'.
ga - Shortcut for 'git add .'.
gc <message> - Shortcut for 'git commit -m'.
gp - Shortcut for 'git push'.
g - Changes to the GitHub directory.
gcom <message> - Adds all changes and commits with the specified message.
lazyg <message> - Adds all changes, commits with the specified message, and pushes to the remote repository.
sysinfo - Displays detailed system information.
flushdns - Clears the DNS cache.
cpy <text> - Copies the specified text to the clipboard.
pst - Retrieves text from the clipboard.
Use 'Show-Help' to display this help message.
"@
}
Write-Host "Use 'Show-Help' to display help"