forked from ChrisTitusTech/powershell-profile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Microsoft.PowerShell_profile.ps1
313 lines (263 loc) · 11.3 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
### 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. ############
############ ############
#################################################################################################################################
# Opts out of telemetry before doing anything. This only happends when PowerShell is run as administrator!
if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) {
[System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine)
}
# Checks if there is a connection to GitHub (https://github.com) 5 second timeout
$canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 5
# Import modules and external profiles
# Ensure the Terminal-Icons module is installed before importing it
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 since there was no connection to GitHub (https://github.com)." -ForegroundColor Yellow
return
}
try {
Write-Host "Checking for Profile updates..." -ForegroundColor Cyan
$url = "https://raw.githubusercontent.com/F5T3/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 "The PowerShell profile has been updated. Please restart PowerShell for the changes to be reflected" -ForegroundColor Magenta
}
} catch {
Write-Error "Unable to check for `$profile updates"
} finally {
Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue
}
}
Update-Profile
#Check for PowerShell updates
function Update-PowerShell {
if (-not $global:canConnectToGitHub) {
Write-Host "Skipping profile update since there was no connection to GitHub (https://github.com)." -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 PowerShell for the changes to be reflected" -ForegroundColor Magenta
} else {
Write-Host "Your PowerShell is up to date." -ForegroundColor Green
}
} catch {
Write-Error "Failed to update PowerShell. Error: $_"
}
}
Update-PowerShell
function Fix-ModuleRepos {
Get-ChildItem -Path $env:PSModulePath.Split(';') -Filter 'PackageManagement' -Directory -ErrorAction SilentlyContinue |
Get-ChildItem -Directory |
Where-Object -Property Name -Match '\d*\.\d*\.\d*' |
Get-ChildItem -Filter 'netstandard2.0' -Directory |
ForEach-Object -Process {
foreach ($clr in 'fullclr', 'coreclr') {
Copy-Item -Path $_.FullName -Destination "$($_.Parent)\$clr" -Recurse -ErrorAction SilentlyContinue
}
}
}
Fix-ModuleRepos
# 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 cursor) { 'cursor' }
elseif (Test-CommandExists sublime_text) {'sublime_text' }
elseif (Test-CommandExists code) { 'code' }
elseif (Test-CommandExists notepad++) { 'notepad++' }
elseif (Test-CommandExists notepads) { 'notepads' }
else {'notepad'}
Set-Alias -Name nvim -Value $EDITOR
Set-Alias -Name pvim -Value $EDITOR
Set-Alias -Name vim -Value $EDITOR
Set-Alias -Name vi -Value $EDITOR
Set-Alias -Name cursor -Value $EDITOR
Set-Alias -Name sublime_text -Value $EDITOR
Set-Alias -Name code -Value $EDITOR
Set-Alias -Name notepad++ -Value $EDITOR
Set-Alias -Name notepads -Value $EDITOR
Set-Alias -Name notepad -Value $EDITOR
function Edit {
nvim $PROFILE.CurrentUserAllHosts
}
function touch($file) { "" | Out-File $file -Encoding ASCII }
function ff($name) {
Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object {
Write-Output "$($_.directory)\$($_)"
}
}
# Network Utilities
function PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content }
# System Utilities
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 Sync {
& "$PROFILE | Split-Path\..\sync.ps1"
}
function Reload {
& $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)
Get-Content $Path -Tail $n
}
# 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 { nvim $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 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 }
# Clipboard Utilities
function cpy { Set-Clipboard $args[0] }
function pst { Get-Clipboard }
# Enhanced PowerShell Experience
Set-PSReadLineOption -Colors @{
Command = 'Yellow'
Parameter = 'Green'
String = 'DarkCyan'
}
## Final Line to set prompt
oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression
if (Get-Command zoxide -ErrorAction SilentlyContinue) {
Invoke-Expression (& { (zoxide init powershell | Out-String) })
}
fastfetch