From 18bad108e373e1cf5b17265cf230af478a94bb32 Mon Sep 17 00:00:00 2001 From: tay_shell Date: Thu, 9 May 2024 23:15:09 -0300 Subject: [PATCH 01/64] Added ctrl+f to accept next line & li to list directory and format wide to a column of 3 --- Microsoft.PowerShell_profile.ps1 | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 278e8a4a..23729094 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -256,6 +256,31 @@ Set-PSReadLineOption -Colors @{ 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 + + + + ## 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) { From 1810ae2b002b7a5a2f3c6dd1371635447cf85409 Mon Sep 17 00:00:00 2001 From: poa00 Date: Sun, 23 Jun 2024 19:28:09 -0500 Subject: [PATCH 02/64] Update README.md --- README.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c126960a..6c33cfcf 100644 --- a/README.md +++ b/README.md @@ -12,11 +12,35 @@ irm "https://github.com/ChrisTitusTech/powershell-profile/raw/main/setup.ps1" | ## 🛠️ Fix the Missing Font -After running the script, you'll find a downloaded `cove.zip` file in the folder you executed the script from. Follow these steps to install the required nerd fonts: +After running the script, you'll have two options for installing a font patched to support icons in PowerShell: + +### 1) You will find a downloaded `cove.zip` file in the folder you executed the script from. Follow these steps to install the patched `Caskaydia Cove` nerd font family: 1. Extract the `cove.zip` file. 2. Locate and install the nerd fonts. +### 2) With `oh-my-posh` (loaded automatically through the PowerShell profile script hosted on this repo): +1. Run the command `oh-my-posh font install` +2. A list of Nerd Fonts will appear like so: +
+PS> oh-my-posh font install
+
+   Select font
+
+  > 0xProto
+    3270
+    Agave
+    AnonymousPro
+    Arimo
+    AurulentSansMono
+    BigBlueTerminal
+    BitstreamVeraSansMono
+
+    •••••••••
+    ↑/k up • ↓/j down • q quit • ? more
+3. With the up/down arrow keys, select the font you would like to install and press ENTER +4. DONE! + ## Customize this profile **Do not make any changes to the `Microsoft.PowerShell_profile.ps1` file**, since it's hashed and automatically overwritten by any commits to this repository. From 8e1ea84d7c021d378a1b5fa6d290ba5340de2cdd Mon Sep 17 00:00:00 2001 From: korneltlaczala Date: Wed, 26 Jun 2024 21:58:33 +0200 Subject: [PATCH 03/64] setprofile.ps1 script for debugging --- setprofile.ps1 | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 setprofile.ps1 diff --git a/setprofile.ps1 b/setprofile.ps1 new file mode 100644 index 00000000..32e135c2 --- /dev/null +++ b/setprofile.ps1 @@ -0,0 +1,2 @@ +$profilePath = Split-Path -Path $PROFILE +copy .\Microsoft.PowerShell_profile.ps1 $profilePath \ No newline at end of file From d72ea9713df1d1440d71962a2500a447dc1b2248 Mon Sep 17 00:00:00 2001 From: korneltlaczala Date: Wed, 26 Jun 2024 21:59:34 +0200 Subject: [PATCH 04/64] add legacy zoxide commands --- Microsoft.PowerShell_profile.ps1 | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 91992e0e..5f226c8b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -321,6 +321,9 @@ if (Get-Command zoxide -ErrorAction SilentlyContinue) { } } +Set-Alias -Name z -Value __zoxide_z +Set-Alias -Name zi -Value __zoxide_zi + # Help Function function Show-Help { @" From c731d932594b7aaf5a2270226deaedc46942128d Mon Sep 17 00:00:00 2001 From: korneltlaczala Date: Wed, 26 Jun 2024 22:08:27 +0200 Subject: [PATCH 05/64] make g function more robust --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 5f226c8b..7f2a1fec 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -258,7 +258,7 @@ function gc { param($m) git commit -m "$m" } function gp { git push } -function g { z Github } +function g { __zoxide_z github } function gcl { git clone "$args" } From efe8cd66da4e7b91d8f05c559f42da084108fda2 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 1 Jul 2024 07:24:46 +0200 Subject: [PATCH 06/64] changes suggested by TakenMC --- Microsoft.PowerShell_profile.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 7f2a1fec..e541f6a4 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -321,8 +321,8 @@ if (Get-Command zoxide -ErrorAction SilentlyContinue) { } } -Set-Alias -Name z -Value __zoxide_z -Set-Alias -Name zi -Value __zoxide_zi +Set-Alias -Name z -Value __zoxide_z -Option AllScope -Scope Global -Force +Set-Alias -Name zi -Value __zoxide_zi -Option AllScope -Scope Global -Force # Help Function function Show-Help { From 8fd495d0da7803d28d79fcddd3a7e9705e0690a7 Mon Sep 17 00:00:00 2001 From: MyDrift Date: Tue, 2 Jul 2024 20:05:57 +0200 Subject: [PATCH 07/64] opt-out of telemetry --- Microsoft.PowerShell_profile.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 91992e0e..9848af8f 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -16,6 +16,9 @@ ############ ############ ################################################################################################################################# +#opt-out of telemetry before doing anything +$env:POWERSHELL_TELEMETRY_OPTOUT = "1" + # Initial GitHub.com connectivity check with 1 second timeout $canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 @@ -408,4 +411,4 @@ pst - Retrieves text from the clipboard. Use 'Show-Help' to display this help message. "@ } -Write-Host "Use 'Show-Help' to display help" \ No newline at end of file +Write-Host "Use 'Show-Help' to display help" From 8543ed1d3a3e35d1914190ed9d9d58780df018b9 Mon Sep 17 00:00:00 2001 From: MyDrift Date: Wed, 3 Jul 2024 07:50:19 +0200 Subject: [PATCH 08/64] change to machine level --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 9848af8f..359d4673 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -17,7 +17,7 @@ ################################################################################################################################# #opt-out of telemetry before doing anything -$env:POWERSHELL_TELEMETRY_OPTOUT = "1" +[System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) # Initial GitHub.com connectivity check with 1 second timeout $canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 From 9f34ec5177c6e777700faf8dc09b4abae41dac56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Reynier?= Date: Mon, 8 Jul 2024 13:45:20 +0000 Subject: [PATCH 09/64] Add generic function to install Nerd Fonts --- setup.ps1 | 72 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 28 deletions(-) diff --git a/setup.ps1 b/setup.ps1 index e2149df1..1a835a28 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -16,6 +16,48 @@ function Test-InternetConnection { } } +# Function to install Nerd Fonts +function Install-NerdFonts { + param ( + [string]$FontName = "CascadiaCode", + [string]$FontDisplayName = "CaskaydiaCove NF", + [string]$Version = "3.2.1" + ) + + try { + [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") + $fontFamilies = (New-Object System.Drawing.Text.InstalledFontCollection).Families.Name + if ($fontFamilies -notcontains "${FontDisplayName}") { + $fontZipUrl = "https://github.com/ryanoasis/nerd-fonts/releases/download/v${Version}/${FontName}.zip" + $zipFilePath = "$env:TEMP\${FontName}.zip" + $extractPath = "$env:TEMP\${FontName}" + + $webClient = New-Object System.Net.WebClient + $webClient.DownloadFileAsync((New-Object System.Uri($fontZipUrl)), $zipFilePath) + + while ($webClient.IsBusy) { + Start-Sleep -Seconds 2 + } + + Expand-Archive -Path $zipFilePath -DestinationPath $extractPath -Force + $destination = (New-Object -ComObject Shell.Application).Namespace(0x14) + Get-ChildItem -Path $extractPath -Recurse -Filter "*.ttf" | ForEach-Object { + If (-not(Test-Path "C:\Windows\Fonts\$($_.Name)")) { + $destination.CopyHere($_.FullName, 0x10) + } + } + + Remove-Item -Path $extractPath -Recurse -Force + Remove-Item -Path $zipFilePath -Force + } else { + Write-Host "Font ${FontDisplayName} already installed" + } + } + catch { + Write-Error "Failed to download or install ${FontDisplayName} font. Error: $_" + } +} + # Check for internet connectivity before proceeding if (-not (Test-InternetConnection)) { break @@ -26,7 +68,7 @@ if (!(Test-Path -Path $PROFILE -PathType Leaf)) { try { # Detect Version of PowerShell & Create Profile directories if they do not exist. $profilePath = "" - if ($PSVersionTable.PSEdition -eq "Core") { + if ($PSVersionTable.PSEdition -eq "Core") { $profilePath = "$env:userprofile\Documents\Powershell" } elseif ($PSVersionTable.PSEdition -eq "Desktop") { @@ -66,33 +108,7 @@ catch { } # Font Install -try { - [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") - $fontFamilies = (New-Object System.Drawing.Text.InstalledFontCollection).Families.Name - - if ($fontFamilies -notcontains "CaskaydiaCove NF") { - $webClient = New-Object System.Net.WebClient - $webClient.DownloadFileAsync((New-Object System.Uri("https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/CascadiaCode.zip")), ".\CascadiaCode.zip") - - while ($webClient.IsBusy) { - Start-Sleep -Seconds 2 - } - - Expand-Archive -Path ".\CascadiaCode.zip" -DestinationPath ".\CascadiaCode" -Force - $destination = (New-Object -ComObject Shell.Application).Namespace(0x14) - Get-ChildItem -Path ".\CascadiaCode" -Recurse -Filter "*.ttf" | ForEach-Object { - If (-not(Test-Path "C:\Windows\Fonts\$($_.Name)")) { - $destination.CopyHere($_.FullName, 0x10) - } - } - - Remove-Item -Path ".\CascadiaCode" -Recurse -Force - Remove-Item -Path ".\CascadiaCode.zip" -Force - } -} -catch { - Write-Error "Failed to download or install the Cascadia Code font. Error: $_" -} +Install-NerdFonts -FontName "CascadiaCode" -FontDisplayName "CaskaydiaCove NF" # Final check and message to the user if ((Test-Path -Path $PROFILE) -and (winget list --name "OhMyPosh" -e) -and ($fontFamilies -contains "CaskaydiaCove NF")) { From fd0676878905ad3af47d453c9311ddb15fe8560b Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Sun, 14 Jul 2024 13:44:50 -0500 Subject: [PATCH 10/64] only run telemetry opt out on elevated prompt --- Microsoft.PowerShell_profile.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index b9c1fe04..8ad754bc 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -16,8 +16,10 @@ ############ ############ ################################################################################################################################# -#opt-out of telemetry before doing anything -[System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) +#opt-out of telemetry before doing anything, only if PowerShell is run as admin +if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) { + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) +} # Initial GitHub.com connectivity check with 1 second timeout $canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 From 6e10efb47a36689c5d40d62603051e803f768473 Mon Sep 17 00:00:00 2001 From: Kshamendra Date: Wed, 17 Jul 2024 04:30:57 +0530 Subject: [PATCH 11/64] fix(): ep as alias for Edit-Profile --- Microsoft.PowerShell_profile.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..1b1eff82 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -116,9 +116,12 @@ $EDITOR = if (Test-CommandExists nvim) { 'nvim' } else { 'notepad' } Set-Alias -Name vim -Value $EDITOR +# Quick Access to Editing the Profile function Edit-Profile { vim $PROFILE.CurrentUserAllHosts } +Set-Alias -Name ep -Value Edit-Profile + function touch($file) { "" | Out-File $file -Encoding ASCII } function ff($name) { Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object { @@ -244,9 +247,6 @@ 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] } From 3bf62610cba1b14688fabe15f809e67d0ab377ba Mon Sep 17 00:00:00 2001 From: Kshamendra Date: Wed, 17 Jul 2024 04:39:04 +0530 Subject: [PATCH 12/64] feat(): trash function --- Microsoft.PowerShell_profile.ps1 | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..ce1c5f40 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -237,6 +237,34 @@ function nf { param($name) New-Item -ItemType "file" -Path . -Name $name } # Directory Management function mkcd { param($dir) mkdir $dir -Force; Set-Location $dir } +function trash($path) { + $fullPath = (Resolve-Path -Path $path).Path + + if (Test-Path $fullPath) { + $item = Get-Item $fullPath + + if ($item.PSIsContainer) { + # Handle directory + $parentPath = $item.Parent.FullName + } else { + # Handle file + $parentPath = $item.DirectoryName + } + + $shell = New-Object -ComObject 'Shell.Application' + $shellItem = $shell.NameSpace($parentPath).ParseName($item.Name) + + if ($item) { + $shellItem.InvokeVerb('delete') + Write-Host "Item '$fullPath' has been moved to the Recycle Bin." + } else { + Write-Host "Error: Could not find the item '$fullPath' to trash." + } + } else { + Write-Host "Error: Item '$fullPath' does not exist." + } +} + ### Quality of Life Aliases # Navigation Shortcuts From 0d8e5d9df2df6e81f43876d41f6bbe421d5b1bd1 Mon Sep 17 00:00:00 2001 From: MyDrift Date: Wed, 17 Jul 2024 19:44:13 +0200 Subject: [PATCH 13/64] update winutil opening command --- Microsoft.PowerShell_profile.ps1 | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..1bb6e5fb 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -129,9 +129,14 @@ function ff($name) { # Network Utilities function Get-PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content } -# Open WinUtil +# Open WinUtil full-release function winutil { - iwr -useb https://christitus.com/win | iex + irm https://christitus.com/win | iex +} + +# Open WinUtil pre-release +function winutildev { + irm https://christitus.com/windev | iex } # System Utilities @@ -369,7 +374,9 @@ ff - 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. +winutil - Runs the latest WinUtil full-release script from Chris Titus Tech. + +winutildev - Runs the latest WinUtil pre-release script from Chris Titus Tech. uptime - Displays the system uptime. From e5e2979545d76ad27b1bbbe7494265790475f3fc Mon Sep 17 00:00:00 2001 From: MyDrift Date: Wed, 7 Aug 2024 13:34:01 +0200 Subject: [PATCH 14/64] add custom addons functionality --- Microsoft.PowerShell_profile.ps1 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..1443e889 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -438,4 +438,9 @@ pst - Retrieves text from the clipboard. Use 'Show-Help' to display this help message. "@ } + +if (Test-Path "$PSScriptRoot\CTTcustom.ps1") { + Invoke-Expression -Command "& `"$PSScriptRoot\CTTcustom.ps1`"" +} + Write-Host "Use 'Show-Help' to display help" From 220b446235bb8e74d6a57e7c0667ace94330fcc3 Mon Sep 17 00:00:00 2001 From: rothschild Date: Sun, 15 Sep 2024 20:03:21 +0300 Subject: [PATCH 15/64] Making navigation shortcuts work for users with onedrive (Works with PS5) --- Microsoft.PowerShell_profile.ps1 | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..0cfe01bc 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -240,9 +240,15 @@ 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 } +function docs { + $docs = if(([Environment]::GetFolderPath("MyDocuments"))) {([Environment]::GetFolderPath("MyDocuments"))} else {$HOME + "\Documents"} + Set-Location -Path $docs +} + +function dtop { + $dtop = if ([Environment]::GetFolderPath("Desktop")) {[Environment]::GetFolderPath("Desktop")} else {$HOME + "\Documents"} + Set-Location -Path $dtop +} # Quick Access to Editing the Profile function ep { vim $PROFILE } From 278fa51bc47478344c1c25651714272add3543be Mon Sep 17 00:00:00 2001 From: rothschild Date: Tue, 24 Sep 2024 10:03:44 +0300 Subject: [PATCH 16/64] adding default to Get-Theme so even if you have a leaf profile --- Microsoft.PowerShell_profile.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..df8af2ef 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -328,6 +328,7 @@ function Get-Theme { Invoke-Expression $existingTheme return } + oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression } else { oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression } From f607aabdc389ae15f2cef9853ccf87882c85cf41 Mon Sep 17 00:00:00 2001 From: Fahim Ahmed Date: Fri, 4 Oct 2024 14:40:42 +0600 Subject: [PATCH 17/64] add: auto copy hastebin url to clipboard --- Microsoft.PowerShell_profile.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..f1280a45 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -184,6 +184,7 @@ function hb { $response = Invoke-RestMethod -Uri $uri -Method Post -Body $Content -ErrorAction Stop $hasteKey = $response.key $url = "http://bin.christitus.com/$hasteKey" + Set-Clipboard $url Write-Output $url } catch { Write-Error "Failed to upload the document. Error: $_" From 249534f2c1e9aa3a38af66d6d523086b44effb3e Mon Sep 17 00:00:00 2001 From: Rudra Patel <77568653+ru-dr@users.noreply.github.com> Date: Mon, 14 Oct 2024 18:46:45 +0530 Subject: [PATCH 18/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 113 +++++++++++++++++++------------ 1 file changed, 68 insertions(+), 45 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..29ad6dfc 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -89,6 +89,28 @@ function Update-PowerShell { } Update-PowerShell +function Clear-Cache { + # add clear cache logic here + Write-Host "Clearing cache..." -ForegroundColor Cyan + + # Clear Windows Prefetch + Write-Host "Clearing Windows Prefetch..." -ForegroundColor Yellow + Remove-Item -Path "$env:SystemRoot\Prefetch\*" -Force -ErrorAction SilentlyContinue + + # Clear Windows Temp + Write-Host "Clearing Windows Temp..." -ForegroundColor Yellow + Remove-Item -Path "$env:SystemRoot\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue + + # Clear User Temp + Write-Host "Clearing User Temp..." -ForegroundColor Yellow + Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue + + # Clear Internet Explorer Cache + Write-Host "Clearing Internet Explorer Cache..." -ForegroundColor Yellow + Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\Windows\INetCache\*" -Recurse -Force -ErrorAction SilentlyContinue + + Write-Host "Cache clearing completed." -ForegroundColor Green +} # Admin Check and Prompt Customization $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) @@ -329,7 +351,7 @@ function Get-Theme { return } } else { - oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + oh-my-posh init pwsh --config https://raw.githubusercontent.com/ru-dr/rudr-Theme/refs/heads/main/rudr-theme.omp.json | Invoke-Expression } } @@ -353,89 +375,90 @@ Set-Alias -Name zi -Value __zoxide_zi -Option AllScope -Scope Global -Force # Help Function function Show-Help { - @" -PowerShell Profile Help -======================= + $helpText = @" +$($PSStyle.Foreground.Cyan)PowerShell Profile Help$($PSStyle.Reset) +$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) -Update-Profile - Checks for profile updates from a remote repository and updates if necessary. +$($PSStyle.Foreground.Green)Update-Profile$($PSStyle.Reset) - 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. +$($PSStyle.Foreground.Green)Update-PowerShell$($PSStyle.Reset) - 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. +$($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor. -touch - Creates a new empty file. +$($PSStyle.Foreground.Green)touch$($PSStyle.Reset) - Creates a new empty file. -ff - Finds files recursively with the specified name. +$($PSStyle.Foreground.Green)ff$($PSStyle.Reset) - Finds files recursively with the specified name. -Get-PubIP - Retrieves the public IP address of the machine. +$($PSStyle.Foreground.Green)Get-PubIP$($PSStyle.Reset) - Retrieves the public IP address of the machine. -winutil - Runs the WinUtil script from Chris Titus Tech. +$($PSStyle.Foreground.Green)winutil$($PSStyle.Reset) - Runs the WinUtil script from Chris Titus Tech. -uptime - Displays the system uptime. +$($PSStyle.Foreground.Green)uptime$($PSStyle.Reset) - Displays the system uptime. -reload-profile - Reloads the current user's PowerShell profile. +$($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. -unzip - Extracts a zip file to the current directory. +$($PSStyle.Foreground.Green)unzip$($PSStyle.Reset) - Extracts a zip file to the current directory. -hb - Uploads the specified file's content to a hastebin-like service and returns the URL. +$($PSStyle.Foreground.Green)hb$($PSStyle.Reset) - Uploads the specified file's content to a hastebin-like service and returns the URL. -grep [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input. +$($PSStyle.Foreground.Green)grep$($PSStyle.Reset) [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input. -df - Displays information about volumes. +$($PSStyle.Foreground.Green)df$($PSStyle.Reset) - Displays information about volumes. -sed - Replaces text in a file. +$($PSStyle.Foreground.Green)sed$($PSStyle.Reset) - Replaces text in a file. -which - Shows the path of the command. +$($PSStyle.Foreground.Green)which$($PSStyle.Reset) - Shows the path of the command. -export - Sets an environment variable. +$($PSStyle.Foreground.Green)export$($PSStyle.Reset) - Sets an environment variable. -pkill - Kills processes by name. +$($PSStyle.Foreground.Green)pkill$($PSStyle.Reset) - Kills processes by name. -pgrep - Lists processes by name. +$($PSStyle.Foreground.Green)pgrep$($PSStyle.Reset) - Lists processes by name. -head [n] - Displays the first n lines of a file (default 10). +$($PSStyle.Foreground.Green)head$($PSStyle.Reset) [n] - Displays the first n lines of a file (default 10). -tail [n] - Displays the last n lines of a file (default 10). +$($PSStyle.Foreground.Green)tail$($PSStyle.Reset) [n] - Displays the last n lines of a file (default 10). -nf - Creates a new file with the specified name. +$($PSStyle.Foreground.Green)nf$($PSStyle.Reset) - Creates a new file with the specified name. -mkcd - Creates and changes to a new directory. +$($PSStyle.Foreground.Green)mkcd$($PSStyle.Reset) - Creates and changes to a new directory. -docs - Changes the current directory to the user's Documents folder. +$($PSStyle.Foreground.Green)docs$($PSStyle.Reset) - Changes the current directory to the user's Documents folder. -dtop - Changes the current directory to the user's Desktop folder. +$($PSStyle.Foreground.Green)dtop$($PSStyle.Reset) - Changes the current directory to the user's Desktop folder. -ep - Opens the profile for editing. +$($PSStyle.Foreground.Green)ep$($PSStyle.Reset) - Opens the profile for editing. -k9 - Kills a process by name. +$($PSStyle.Foreground.Green)k9$($PSStyle.Reset) - Kills a process by name. -la - Lists all files in the current directory with detailed formatting. +$($PSStyle.Foreground.Green)la$($PSStyle.Reset) - Lists all files in the current directory with detailed formatting. -ll - Lists all files, including hidden, in the current directory with detailed formatting. +$($PSStyle.Foreground.Green)ll$($PSStyle.Reset) - Lists all files, including hidden, in the current directory with detailed formatting. -gs - Shortcut for 'git status'. +$($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'. -ga - Shortcut for 'git add .'. +$($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. -gc - Shortcut for 'git commit -m'. +$($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. -gp - Shortcut for 'git push'. +$($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'. -g - Changes to the GitHub directory. +$($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. -gcom - Adds all changes and commits with the specified message. +$($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. -lazyg - Adds all changes, commits with the specified message, and pushes to the remote repository. +$($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. -sysinfo - Displays detailed system information. +$($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. -flushdns - Clears the DNS cache. +$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. -cpy - Copies the specified text to the clipboard. +$($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. -pst - Retrieves text from the clipboard. +$($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard. -Use 'Show-Help' to display this help message. +Use '$($PSStyle.Foreground.Magenta)Show-Help$($PSStyle.Reset)' to display this help message. "@ + Write-Host $helpText } -Write-Host "Use 'Show-Help' to display help" +Write-Host "$($PSStyle.Foreground.Yellow)Use 'Show-Help' to display help$($PSStyle.Reset)" From ee7eda0ee2069678753218fa958ac9155a08b25e Mon Sep 17 00:00:00 2001 From: Rudra Patel <77568653+ru-dr@users.noreply.github.com> Date: Mon, 14 Oct 2024 18:50:54 +0530 Subject: [PATCH 19/64] added clear-cache and temp clearing function & colored text in help section --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 29ad6dfc..b9d9c98c 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -351,7 +351,7 @@ function Get-Theme { return } } else { - oh-my-posh init pwsh --config https://raw.githubusercontent.com/ru-dr/rudr-Theme/refs/heads/main/rudr-theme.omp.json | Invoke-Expression + oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression } } From f9feb220b6fd01b158bef254df635830359dff1f Mon Sep 17 00:00:00 2001 From: Rudra Patel <77568653+ru-dr@users.noreply.github.com> Date: Tue, 15 Oct 2024 17:54:47 +0530 Subject: [PATCH 20/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 94 ++++++++++++++++++++++---------- 1 file changed, 66 insertions(+), 28 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index b9d9c98c..f899ba02 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -22,7 +22,7 @@ if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) } # Initial GitHub.com connectivity check with 1 second timeout -$canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 +$global:canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 # Import Modules and External Profiles # Ensure Terminal-Icons module is installed before importing @@ -37,11 +37,6 @@ if (Test-Path($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 @@ -50,21 +45,17 @@ function Update-Profile { 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 + } else { + Write-Host "Profile is up to date." -ForegroundColor Green } } catch { - Write-Error "Unable to check for `$profile updates" + 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 @@ -314,23 +305,70 @@ 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 +# Enhanced PSReadLine Configuration +$PSReadLineOptions = @{ + EditMode = 'Windows' + HistoryNoDuplicates = $true + HistorySearchCursorMovesToEnd = $true + Colors = @{ + Command = '#87CEEB' # SkyBlue (pastel) + Parameter = '#98FB98' # PaleGreen (pastel) + Operator = '#FFB6C1' # LightPink (pastel) + Variable = '#DDA0DD' # Plum (pastel) + String = '#FFDAB9' # PeachPuff (pastel) + Number = '#B0E0E6' # PowderBlue (pastel) + Type = '#F0E68C' # Khaki (pastel) + Comment = '#D3D3D3' # LightGray (pastel) + Keyword = '#8367c7' # Violet (pastel) + Error = '#FF6347' # Tomato (keeping it close to red for visibility) + } + PredictionSource = 'History' + PredictionViewStyle = 'ListView' + BellStyle = 'None' +} +Set-PSReadLineOption @PSReadLineOptions + +# Custom key handlers +Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward +Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward +Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete +Set-PSReadLineKeyHandler -Chord 'Ctrl+d' -Function DeleteChar +Set-PSReadLineKeyHandler -Chord 'Ctrl+w' -Function BackwardDeleteWord +Set-PSReadLineKeyHandler -Chord 'Alt+d' -Function DeleteWord +Set-PSReadLineKeyHandler -Chord 'Ctrl+LeftArrow' -Function BackwardWord +Set-PSReadLineKeyHandler -Chord 'Ctrl+RightArrow' -Function ForwardWord +Set-PSReadLineKeyHandler -Chord 'Ctrl+z' -Function Undo +Set-PSReadLineKeyHandler -Chord 'Ctrl+y' -Function Redo + +# Custom functions for PSReadLine +Set-PSReadLineOption -AddToHistoryHandler { + param($line) + $sensitive = @('password', 'secret', 'token', 'apikey', 'connectionstring') + $hasSensitive = $sensitive | Where-Object { $line -match $_ } + return ($null -eq $hasSensitive) +} + +# Improved prediction settings +Set-PSReadLineOption -PredictionSource HistoryAndPlugin +Set-PSReadLineOption -MaximumHistoryCount 10000 + +# Custom completion for common commands +$scriptblock = { + param($wordToComplete, $commandAst, $cursorPosition) + $customCompletions = @{ + 'git' = @('status', 'add', 'commit', 'push', 'pull', 'clone', 'checkout') + 'npm' = @('install', 'start', 'run', 'test', 'build') + 'deno' = @('run', 'compile', 'bundle', 'test', 'lint', 'fmt', 'cache', 'info', 'doc', 'upgrade') + } + + $command = $commandAst.CommandElements[0].Value + if ($customCompletions.ContainsKey($command)) { + $customCompletions[$command] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } } } -Set-PSReadLineOption @PSROptions -Set-PSReadLineKeyHandler -Chord 'Ctrl+f' -Function ForwardWord -Set-PSReadLineKeyHandler -Chord 'Enter' -Function ValidateAndAcceptLine +Register-ArgumentCompleter -Native -CommandName git, npm, deno -ScriptBlock $scriptblock $scriptblock = { param($wordToComplete, $commandAst, $cursorPosition) From 25c04c6689dabaaf590e05a71522b1e6eeef7306 Mon Sep 17 00:00:00 2001 From: Blazzycrafter <39300111+Blazzycrafter@users.noreply.github.com> Date: Wed, 13 Nov 2024 01:38:04 +0100 Subject: [PATCH 21/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..bf04567b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -148,10 +148,34 @@ function admin { 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 ', '') } + try { + # Überprüfe die PowerShell-Version + if ($PSVersionTable.PSVersion.Major -eq 5) { + $lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime + $bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot) + } else { + $lastBootStr = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } + $bootTime = [System.DateTime]::ParseExact($lastBootStr, "dd.MM.yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + } + + # Formatiere die Startzeit + $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray + + # Berechne die Uptime + $uptime = (Get-Date) - $bootTime + + # Uptime in Tage, Stunden, Minuten und Sekunden aufteilen + $days = $uptime.Days + $hours = $uptime.Hours + $minutes = $uptime.Minutes + $seconds = $uptime.Seconds + + # Uptime ausgeben + Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue + + } catch { + Write-Error "An error occurred while retrieving system uptime." } } From 0bb16adb3e5b848a6d989d2abf6894d085e36f07 Mon Sep 17 00:00:00 2001 From: Blazzycrafter <39300111+Blazzycrafter@users.noreply.github.com> Date: Wed, 13 Nov 2024 01:38:04 +0100 Subject: [PATCH 22/64] Update Microsoft.PowerShell_profile.ps1 updeted the uptime command to show the last startup time AND the UPTIME ... with color :D ![image](https://gist.github.com/user-attachments/assets/b64050c3-e532-4c0b-a0d4-f7075c833c28) Signed-off-by: Blazzycrafter --- Microsoft.PowerShell_profile.ps1 | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..bf04567b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -148,10 +148,34 @@ function admin { 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 ', '') } + try { + # Überprüfe die PowerShell-Version + if ($PSVersionTable.PSVersion.Major -eq 5) { + $lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime + $bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot) + } else { + $lastBootStr = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } + $bootTime = [System.DateTime]::ParseExact($lastBootStr, "dd.MM.yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + } + + # Formatiere die Startzeit + $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray + + # Berechne die Uptime + $uptime = (Get-Date) - $bootTime + + # Uptime in Tage, Stunden, Minuten und Sekunden aufteilen + $days = $uptime.Days + $hours = $uptime.Hours + $minutes = $uptime.Minutes + $seconds = $uptime.Seconds + + # Uptime ausgeben + Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue + + } catch { + Write-Error "An error occurred while retrieving system uptime." } } From 58a75860dcc431b98be1132f533cd71a3ea54de3 Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Wed, 13 Nov 2024 01:56:06 +0100 Subject: [PATCH 23/64] comments translated Signed-off-by: Blazzycrafter --- Microsoft.PowerShell_profile.ps1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bf04567b..26f40c75 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -149,7 +149,7 @@ Set-Alias -Name su -Value admin function uptime { try { - # Überprüfe die PowerShell-Version + # check powershell version if ($PSVersionTable.PSVersion.Major -eq 5) { $lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime $bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot) @@ -158,20 +158,20 @@ function uptime { $bootTime = [System.DateTime]::ParseExact($lastBootStr, "dd.MM.yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) } - # Formatiere die Startzeit + # Format the start time $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray - # Berechne die Uptime + # calculate uptime $uptime = (Get-Date) - $bootTime - # Uptime in Tage, Stunden, Minuten und Sekunden aufteilen + # Uptime in days, hours, minutes, and seconds $days = $uptime.Days $hours = $uptime.Hours $minutes = $uptime.Minutes $seconds = $uptime.Seconds - # Uptime ausgeben + # Uptime output Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue } catch { From e255d2787e443027471db66bc28d635215050579 Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Sun, 24 Nov 2024 17:09:33 +0100 Subject: [PATCH 24/64] added a debug flag to make it simpler to develope on main file while NOT updating (by NOT auto trigger the update functions) --- Microsoft.PowerShell_profile.ps1 | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 26f40c75..a6a2bf15 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -1,6 +1,9 @@ ### PowerShell Profile Refactor ### Version 1.03 - Refactored +$debug = $true + + ################################################################################################################################# ############ ############ ############ !!! WARNING: !!! ############ @@ -57,7 +60,13 @@ function Update-Profile { Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue } } -Update-Profile +# skip in debug mode +if (-not $debug) { + Update-Profile +} else { + Write-Warning "Skipping profile update check in debug mode" +} + function Update-PowerShell { if (-not $global:canConnectToGitHub) { @@ -87,8 +96,12 @@ function Update-PowerShell { Write-Error "Failed to update PowerShell. Error: $_" } } -Update-PowerShell - +# skip in debug mode +if (-not $debug) { + Update-PowerShell +} else { + Write-Warning "Skipping PowerShell update in debug mode" +} # Admin Check and Prompt Customization $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) From 781b40226a7d89b35b6d5ed5e852fb0b52b719fb Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Sun, 24 Nov 2024 17:17:11 +0100 Subject: [PATCH 25/64] implemented: https://github.com/ChrisTitusTech/powershell-profile/pull/120#pullrequestreview-2456739712 --- Microsoft.PowerShell_profile.ps1 | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index a6a2bf15..c07d4841 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -168,11 +168,34 @@ function uptime { $bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot) } else { $lastBootStr = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } + # check date format + if ($lastBootStr -match '^\d{2}/\d{2}/\d{4}') { + $dateFormat = 'dd/MM/yyyy' + } elseif ($lastBootStr -match '^\d{2}-\d{2}-\d{4}') { + $dateFormat = 'dd-MM-yyyy' + } elseif ($lastBootStr -match '^\d{4}/\d{2}/\d{2}') { + $dateFormat = 'yyyy/MM/dd' + } elseif ($lastBootStr -match '^\d{4}-\d{2}-\d{2}') { + $dateFormat = 'yyyy-MM-dd' + } elseif ($lastBootStr -match '^\d{2}\.\d{2}\.\d{4}') { + $dateFormat = 'dd.MM.yyyy' + } + + # check time format + if ($lastBootStr -match '\bAM\b' -or $lastBootStr -match '\bPM\b') { + $timeFormat = 'h:mm:ss tt' + } else { + $timeFormat = 'HH:mm:ss' + } + + $bootTime = [System.DateTime]::ParseExact($lastBootStr, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) + $bootTime = [System.DateTime]::ParseExact($lastBootStr, "dd.MM.yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) } # Format the start time - $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + ### $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + " [$lastBootStr]" Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray # calculate uptime @@ -186,6 +209,7 @@ function uptime { # Uptime output Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue + } catch { Write-Error "An error occurred while retrieving system uptime." From 79294ce809c854aea44d9ef245eea96515b95c20 Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Sun, 24 Nov 2024 17:17:40 +0100 Subject: [PATCH 26/64] disabled debug mode --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c07d4841..9bbbe956 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -1,7 +1,7 @@ ### PowerShell Profile Refactor ### Version 1.03 - Refactored -$debug = $true +$debug = $false ################################################################################################################################# From 98f78d1c2d6466f88dad727d1358d745dbc97c8c Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Sun, 24 Nov 2024 17:29:48 +0100 Subject: [PATCH 27/64] Added debug message --- Microsoft.PowerShell_profile.ps1 | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 9bbbe956..7e9ae1e0 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -3,6 +3,19 @@ $debug = $false +if ($debug) { + Write-Host "#######################################" -ForegroundColor Red + Write-Host "# Debug mode enabled #" -ForegroundColor Red + Write-Host "# ONLY FOR DEVELOPMENT #" -ForegroundColor Red + Write-Host "# #" -ForegroundColor Red + Write-Host "# IF YOU ARE NOT DEVELOPING #" -ForegroundColor Red + Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red + Write-Host "# to discard all changes #" -ForegroundColor Red + Write-Host "# and update to the latest profile #" -ForegroundColor Red + Write-Host "# version #" -ForegroundColor Red + Write-Host "#######################################" -ForegroundColor Red +} + ################################################################################################################################# ############ ############ From 6f35074ae8fd688026b39344280f18accd291298 Mon Sep 17 00:00:00 2001 From: Blazzycrafter Date: Sun, 24 Nov 2024 18:09:07 +0100 Subject: [PATCH 28/64] Merge branch 'main' of https://github.com/Blazzycrafter/powershell-profile # Conflicts: # Microsoft.PowerShell_profile.ps1 FIX! --- Microsoft.PowerShell_profile.ps1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 7e9ae1e0..cc6ae73b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -202,8 +202,6 @@ function uptime { } $bootTime = [System.DateTime]::ParseExact($lastBootStr, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) - - $bootTime = [System.DateTime]::ParseExact($lastBootStr, "dd.MM.yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) } # Format the start time From 4b37a4baea92fe7810fa6745862a79130922c483 Mon Sep 17 00:00:00 2001 From: StudentSerai1181201811 <60701306+StudentSerai1181201811@users.noreply.github.com> Date: Mon, 25 Nov 2024 21:13:54 +0800 Subject: [PATCH 29/64] Fix admin elevation arguments When using admin such as `admin ls`, it works fine. However, if passing in multiple arguments such as `admin sfc /scannow`, it doesn't work. This pull request should fix this. --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 8ad754bc..ba3119c8 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -137,7 +137,7 @@ function winutil { # System Utilities function admin { if ($args.Count -gt 0) { - $argList = "& '$args'" + $argList = $args -join ' ' Start-Process wt -Verb runAs -ArgumentList "pwsh.exe -NoExit -Command $argList" } else { Start-Process wt -Verb runAs From 0640373cec48a32c9bb510730a34c6e121b077b3 Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Mon, 25 Nov 2024 15:07:47 -0600 Subject: [PATCH 30/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 6a41eca7..238fc8bf 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -92,7 +92,7 @@ function Update-PowerShell { if ($updateNeeded) { Write-Host "Updating PowerShell..." -ForegroundColor Yellow - winget upgrade "Microsoft.PowerShell" --accept-source-agreements --accept-package-agreements + Start-Process powershell.exe -ArgumentList "-NoProfile -Command winget upgrade Microsoft.PowerShell --accept-source-agreements --accept-package-agreements" -Wait -NoNewWindow 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 From c3aba5722349d6558a64b1ec1413628eab92f69d Mon Sep 17 00:00:00 2001 From: Anirudh Gupta Date: Fri, 17 Jan 2025 14:02:14 +0530 Subject: [PATCH 31/64] profile: Run update check every 7 days Signed-off-by: Anirudh Gupta --- Microsoft.PowerShell_profile.ps1 | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 238fc8bf..80fe4ebb 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -3,6 +3,12 @@ $debug = $false +# Define the path to the file that stores the last execution time +$timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" + +# Define the update interval in days +$updateInterval = 7 + if ($debug) { Write-Host "#######################################" -ForegroundColor Red Write-Host "# Debug mode enabled #" -ForegroundColor Red @@ -72,8 +78,12 @@ function Update-Profile { } # skip in debug mode -if (-not $debug) { +if (-not $debug -and ((-not (Test-Path $timeFilePath)) -or ((Get-Date) - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd HH:mm:ss', $null)).TotalDays -gt $updateInterval)) { Update-Profile + $currentTime = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' + $currentTime | Out-File -FilePath $timeFilePath +} elseif (-not $debug) { + Write-Warning "Profile update skipped. Last update was within the last 7 days." } else { Write-Warning "Skipping profile update check in debug mode" } From 3001e51adce25b74ed9591c2add90536776fb7a3 Mon Sep 17 00:00:00 2001 From: Anirudh Gupta Date: Fri, 17 Jan 2025 14:47:38 +0530 Subject: [PATCH 32/64] profile: Add a -1 condition to always check for update + set time format to only include date Signed-off-by: Anirudh Gupta --- Microsoft.PowerShell_profile.ps1 | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 80fe4ebb..c2c57a42 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -6,7 +6,7 @@ $debug = $false # Define the path to the file that stores the last execution time $timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" -# Define the update interval in days +# Define the update interval in days, set to -1 to always check $updateInterval = 7 if ($debug) { @@ -77,13 +77,18 @@ function Update-Profile { } } -# skip in debug mode -if (-not $debug -and ((-not (Test-Path $timeFilePath)) -or ((Get-Date) - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd HH:mm:ss', $null)).TotalDays -gt $updateInterval)) { +# Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval) +if (-not $debug -and ` + ($updateInterval -eq -1 -or ` + -not (Test-Path $timeFilePath) -or ` + ((Get-Date) - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd', $null)).TotalDays -gt $updateInterval)) { + Update-Profile - $currentTime = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' + $currentTime = Get-Date -Format 'yyyy-MM-dd' $currentTime | Out-File -FilePath $timeFilePath + } elseif (-not $debug) { - Write-Warning "Profile update skipped. Last update was within the last 7 days." + Write-Warning "Profile update skipped. Last update check was within the last $updateInterval day(s)." } else { Write-Warning "Skipping profile update check in debug mode" } @@ -113,8 +118,17 @@ function Update-PowerShell { } # skip in debug mode -if (-not $debug) { +# Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval) +if (-not $debug -and ` + ($updateInterval -eq -1 -or ` + -not (Test-Path $timeFilePath) -or ` + ((Get-Date).Date - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd', $null).Date).TotalDays -gt $updateInterval)) { + Update-PowerShell + $currentTime = Get-Date -Format 'yyyy-MM-dd' + $currentTime | Out-File -FilePath $timeFilePath +} elseif (-not $debug) { + Write-Warning "PowerShell update skipped. Last update check was within the last $updateInterval day(s)." } else { Write-Warning "Skipping PowerShell update in debug mode" } From c53d3ced01c86fea0777d92369b4d6b4c071967a Mon Sep 17 00:00:00 2001 From: Joseph Hanson Date: Mon, 3 Feb 2025 12:42:42 -0600 Subject: [PATCH 33/64] Removed warning when update is skipped. --- Microsoft.PowerShell_profile.ps1 | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c2c57a42..ed5dcfb6 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -87,9 +87,7 @@ if (-not $debug -and ` $currentTime = Get-Date -Format 'yyyy-MM-dd' $currentTime | Out-File -FilePath $timeFilePath -} elseif (-not $debug) { - Write-Warning "Profile update skipped. Last update check was within the last $updateInterval day(s)." -} else { +} elseif ($debug) { Write-Warning "Skipping profile update check in debug mode" } @@ -127,9 +125,7 @@ if (-not $debug -and ` Update-PowerShell $currentTime = Get-Date -Format 'yyyy-MM-dd' $currentTime | Out-File -FilePath $timeFilePath -} elseif (-not $debug) { - Write-Warning "PowerShell update skipped. Last update check was within the last $updateInterval day(s)." -} else { +} elseif ($debug) { Write-Warning "Skipping PowerShell update in debug mode" } From 0e7931a1e7242ec4b3528d02143c03b96ba088fa Mon Sep 17 00:00:00 2001 From: jlcs-dev Date: Sun, 9 Feb 2025 22:35:14 +0100 Subject: [PATCH 34/64] Replacing USERPROFILE env with Env GetFolderPath(MyDocuments) --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c2c57a42..f451ec86 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -4,7 +4,7 @@ $debug = $false # Define the path to the file that stores the last execution time -$timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" +$timeFilePath = [Environment]::GetFolderPath("MyDocuments") + "\PowerShell\LastExecutionTime.txt" # Define the update interval in days, set to -1 to always check $updateInterval = 7 From d9cef5096782e097fada4695e147240a24eb41ba Mon Sep 17 00:00:00 2001 From: Zac Morris Date: Mon, 10 Feb 2025 13:44:25 -0800 Subject: [PATCH 35/64] Update Microsoft.PowerShell_profile.ps1 Added code to implement VARIABLE and FUNCTION overrides in profile.ps1. Also modified Show-Help to sort in alphabetical order by category [Patch2 changes and overzealous find/replace in custom-key-handlers --- Microsoft.PowerShell_profile.ps1 | 379 ++++++++++++++++++------------- 1 file changed, 219 insertions(+), 160 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c2c57a42..489ec6d2 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -1,28 +1,3 @@ -### PowerShell Profile Refactor -### Version 1.03 - Refactored - -$debug = $false - -# Define the path to the file that stores the last execution time -$timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" - -# Define the update interval in days, set to -1 to always check -$updateInterval = 7 - -if ($debug) { - Write-Host "#######################################" -ForegroundColor Red - Write-Host "# Debug mode enabled #" -ForegroundColor Red - Write-Host "# ONLY FOR DEVELOPMENT #" -ForegroundColor Red - Write-Host "# #" -ForegroundColor Red - Write-Host "# IF YOU ARE NOT DEVELOPING #" -ForegroundColor Red - Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red - Write-Host "# to discard all changes #" -ForegroundColor Red - Write-Host "# and update to the latest profile #" -ForegroundColor Red - Write-Host "# version #" -ForegroundColor Red - Write-Host "#######################################" -ForegroundColor Red -} - - ################################################################################################################################# ############ ############ ############ !!! WARNING: !!! ############ @@ -33,11 +8,90 @@ if ($debug) { ############ ############ #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!# ############ ############ -############ IF YOU WANT TO MAKE CHANGES, USE THE Edit-Profile FUNCTION ############ -############ AND SAVE YOUR CHANGES IN THE FILE CREATED. ############ +############ TO ADD YOUR OWN CODE OR IF YOU WANT TO OVERRIDE ANY OF THESE VARIABLES ############ +############ OR FUNCTIONS. USE THE Edit-Profile FUNCTION TO CREATE YOUR OWN profile.ps1 FILE. ############ +############ TO OVERRIDE IN YOUR NEW profile.ps1 FILE, REWRITE THE VARIABLE ############ +############ OR FUNCTION, ADDING "_Override" TO THE NAME. ############ +############ ############ +############ THE FOLLOWING VARIABLES RESPECT _Override: ############ +############ $EDITOR_Override ############ +############ $debug_Override ############ +############ $repo_root_Override [To point to a fork, for example] ############ +############ $timeFilePath_Override ############ +############ $updateInterval_Override ############ +############ ############ +############ THE FOLLOWING FUNCTIONS RESPECT _Override: ############ +############ Debug-Message_Override ############ +############ Update-Profile_Override ############ +############ Update-PowerShell_Override ############ +############ Clear-Cache_Override ############ +############ Get-Theme_Override ############ +############ WinUtilDev_Override [To call a fork, for example] ############ ############ ############ ################################################################################################################################# +### PowerShell Profile Refactor +### Version 1.04 - Refactored + +if ($debug_Override){ + # If variable debug_Override is defined in profile.ps1 file + # then use it instead + $debug = $debug_Override +} else { + $debug = $false +} + +# Define the path to the file that stores the last execution time +if ($repo_root_Override){ + # If variable $repo_root_Override is defined in profile.ps1 file + # then use it instead + $repo_root = $repo_root_Override +} else { + $repo_root = "https://raw.githubusercontent.com/ChrisTitusTech" +} + +# Define the path to the file that stores the last execution time +if ($timeFilePath_Override){ + # If variable $timeFilePath_Override is defined in profile.ps1 file + # then use it instead + $timeFilePath = $timeFilePath_Override +} else { + $timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" +} + +# Define the update interval in days, set to -1 to always check +if ($updateInterval_Override){ + # If variable $updateInterval_Override is defined in profile.ps1 file + # then use it instead + $updateInterval = $updateInterval_Override +} else { + $updateInterval = 7 +} + +function Debug-Message{ + # If function "Debug-Message_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "Debug-Message_Override" -ErrorAction SilentlyContinue) { + Debug-Message_Override + } else { + Write-Host "#######################################" -ForegroundColor Red + Write-Host "# Debug mode enabled #" -ForegroundColor Red + Write-Host "# ONLY FOR DEVELOPMENT #" -ForegroundColor Red + Write-Host "# #" -ForegroundColor Red + Write-Host "# IF YOU ARE NOT DEVELOPING #" -ForegroundColor Red + Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red + Write-Host "# to discard all changes #" -ForegroundColor Red + Write-Host "# and update to the latest profile #" -ForegroundColor Red + Write-Host "# version #" -ForegroundColor Red + Write-Host "#######################################" -ForegroundColor Red + } +} + +if ($debug) { + DebugMessage +} + + #opt-out of telemetry before doing anything, only if PowerShell is run as admin if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) { [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) @@ -59,21 +113,27 @@ if (Test-Path($ChocolateyProfile)) { # Check for Profile Updates function Update-Profile { - 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 - } else { - Write-Host "Profile is up to date." -ForegroundColor Green + # If function "Update-Profile_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "Update-Profile_Override" -ErrorAction SilentlyContinue) { + Update-Profile_Override; + } else { + try { + $url = "$repo_root/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 + } else { + Write-Host "Profile is up to date." -ForegroundColor Green + } + } catch { + Write-Error "Unable to check for `$profile updates: $_" + } finally { + Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue } - } catch { - Write-Error "Unable to check for `$profile updates: $_" - } finally { - Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue } } @@ -94,26 +154,32 @@ if (-not $debug -and ` } function Update-PowerShell { - 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 function "Update-PowerShell_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "Update-PowerShell_Override" -ErrorAction SilentlyContinue) { + Update-PowerShell_Override; + } else { + 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 - Start-Process powershell.exe -ArgumentList "-NoProfile -Command winget upgrade Microsoft.PowerShell --accept-source-agreements --accept-package-agreements" -Wait -NoNewWindow - 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 + if ($updateNeeded) { + Write-Host "Updating PowerShell..." -ForegroundColor Yellow + Start-Process powershell.exe -ArgumentList "-NoProfile -Command winget upgrade Microsoft.PowerShell --accept-source-agreements --accept-package-agreements" -Wait -NoNewWindow + 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: $_" } - } catch { - Write-Error "Failed to update PowerShell. Error: $_" } } @@ -134,26 +200,36 @@ if (-not $debug -and ` } function Clear-Cache { - # add clear cache logic here - Write-Host "Clearing cache..." -ForegroundColor Cyan + # If function "Clear-Cache_Override" is defined in profile.ps1 file + # then call it instead. + # ----------------------------------------------------------------- + # If you do override this function, you should should probably duplicate + # the following calls in your override function, just don't call this + # function from your override function, otherwise you'll be in an infinate loop. + if (Get-Command -Name "Clear-Cache_Override" -ErrorAction SilentlyContinue) { + Clear-Cache_Override + } else { + # add clear cache logic here + Write-Host "Clearing cache..." -ForegroundColor Cyan - # Clear Windows Prefetch - Write-Host "Clearing Windows Prefetch..." -ForegroundColor Yellow - Remove-Item -Path "$env:SystemRoot\Prefetch\*" -Force -ErrorAction SilentlyContinue + # Clear Windows Prefetch + Write-Host "Clearing Windows Prefetch..." -ForegroundColor Yellow + Remove-Item -Path "$env:SystemRoot\Prefetch\*" -Force -ErrorAction SilentlyContinue - # Clear Windows Temp - Write-Host "Clearing Windows Temp..." -ForegroundColor Yellow - Remove-Item -Path "$env:SystemRoot\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue + # Clear Windows Temp + Write-Host "Clearing Windows Temp..." -ForegroundColor Yellow + Remove-Item -Path "$env:SystemRoot\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue - # Clear User Temp - Write-Host "Clearing User Temp..." -ForegroundColor Yellow - Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue + # Clear User Temp + Write-Host "Clearing User Temp..." -ForegroundColor Yellow + Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue - # Clear Internet Explorer Cache - Write-Host "Clearing Internet Explorer Cache..." -ForegroundColor Yellow - Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\Windows\INetCache\*" -Recurse -Force -ErrorAction SilentlyContinue + # Clear Internet Explorer Cache + Write-Host "Clearing Internet Explorer Cache..." -ForegroundColor Yellow + Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\Windows\INetCache\*" -Recurse -Force -ErrorAction SilentlyContinue - Write-Host "Cache clearing completed." -ForegroundColor Green + Write-Host "Cache clearing completed." -ForegroundColor Green + } } # Admin Check and Prompt Customization @@ -172,14 +248,18 @@ function Test-CommandExists { } # 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' } +if ($EDITOR_Override){ + $EDITOR = $EDITOR_Override +} else { + $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 # Quick Access to Editing the Profile @@ -200,12 +280,18 @@ function Get-PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content } # Open WinUtil full-release function winutil { - irm https://christitus.com/win | iex + irm https://christitus.com/win | iex } -# Open WinUtil pre-release +# Open WinUtil dev-release function winutildev { - irm https://christitus.com/windev | iex + # If function "WinUtilDev_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "WinUtilDev_Override" -ErrorAction SilentlyContinue) { + WinUtilDev_Override + } else { + irm https://christitus.com/windev | iex + } } # System Utilities @@ -521,15 +607,21 @@ 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 - } - oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + # If function "Get-Theme_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue) { + Get-Theme_Override } else { - oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + 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 + } + oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + } else { + oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + } } } @@ -556,86 +648,53 @@ function Show-Help { $helpText = @" $($PSStyle.Foreground.Cyan)PowerShell Profile Help$($PSStyle.Reset) $($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) - $($PSStyle.Foreground.Green)Update-Profile$($PSStyle.Reset) - Checks for profile updates from a remote repository and updates if necessary. - $($PSStyle.Foreground.Green)Update-PowerShell$($PSStyle.Reset) - Checks for the latest PowerShell release and updates if a new version is available. - $($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor. -$($PSStyle.Foreground.Green)touch$($PSStyle.Reset) - Creates a new empty file. - -$($PSStyle.Foreground.Green)ff$($PSStyle.Reset) - Finds files recursively with the specified name. - -$($PSStyle.Foreground.Green)Get-PubIP$($PSStyle.Reset) - Retrieves the public IP address of the machine. - -$($PSStyle.Foreground.Green)winutil$($PSStyle.Reset) - Runs the latest WinUtil full-release script from Chris Titus Tech. - -$($PSStyle.Foreground.Green)winutildev$($PSStyle.Reset) - Runs the latest WinUtil pre-release script from Chris Titus Tech. - -$($PSStyle.Foreground.Green)uptime$($PSStyle.Reset) - Displays the system uptime. - -$($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. - -$($PSStyle.Foreground.Green)unzip$($PSStyle.Reset) - Extracts a zip file to the current directory. - -$($PSStyle.Foreground.Green)hb$($PSStyle.Reset) - Uploads the specified file's content to a hastebin-like service and returns the URL. - -$($PSStyle.Foreground.Green)grep$($PSStyle.Reset) [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input. +$($PSStyle.Foreground.Cyan)Git Shortcuts$($PSStyle.Reset) +$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) +$($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. +$($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. +$($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. +$($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. +$($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'. +$($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'. +$($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. +$($PSStyle.Foreground.Cyan)Shortcuts$($PSStyle.Reset) +$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) +$($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. $($PSStyle.Foreground.Green)df$($PSStyle.Reset) - Displays information about volumes. - -$($PSStyle.Foreground.Green)sed$($PSStyle.Reset) - Replaces text in a file. - -$($PSStyle.Foreground.Green)which$($PSStyle.Reset) - Shows the path of the command. - -$($PSStyle.Foreground.Green)export$($PSStyle.Reset) - Sets an environment variable. - -$($PSStyle.Foreground.Green)pkill$($PSStyle.Reset) - Kills processes by name. - -$($PSStyle.Foreground.Green)pgrep$($PSStyle.Reset) - Lists processes by name. - -$($PSStyle.Foreground.Green)head$($PSStyle.Reset) [n] - Displays the first n lines of a file (default 10). - -$($PSStyle.Foreground.Green)tail$($PSStyle.Reset) [n] - Displays the last n lines of a file (default 10). - -$($PSStyle.Foreground.Green)nf$($PSStyle.Reset) - Creates a new file with the specified name. - -$($PSStyle.Foreground.Green)mkcd$($PSStyle.Reset) - Creates and changes to a new directory. - $($PSStyle.Foreground.Green)docs$($PSStyle.Reset) - Changes the current directory to the user's Documents folder. - $($PSStyle.Foreground.Green)dtop$($PSStyle.Reset) - Changes the current directory to the user's Desktop folder. - $($PSStyle.Foreground.Green)ep$($PSStyle.Reset) - Opens the profile for editing. - +$($PSStyle.Foreground.Green)export$($PSStyle.Reset) - Sets an environment variable. +$($PSStyle.Foreground.Green)ff$($PSStyle.Reset) - Finds files recursively with the specified name. +$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. +$($PSStyle.Foreground.Green)Get-PubIP$($PSStyle.Reset) - Retrieves the public IP address of the machine. +$($PSStyle.Foreground.Green)grep$($PSStyle.Reset) [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input. +$($PSStyle.Foreground.Green)hb$($PSStyle.Reset) - Uploads the specified file's content to a hastebin-like service and returns the URL. +$($PSStyle.Foreground.Green)head$($PSStyle.Reset) [n] - Displays the first n lines of a file (default 10). $($PSStyle.Foreground.Green)k9$($PSStyle.Reset) - Kills a process by name. - $($PSStyle.Foreground.Green)la$($PSStyle.Reset) - Lists all files in the current directory with detailed formatting. - $($PSStyle.Foreground.Green)ll$($PSStyle.Reset) - Lists all files, including hidden, in the current directory with detailed formatting. - -$($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'. - -$($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. - -$($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. - -$($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'. - -$($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. - -$($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. - -$($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. - -$($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. - -$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. - -$($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. - +$($PSStyle.Foreground.Green)mkcd$($PSStyle.Reset) - Creates and changes to a new directory. +$($PSStyle.Foreground.Green)nf$($PSStyle.Reset) - Creates a new file with the specified name. +$($PSStyle.Foreground.Green)pgrep$($PSStyle.Reset) - Lists processes by name. +$($PSStyle.Foreground.Green)pkill$($PSStyle.Reset) - Kills processes by name. $($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard. +$($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. +$($PSStyle.Foreground.Green)sed$($PSStyle.Reset) - Replaces text in a file. +$($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. +$($PSStyle.Foreground.Green)tail$($PSStyle.Reset) [n] - Displays the last n lines of a file (default 10). +$($PSStyle.Foreground.Green)touch$($PSStyle.Reset) - Creates a new empty file. +$($PSStyle.Foreground.Green)unzip$($PSStyle.Reset) - Extracts a zip file to the current directory. +$($PSStyle.Foreground.Green)uptime$($PSStyle.Reset) - Displays the system uptime. +$($PSStyle.Foreground.Green)which$($PSStyle.Reset) - Shows the path of the command. +$($PSStyle.Foreground.Green)winutil$($PSStyle.Reset) - Runs the latest WinUtil full-release script from Chris Titus Tech. +$($PSStyle.Foreground.Green)winutildev$($PSStyle.Reset) - Runs the latest WinUtil pre-release script from Chris Titus Tech. +$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) Use '$($PSStyle.Foreground.Magenta)Show-Help$($PSStyle.Reset)' to display this help message. "@ From 09d972772bcc8f4ffb93703951cd3593bc494869 Mon Sep 17 00:00:00 2001 From: Zac Morris Date: Mon, 10 Feb 2025 14:07:36 -0800 Subject: [PATCH 36/64] Update README.md I added the instructions for the Variable/Function overrides vis profile.ps1 --- README.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6c33cfcf..89860237 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,23 @@ PS> oh-my-posh font install **Do not make any changes to the `Microsoft.PowerShell_profile.ps1` file**, since it's hashed and automatically overwritten by any commits to this repository. -After the profile is installed and active, run the `Edit-Profile` function to create a separate profile file for your current user. Make any changes and customizations in this new file named `profile.ps1`. +After the profile is installed and active, run the `Edit-Profile` function to create a separate profile file [`profile.ps1`] for your current user. Add any custom code, and/or override VARIABLES/FUNCTIONS in `Microsoft.PowerShell_profile.ps1` by adding any of the following Variable or Function names: -Now, enjoy your enhanced and stylish PowerShell experience! 🚀 +THE FOLLOWING VARIABLES RESPECT _Override: +
+$EDITOR_Override
+$debug_Override
+$repo_root_Override  [To point to a fork, for example]
+$timeFilePath_Override
+$updateInterval_Override
+
+ +THE FOLLOWING FUNCTIONS RESPECT _Override: _(do not call the original function from your override function, or you'll create an infinite loop)_ +
+Debug-Message_Override
+Update-Profile_Override
+Update-PowerShell_Override
+Clear-Cache_Override
+Get-Theme_Override
+WinUtilDev_Override [To call a fork, for example]
+
From 5bdb4f4d32037154179d3ea4f95e2489679a37a9 Mon Sep 17 00:00:00 2001 From: Zac Morris Date: Tue, 11 Feb 2025 06:42:18 -0800 Subject: [PATCH 37/64] Small fix of line 91 Forgot a dash in the Debug-Message call on line 91. --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 489ec6d2..e0a6d890 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -88,7 +88,7 @@ function Debug-Message{ } if ($debug) { - DebugMessage + Debug-Message } From 9a6d8dd18f88ffbbb67754e56b4e942d0073f00d Mon Sep 17 00:00:00 2001 From: Zac Morris Date: Tue, 18 Feb 2025 14:38:22 -0800 Subject: [PATCH 38/64] Roll Set-PSReadlineOption -PredictionSource into a function, so that it can be override via profile.ps1 Added logic to roll the Set-PSReadlineOption -PredictionSource lines into a function called Set-PredictionSource so that it can be overridden via _Override logic; also added this to the list of functions that respect _Override --- Microsoft.PowerShell_profile.ps1 | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index e0a6d890..c6d4d815 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -27,7 +27,7 @@ ############ Clear-Cache_Override ############ ############ Get-Theme_Override ############ ############ WinUtilDev_Override [To call a fork, for example] ############ -############ ############ +############ Set-PredictionSource ############ ################################################################################################################################# ### PowerShell Profile Refactor @@ -573,9 +573,18 @@ Set-PSReadLineOption -AddToHistoryHandler { return ($null -eq $hasSensitive) } -# Improved prediction settings -Set-PSReadLineOption -PredictionSource HistoryAndPlugin -Set-PSReadLineOption -MaximumHistoryCount 10000 +function Set-PredictionSource { + # If function "Set-PredictionSource_Override" is defined in profile.ps1 file + # then call it instead. + if (Get-Command -Name "Set-PredictionSource_Override" -ErrorAction SilentlyContinue) { + Set-PredictionSource_Override; + } else { + # Improved prediction settings + Set-PSReadLineOption -PredictionSource HistoryAndPlugin + Set-PSReadLineOption -MaximumHistoryCount 10000 + } +} +Set-PredictionSource # Custom completion for common commands $scriptblock = { From 1b8c0ae2f5c067a4ee8250957c6f9bf6fc08af53 Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Fri, 28 Feb 2025 15:44:44 -0600 Subject: [PATCH 39/64] mit yo --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..03a5d53f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Chris Titus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From e626fb8695fc2e21286a591293d26ed31b8e0d8e Mon Sep 17 00:00:00 2001 From: StudentSerai1181201811 <60701306+StudentSerai1181201811@users.noreply.github.com> Date: Sat, 8 Mar 2025 19:07:39 +0800 Subject: [PATCH 40/64] Update Microsoft.PowerShell_profile.ps1 Simplified datetime format checking, fixes for when day or month is not double digits, fixed powershell 5 formatting --- Microsoft.PowerShell_profile.ps1 | 35 +++++++++----------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c2c57a42..0b6efb41 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -223,38 +223,24 @@ Set-Alias -Name su -Value admin function uptime { try { + # find date/time format + $dateFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.ShortDatePattern + $timeFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.LongTimePattern + # check powershell version if ($PSVersionTable.PSVersion.Major -eq 5) { $lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime $bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot) + + # reformat lastBoot + $lastBoot = $bootTime.ToString("$dateFormat $timeFormat") } else { - $lastBootStr = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } - # check date format - if ($lastBootStr -match '^\d{2}/\d{2}/\d{4}') { - $dateFormat = 'dd/MM/yyyy' - } elseif ($lastBootStr -match '^\d{2}-\d{2}-\d{4}') { - $dateFormat = 'dd-MM-yyyy' - } elseif ($lastBootStr -match '^\d{4}/\d{2}/\d{2}') { - $dateFormat = 'yyyy/MM/dd' - } elseif ($lastBootStr -match '^\d{4}-\d{2}-\d{2}') { - $dateFormat = 'yyyy-MM-dd' - } elseif ($lastBootStr -match '^\d{2}\.\d{2}\.\d{4}') { - $dateFormat = 'dd.MM.yyyy' - } - - # check time format - if ($lastBootStr -match '\bAM\b' -or $lastBootStr -match '\bPM\b') { - $timeFormat = 'h:mm:ss tt' - } else { - $timeFormat = 'HH:mm:ss' - } - - $bootTime = [System.DateTime]::ParseExact($lastBootStr, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) + $lastBoot = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } + $bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) } # Format the start time - ### $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) - $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + " [$lastBootStr]" + $formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + " [$lastBoot]" Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray # calculate uptime @@ -268,7 +254,6 @@ function uptime { # Uptime output Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue - } catch { Write-Error "An error occurred while retrieving system uptime." From d9f7acbe407bb1e429c781cde7a43dcf32b16b38 Mon Sep 17 00:00:00 2001 From: Victor Moraes Date: Wed, 9 Apr 2025 07:45:52 -0300 Subject: [PATCH 41/64] profile: fix `la` and `ll` functions so they do what the help says --- Microsoft.PowerShell_profile.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index c2c57a42..215b74aa 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -403,8 +403,8 @@ function dtop { 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 } +function la { Get-ChildItem | Format-Table -AutoSize } +function ll { Get-ChildItem -Force | Format-Table -AutoSize } # Git Shortcuts function gs { git status } From 53369df75950cf3eb46f4f924d6247ad74903d4f Mon Sep 17 00:00:00 2001 From: Marco Marigo Date: Fri, 18 Apr 2025 11:49:21 +0200 Subject: [PATCH 42/64] Replaced the use of the command "net statistics workstation ..." with "Get-Uptime" available since PowerShell ver. 6. The reason is that the output of the command "net statistics" depends on the language of the operating system and it is not possible to execute: net statistics workstation | Select-String "since" ... In Italy for example the output of the command is for example: ... Statistiche dal 18/04/2025 08:48:09 ... --- Microsoft.PowerShell_profile.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 4c0de8ce..59f41011 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -231,7 +231,8 @@ function uptime { # reformat lastBoot $lastBoot = $bootTime.ToString("$dateFormat $timeFormat") } else { - $lastBoot = net statistics workstation | Select-String "since" | ForEach-Object { $_.ToString().Replace('Statistics since ', '') } + # the Get-Uptime cmdlet was introduced in PowerShell 6.0 + $lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat") $bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) } From e1473e43a73dc7686cd4dfdfc432fec81b2b7bec Mon Sep 17 00:00:00 2001 From: Me Date: Fri, 18 Apr 2025 11:56:29 +0200 Subject: [PATCH 43/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 59f41011..a3709383 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -231,7 +231,7 @@ function uptime { # reformat lastBoot $lastBoot = $bootTime.ToString("$dateFormat $timeFormat") } else { - # the Get-Uptime cmdlet was introduced in PowerShell 6.0 + # the Get-Uptime cmdlet was introduced in PowerShell 6.0 $lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat") $bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) } From 7af66114da8f39557b7e0722b1e3498036c9851b Mon Sep 17 00:00:00 2001 From: Marco Marigo Date: Fri, 18 Apr 2025 12:01:14 +0200 Subject: [PATCH 44/64] change comment --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index a3709383..19846ef0 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -231,7 +231,7 @@ function uptime { # reformat lastBoot $lastBoot = $bootTime.ToString("$dateFormat $timeFormat") } else { - # the Get-Uptime cmdlet was introduced in PowerShell 6.0 + # the Get-Uptime cmdlet was introduced in PowerShell 6.0 $lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat") $bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) } From ec1bc5ef17703d94a03c925576e54fa9e56a964b Mon Sep 17 00:00:00 2001 From: Favian Rizqulloh <48427319+favianrizqulloh@users.noreply.github.com> Date: Tue, 3 Jun 2025 21:03:45 +0700 Subject: [PATCH 45/64] Add VSCodium to the list of editors --- Microsoft.PowerShell_profile.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 4c0de8ce..259e5af0 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -173,6 +173,7 @@ $EDITOR = if (Test-CommandExists nvim) { 'nvim' } elseif (Test-CommandExists vim) { 'vim' } elseif (Test-CommandExists vi) { 'vi' } elseif (Test-CommandExists code) { 'code' } + elseif (Test-CommandExists codium) { 'codium' } elseif (Test-CommandExists notepad++) { 'notepad++' } elseif (Test-CommandExists sublime_text) { 'sublime_text' } else { 'notepad' } From d8a19b4e1d70a24e9e9a9bf01f2119f712828455 Mon Sep 17 00:00:00 2001 From: Fahim Ahmed Date: Tue, 17 Jun 2025 16:04:40 +0600 Subject: [PATCH 46/64] fix: suppress output of internet connectivity test in Test-InternetConnection function --- setup.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.ps1 b/setup.ps1 index 1a835a28..43c752cc 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -7,7 +7,7 @@ if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdenti # Function to test internet connectivity function Test-InternetConnection { try { - $testConnection = Test-Connection -ComputerName www.google.com -Count 1 -ErrorAction Stop + Test-Connection -ComputerName www.google.com -Count 1 -ErrorAction Stop | Out-Null return $true } catch { From a5ae089c3ebde984270d97d8cc1c8f0a2ecc130c Mon Sep 17 00:00:00 2001 From: Fahim Ahmed Date: Tue, 17 Jun 2025 16:07:00 +0600 Subject: [PATCH 47/64] fix: adjust spacing in warning message for clarity --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 4c0de8ce..0feb46b9 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -15,7 +15,7 @@ if ($debug) { Write-Host "# ONLY FOR DEVELOPMENT #" -ForegroundColor Red Write-Host "# #" -ForegroundColor Red Write-Host "# IF YOU ARE NOT DEVELOPING #" -ForegroundColor Red - Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red + Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red Write-Host "# to discard all changes #" -ForegroundColor Red Write-Host "# and update to the latest profile #" -ForegroundColor Red Write-Host "# version #" -ForegroundColor Red From 8bdfe44652c68887c8da2a39e15a009507b78eff Mon Sep 17 00:00:00 2001 From: Fahim Ahmed Date: Tue, 17 Jun 2025 16:22:53 +0600 Subject: [PATCH 48/64] fix: enhance clipboard output message for clarity --- Microsoft.PowerShell_profile.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 0feb46b9..a6fe2630 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -285,8 +285,8 @@ function hb { $response = Invoke-RestMethod -Uri $uri -Method Post -Body $Content -ErrorAction Stop $hasteKey = $response.key $url = "http://bin.christitus.com/$hasteKey" - Set-Clipboard $url - Write-Output $url + Set-Clipboard $url + Write-Output "$url copied to clipboard." } catch { Write-Error "Failed to upload the document. Error: $_" } From 1295ff8e4c8dc010aabf517f1aa3d60b0a38e0ef Mon Sep 17 00:00:00 2001 From: Fahim Ahmed Date: Tue, 17 Jun 2025 16:28:59 +0600 Subject: [PATCH 49/64] fix: remove unnecessary zoxide alias definitions --- Microsoft.PowerShell_profile.ps1 | 3 --- 1 file changed, 3 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index a6fe2630..fc027355 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -529,9 +529,6 @@ if (Get-Command zoxide -ErrorAction SilentlyContinue) { } } -Set-Alias -Name z -Value __zoxide_z -Option AllScope -Scope Global -Force -Set-Alias -Name zi -Value __zoxide_zi -Option AllScope -Scope Global -Force - # Help Function function Show-Help { $helpText = @" From 33d75537a195515d85d76623d5e51ac7f28c1330 Mon Sep 17 00:00:00 2001 From: Shardul Junagade <143334512+ShardulJunagade@users.noreply.github.com> Date: Sat, 21 Jun 2025 12:18:19 +0530 Subject: [PATCH 50/64] Update setup.ps1 to save oldprofile.ps1 in the $PROFILE folder --- setup.ps1 | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/setup.ps1 b/setup.ps1 index 1a835a28..7a9c082c 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -89,13 +89,15 @@ if (!(Test-Path -Path $PROFILE -PathType Leaf)) { } else { try { - Get-Item -Path $PROFILE | Move-Item -Destination "oldprofile.ps1" -Force + $backupPath = Join-Path (Split-Path $PROFILE) "oldprofile.ps1" + Move-Item -Path $PROFILE -Destination $backupPath -Force Invoke-RestMethod https://github.com/ChrisTitusTech/powershell-profile/raw/main/Microsoft.PowerShell_profile.ps1 -OutFile $PROFILE - Write-Host "The profile @ [$PROFILE] has been created and old profile removed." - Write-Host "Please back up any persistent components of your old profile to [$HOME\Documents\PowerShell\Profile.ps1] as there is an updater in the installed profile which uses the hash to update the profile and will lead to loss of changes" + Write-Host "✅ PowerShell profile at [$PROFILE] has been updated." + Write-Host "📦 Your old profile has been backed up to [$backupPath]" + Write-Host "⚠️ NOTE: Please back up any persistent components of your old profile to [$HOME\Documents\PowerShell\Profile.ps1] as there is an updater in the installed profile which uses the hash to update the profile and will lead to loss of changes" } catch { - Write-Error "Failed to backup and update the profile. Error: $_" + Write-Error "❌ Failed to backup and update the profile. Error: $_" } } From 25cc575476e9a1b16c3b0f86822cc34998a1cbc8 Mon Sep 17 00:00:00 2001 From: Shardul Junagade <143334512+ShardulJunagade@users.noreply.github.com> Date: Mon, 23 Jun 2025 08:23:54 +0530 Subject: [PATCH 51/64] change gp to gpush and add gpull --- Microsoft.PowerShell_profile.ps1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 4c0de8ce..c54ed035 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -394,7 +394,9 @@ function ga { git add . } function gc { param($m) git commit -m "$m" } -function gp { git push } +function gpush { git push } + +function gpull { git pull } function g { __zoxide_z github } From f1a6b89017b8161fbe21c916768146b37d514998 Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Wed, 2 Jul 2025 17:04:51 -0500 Subject: [PATCH 52/64] Update Microsoft.PowerShell_profile.ps1 --- Microsoft.PowerShell_profile.ps1 | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index fb99bb47..9b225d68 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -501,23 +501,7 @@ $scriptblock = { } 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 - } - oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression - } 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 +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 --cmd cd powershell | Out-String) }) } else { From 9edd63a10f4c13c8ec184c12f9db2e4a075a6c3a Mon Sep 17 00:00:00 2001 From: Shardul Junagade <23110297@iitgn.ac.in> Date: Thu, 3 Jul 2025 07:08:02 +0530 Subject: [PATCH 53/64] add gpush, gpull in Show-Help --- Microsoft.PowerShell_profile.ps1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 9b225d68..35c21be1 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -585,7 +585,9 @@ $($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. $($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. -$($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'. +$($PSStyle.Foreground.Green)gpush$($PSStyle.Reset) - Shortcut for 'git push'. + +$($PSStyle.Foreground.Green)gpull$($PSStyle.Reset) - Shortcut for 'git pull'. $($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. From 6013a5d440c1bc768dbf33257a256c47f42522c2 Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Mon, 14 Jul 2025 21:14:44 -0500 Subject: [PATCH 54/64] Zoxide fix --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index ae3e82b1..5ffac158 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -611,7 +611,7 @@ Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock 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 --cmd cd powershell | Out-String) }) + Invoke-Expression (& { (zoxide init powershell | Out-String) }) } else { Write-Host "zoxide command not found. Attempting to install via winget..." try { From 87c4c63f9817e6de026a1db5820db56022fa3175 Mon Sep 17 00:00:00 2001 From: Chris Titus Date: Mon, 14 Jul 2025 21:16:00 -0500 Subject: [PATCH 55/64] zoxide z alias --- Microsoft.PowerShell_profile.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 5ffac158..18b39da5 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -611,13 +611,13 @@ Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock 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) }) + Invoke-Expression (& { (zoxide init --cmd z 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) }) + Invoke-Expression (& { (zoxide init --cmd z powershell | Out-String) }) } catch { Write-Error "Failed to install zoxide. Error: $_" } From c9766c45a2f2f9458de8b14a2b0b77bae8719706 Mon Sep 17 00:00:00 2001 From: Pierre Chateau Date: Tue, 15 Jul 2025 17:46:53 +0200 Subject: [PATCH 56/64] Fixes to that if there is an Get-Theme_Override then call that function to fix oh-my-posh problems and keep zoxide working. Example function Get-Theme_Override { Invoke-Expression (& { (oh-my-posh init pwsh --config c:\ws\oh-my-posh\pmc.chips.omp.json | Out-String) }) } --- Microsoft.PowerShell_profile.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 18b39da5..bd638950 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -608,7 +608,11 @@ $scriptblock = { } Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock -oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression +if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue){ + Get-Theme_Override; +} else { + 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 --cmd z powershell | Out-String) }) From d4d8ce8bceffe538e63ebadc4793191a85c98b0b Mon Sep 17 00:00:00 2001 From: yusufakg <101368497+yusufakg@users.noreply.github.com> Date: Tue, 15 Jul 2025 17:34:35 +0200 Subject: [PATCH 57/64] install the cobalt2 theme locally for faster launch times --- Microsoft.PowerShell_profile.ps1 | 39 ++++++++++++++++++++++--------- setup.ps1 | 40 +++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 12 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bd638950..7a7cde8b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -319,7 +319,7 @@ function uptime { # find date/time format $dateFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.ShortDatePattern $timeFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.LongTimePattern - + # check powershell version if ($PSVersionTable.PSVersion.Major -eq 5) { $lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime @@ -329,7 +329,7 @@ function uptime { $lastBoot = $bootTime.ToString("$dateFormat $timeFormat") } else { # the Get-Uptime cmdlet was introduced in PowerShell 6.0 - $lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat") + $lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat") $bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture) } @@ -368,16 +368,16 @@ function hb { 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 @@ -468,12 +468,12 @@ function trash($path) { ### Quality of Life Aliases # Navigation Shortcuts -function docs { +function docs { $docs = if(([Environment]::GetFolderPath("MyDocuments"))) {([Environment]::GetFolderPath("MyDocuments"))} else {$HOME + "\Documents"} Set-Location -Path $docs } - -function dtop { + +function dtop { $dtop = if ([Environment]::GetFolderPath("Desktop")) {[Environment]::GetFolderPath("Desktop")} else {$HOME + "\Documents"} Set-Location -Path $dtop } @@ -589,7 +589,7 @@ $scriptblock = { 'npm' = @('install', 'start', 'run', 'test', 'build') 'deno' = @('run', 'compile', 'bundle', 'test', 'lint', 'fmt', 'cache', 'info', 'doc', 'upgrade') } - + $command = $commandAst.CommandElements[0].Value if ($customCompletions.ContainsKey($command)) { $customCompletions[$command] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { @@ -608,10 +608,27 @@ $scriptblock = { } Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock -if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue){ +if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue) { Get-Theme_Override; } else { - oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression + # Oh My Posh initialization with local theme fallback and auto-download + $localThemePath = "$env:userprofile\Documents\PowerShell\cobalt2.omp.json" + if (-not (Test-Path $localThemePath)) { + # Try to download the theme file to the detected local path + $themeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json" + try { + Invoke-RestMethod -Uri $themeUrl -OutFile $localThemePath + Write-Host "Downloaded missing Oh My Posh theme to $localThemePath" + } catch { + Write-Warning "Failed to download theme file. Falling back to remote theme. Error: $_" + } + } + if (Test-Path $localThemePath) { + oh-my-posh init pwsh --config $localThemePath | Invoke-Expression + } else { + # Fallback to remote theme if local file doesn't exist + 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) { diff --git a/setup.ps1 b/setup.ps1 index 18c430df..6643f76f 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -101,6 +101,41 @@ else { } } +# Function to download Oh My Posh theme locally +function Install-OhMyPoshTheme { + param ( + [string]$ThemeName = "cobalt2", + [string]$ThemeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json" + ) + + try { + # Detect Version of PowerShell & Create Profile directories if they do not exist. + $profilePath = "" + if ($PSVersionTable.PSEdition -eq "Core") { + $profilePath = "$env:userprofile\Documents\Powershell" + } + elseif ($PSVersionTable.PSEdition -eq "Desktop") { + $profilePath = "$env:userprofile\Documents\WindowsPowerShell" + } + + if (!(Test-Path -Path $profilePath)) { + New-Item -Path $profilePath -ItemType "directory" -Force + } + + $themeFilePath = Join-Path $profilePath "$ThemeName.omp.json" + + # Download the theme file + Invoke-RestMethod -Uri $ThemeUrl -OutFile $themeFilePath + Write-Host "Oh My Posh theme '$ThemeName' has been downloaded to [$themeFilePath]" + + return $themeFilePath + } + catch { + Write-Error "Failed to download Oh My Posh theme. Error: $_" + return $null + } +} + # OMP Install try { winget install -e --accept-source-agreements --accept-package-agreements JanDeDobbeleer.OhMyPosh @@ -109,11 +144,14 @@ catch { Write-Error "Failed to install Oh My Posh. Error: $_" } +# Download Oh My Posh theme locally +$themeInstalled = Install-OhMyPoshTheme -ThemeName "cobalt2" + # Font Install Install-NerdFonts -FontName "CascadiaCode" -FontDisplayName "CaskaydiaCove NF" # Final check and message to the user -if ((Test-Path -Path $PROFILE) -and (winget list --name "OhMyPosh" -e) -and ($fontFamilies -contains "CaskaydiaCove NF")) { +if ((Test-Path -Path $PROFILE) -and (winget list --name "OhMyPosh" -e) -and ($fontFamilies -contains "CaskaydiaCove NF") -and $themeInstalled) { Write-Host "Setup completed successfully. Please restart your PowerShell session to apply changes." } else { Write-Warning "Setup completed with errors. Please check the error messages above." From 0223d397fc5b8a515c5177ef7ccd0b07c25f81cf Mon Sep 17 00:00:00 2001 From: yusufakg <101368497+yusufakg@users.noreply.github.com> Date: Wed, 16 Jul 2025 02:28:08 +0200 Subject: [PATCH 58/64] improve cross-edition compatibility --- Microsoft.PowerShell_profile.ps1 | 69 ++++++++++++++++++++++++-------- setup.ps1 | 48 +++++++++------------- 2 files changed, 71 insertions(+), 46 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 7a7cde8b..eb1be5bb 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -3,12 +3,6 @@ $debug = $false -# Define the path to the file that stores the last execution time -$timeFilePath = [Environment]::GetFolderPath("MyDocuments") + "\PowerShell\LastExecutionTime.txt" - -# Define the update interval in days, set to -1 to always check -$updateInterval = 7 - ################################################################################################################################# ############ ############ ############ !!! WARNING: !!! ############ @@ -61,13 +55,26 @@ if ($repo_root_Override){ $repo_root = "https://raw.githubusercontent.com/ChrisTitusTech" } +# Helper function for cross-edition compatibility +function Get-ProfileDir { + if ($PSVersionTable.PSEdition -eq "Core") { + return "$env:userprofile\Documents\PowerShell" + } elseif ($PSVersionTable.PSEdition -eq "Desktop") { + return "$env:userprofile\Documents\WindowsPowerShell" + } else { + Write-Error "Unsupported PowerShell edition: $($PSVersionTable.PSEdition)" + return $null + } +} + # Define the path to the file that stores the last execution time if ($timeFilePath_Override){ # If variable $timeFilePath_Override is defined in profile.ps1 file # then use it instead $timeFilePath = $timeFilePath_Override } else { - $timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" + $profileDir = Get-ProfileDir + $timeFilePath = "$profileDir\LastExecutionTime.txt" } # Define the update interval in days, set to -1 to always check @@ -108,8 +115,19 @@ if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) } -# Initial GitHub.com connectivity check with 1 second timeout -$global:canConnectToGitHub = Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 +# Initial GitHub.com connectivity check +function Test-GitHubConnection { + if ($PSVersionTable.PSEdition -eq "Core") { + # If PowerShell Core, use a 1 second timeout + return Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1 + } else { + # For PowerShell Desktop, use .NET Ping class with timeout + $ping = New-Object System.Net.NetworkInformation.Ping + $result = $ping.Send("github.com", 1000) # 1 second timeout + return ($result.Status -eq "Success") + } +} +$global:canConnectToGitHub = Test-GitHubConnection # Import Modules and External Profiles # Ensure Terminal-Icons module is installed before importing @@ -524,6 +542,20 @@ function cpy { Set-Clipboard $args[0] } function pst { Get-Clipboard } +# Set-PSReadLineOption Compatibility for PowerShell Desktop +function Set-PSReadLineOptionsCompat { + param([hashtable]$Options) + if ($PSVersionTable.PSEdition -eq "Core") { + Set-PSReadLineOption @Options + } else { + # Remove unsupported keys for Desktop and silence errors + $SafeOptions = $Options.Clone() + $SafeOptions.Remove('PredictionSource') + $SafeOptions.Remove('PredictionViewStyle') + Set-PSReadLineOption @SafeOptions + } +} + # Enhanced PowerShell Experience # Enhanced PSReadLine Configuration $PSReadLineOptions = @{ @@ -546,7 +578,7 @@ $PSReadLineOptions = @{ PredictionViewStyle = 'ListView' BellStyle = 'None' } -Set-PSReadLineOption @PSReadLineOptions +Set-PSReadLineOptionsCompat -Options $PSReadLineOptions # Custom key handlers Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward @@ -568,15 +600,18 @@ Set-PSReadLineOption -AddToHistoryHandler { return ($null -eq $hasSensitive) } +# Fix Set-PredictionSource for Desktop function Set-PredictionSource { - # If function "Set-PredictionSource_Override" is defined in profile.ps1 file - # then call it instead. + # If "Set-PredictionSource_Override" is defined in profile.ps1 file, call it instead. if (Get-Command -Name "Set-PredictionSource_Override" -ErrorAction SilentlyContinue) { - Set-PredictionSource_Override; + Set-PredictionSource_Override + } elseif ($PSVersionTable.PSEdition -eq "Core") { + # Improved prediction settings + Set-PSReadLineOption -PredictionSource HistoryAndPlugin + Set-PSReadLineOption -MaximumHistoryCount 10000 } else { - # Improved prediction settings - Set-PSReadLineOption -PredictionSource HistoryAndPlugin - Set-PSReadLineOption -MaximumHistoryCount 10000 + # Desktop version - use History only + Set-PSReadLineOption -MaximumHistoryCount 10000 } } Set-PredictionSource @@ -612,7 +647,7 @@ if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue) { Get-Theme_Override; } else { # Oh My Posh initialization with local theme fallback and auto-download - $localThemePath = "$env:userprofile\Documents\PowerShell\cobalt2.omp.json" + $localThemePath = Join-Path (Get-ProfileDir) "cobalt2.omp.json" if (-not (Test-Path $localThemePath)) { # Try to download the theme file to the detected local path $themeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json" diff --git a/setup.ps1 b/setup.ps1 index 6643f76f..ea758164 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -58,6 +58,18 @@ function Install-NerdFonts { } } +# Helper function for cross-edition compatibility +function Get-ProfileDir { + if ($PSVersionTable.PSEdition -eq "Core") { + return "$env:userprofile\Documents\PowerShell" + } elseif ($PSVersionTable.PSEdition -eq "Desktop") { + return "$env:userprofile\Documents\WindowsPowerShell" + } else { + Write-Error "Unsupported PowerShell edition: $($PSVersionTable.PSEdition)" + break + } +} + # Check for internet connectivity before proceeding if (-not (Test-InternetConnection)) { break @@ -66,19 +78,10 @@ if (-not (Test-InternetConnection)) { # Profile creation or update if (!(Test-Path -Path $PROFILE -PathType Leaf)) { try { - # Detect Version of PowerShell & Create Profile directories if they do not exist. - $profilePath = "" - if ($PSVersionTable.PSEdition -eq "Core") { - $profilePath = "$env:userprofile\Documents\Powershell" - } - elseif ($PSVersionTable.PSEdition -eq "Desktop") { - $profilePath = "$env:userprofile\Documents\WindowsPowerShell" - } - + $profilePath = Get-ProfileDir if (!(Test-Path -Path $profilePath)) { - New-Item -Path $profilePath -ItemType "directory" + New-Item -Path $profilePath -ItemType "directory" -Force } - Invoke-RestMethod https://github.com/ChrisTitusTech/powershell-profile/raw/main/Microsoft.PowerShell_profile.ps1 -OutFile $PROFILE Write-Host "The profile @ [$PROFILE] has been created." Write-Host "If you want to make any personal changes or customizations, please do so at [$profilePath\Profile.ps1] as there is an updater in the installed profile which uses the hash to update the profile and will lead to loss of changes" @@ -107,27 +110,14 @@ function Install-OhMyPoshTheme { [string]$ThemeName = "cobalt2", [string]$ThemeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json" ) - + $profilePath = Get-ProfileDir + if (!(Test-Path -Path $profilePath)) { + New-Item -Path $profilePath -ItemType "directory" + } + $themeFilePath = Join-Path $profilePath "$ThemeName.omp.json" try { - # Detect Version of PowerShell & Create Profile directories if they do not exist. - $profilePath = "" - if ($PSVersionTable.PSEdition -eq "Core") { - $profilePath = "$env:userprofile\Documents\Powershell" - } - elseif ($PSVersionTable.PSEdition -eq "Desktop") { - $profilePath = "$env:userprofile\Documents\WindowsPowerShell" - } - - if (!(Test-Path -Path $profilePath)) { - New-Item -Path $profilePath -ItemType "directory" -Force - } - - $themeFilePath = Join-Path $profilePath "$ThemeName.omp.json" - - # Download the theme file Invoke-RestMethod -Uri $ThemeUrl -OutFile $themeFilePath Write-Host "Oh My Posh theme '$ThemeName' has been downloaded to [$themeFilePath]" - return $themeFilePath } catch { From 1fafe785ead4e974343cba2cc8c49e2a823b3167 Mon Sep 17 00:00:00 2001 From: yusufakg <101368497+yusufakg@users.noreply.github.com> Date: Wed, 16 Jul 2025 19:19:41 +0200 Subject: [PATCH 59/64] some small changes to fix warnings of PSScriptAnalyzer --- Microsoft.PowerShell_profile.ps1 | 41 +++++++++++++++++--------------- setup.ps1 | 5 +++- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index eb1be5bb..be34164b 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -1,5 +1,5 @@ ### PowerShell Profile Refactor -### Version 1.03 - Refactored +### Version 1.04 - Refactored $debug = $false @@ -35,9 +35,6 @@ $debug = $false ############ Set-PredictionSource ############ ################################################################################################################################# -### PowerShell Profile Refactor -### Version 1.04 - Refactored - if ($debug_Override){ # If variable debug_Override is defined in profile.ps1 file # then use it instead @@ -110,7 +107,7 @@ if ($debug) { } -#opt-out of telemetry before doing anything, only if PowerShell is run as admin +# Opt-out of telemetry before doing anything, only if PowerShell is run as admin if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) { [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine) } @@ -145,7 +142,7 @@ function Update-Profile { # If function "Update-Profile_Override" is defined in profile.ps1 file # then call it instead. if (Get-Command -Name "Update-Profile_Override" -ErrorAction SilentlyContinue) { - Update-Profile_Override; + Update-Profile_Override } else { try { $url = "$repo_root/powershell-profile/main/Microsoft.PowerShell_profile.ps1" @@ -184,7 +181,7 @@ function Update-PowerShell { # If function "Update-PowerShell_Override" is defined in profile.ps1 file # then call it instead. if (Get-Command -Name "Update-PowerShell_Override" -ErrorAction SilentlyContinue) { - Update-PowerShell_Override; + Update-PowerShell_Override } else { try { Write-Host "Checking for PowerShell updates..." -ForegroundColor Cyan @@ -293,6 +290,13 @@ function Edit-Profile { } Set-Alias -Name ep -Value Edit-Profile +function Invoke-Profile { + if ($PSVersionTable.PSEdition -eq "Desktop") { + Write-Host "Note: Some Oh My Posh/PSReadLine errors are expected in PowerShell 5. The profile still works fine." -ForegroundColor Yellow + } + & $PROFILE +} + function touch($file) { "" | Out-File $file -Encoding ASCII } function ff($name) { Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object { @@ -301,21 +305,21 @@ function ff($name) { } # Network Utilities -function Get-PubIP { (Invoke-WebRequest http://ifconfig.me/ip).Content } +function pubip { (Invoke-WebRequest http://ifconfig.me/ip).Content } # Open WinUtil full-release function winutil { - irm https://christitus.com/win | iex + Invoke-Expression (Invoke-RestMethod https://christitus.com/win) } # Open WinUtil dev-release function winutildev { - # If function "WinUtilDev_Override" is defined in profile.ps1 file + # If function "WinUtilDev_Override" is defined in profile.ps1 file # then call it instead. if (Get-Command -Name "WinUtilDev_Override" -ErrorAction SilentlyContinue) { WinUtilDev_Override } else { - irm https://christitus.com/windev | iex + Invoke-Expression (Invoke-RestMethod https://christitus.com/windev) } } @@ -372,10 +376,6 @@ function uptime { } } -function reload-profile { - & $profile -} - function unzip ($file) { Write-Output("Extracting", $file, "to", $pwd) $fullFile = Get-ChildItem -Path $pwd -Filter $file | ForEach-Object { $_.FullName } @@ -602,7 +602,8 @@ Set-PSReadLineOption -AddToHistoryHandler { # Fix Set-PredictionSource for Desktop function Set-PredictionSource { - # If "Set-PredictionSource_Override" is defined in profile.ps1 file, call it instead. + # If "Set-PredictionSource_Override" is defined in profile.ps1 file + # then call it instead. if (Get-Command -Name "Set-PredictionSource_Override" -ErrorAction SilentlyContinue) { Set-PredictionSource_Override } elseif ($PSVersionTable.PSEdition -eq "Core") { @@ -643,8 +644,10 @@ $scriptblock = { } Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock +# If function "Get-Theme_Override" is defined in profile.ps1 file +# then call it instead. if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue) { - Get-Theme_Override; + Get-Theme_Override } else { # Oh My Posh initialization with local theme fallback and auto-download $localThemePath = Join-Path (Get-ProfileDir) "cobalt2.omp.json" @@ -687,6 +690,7 @@ $($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) $($PSStyle.Foreground.Green)Update-Profile$($PSStyle.Reset) - Checks for profile updates from a remote repository and updates if necessary. $($PSStyle.Foreground.Green)Update-PowerShell$($PSStyle.Reset) - Checks for the latest PowerShell release and updates if a new version is available. $($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor. +$($PSStyle.Foreground.Green)Invoke-Profile$($PSStyle.Reset) - Runs the current user's profile to reload settings. $($PSStyle.Foreground.Cyan)Git Shortcuts$($PSStyle.Reset) $($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) @@ -708,7 +712,7 @@ $($PSStyle.Foreground.Green)ep$($PSStyle.Reset) - Opens the profile for editing. $($PSStyle.Foreground.Green)export$($PSStyle.Reset) - Sets an environment variable. $($PSStyle.Foreground.Green)ff$($PSStyle.Reset) - Finds files recursively with the specified name. $($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. -$($PSStyle.Foreground.Green)Get-PubIP$($PSStyle.Reset) - Retrieves the public IP address of the machine. +$($PSStyle.Foreground.Green)pubip$($PSStyle.Reset) - Retrieves the public IP address of the machine. $($PSStyle.Foreground.Green)grep$($PSStyle.Reset) [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input. $($PSStyle.Foreground.Green)hb$($PSStyle.Reset) - Uploads the specified file's content to a hastebin-like service and returns the URL. $($PSStyle.Foreground.Green)head$($PSStyle.Reset) [n] - Displays the first n lines of a file (default 10). @@ -731,7 +735,6 @@ $($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system $($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. $($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. $($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard. -$($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. $($PSStyle.Foreground.Green)sed$($PSStyle.Reset) - Replaces text in a file. $($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. $($PSStyle.Foreground.Green)tail$($PSStyle.Reset) [n] - Displays the last n lines of a file (default 10). diff --git a/setup.ps1 b/setup.ps1 index ea758164..8e4546ee 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -149,7 +149,10 @@ if ((Test-Path -Path $PROFILE) -and (winget list --name "OhMyPosh" -e) -and ($fo # Choco install try { - Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) + Set-ExecutionPolicy Bypass -Scope Process -Force + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 + $chocoScript = (New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1') + Invoke-Expression $chocoScript } catch { Write-Error "Failed to install Chocolatey. Error: $_" From 3561553ba01ea6343724d30b3e2ff447ff64d881 Mon Sep 17 00:00:00 2001 From: CasperGaming <90271508+CasperGamingOne@users.noreply.github.com> Date: Mon, 21 Jul 2025 17:26:39 +0300 Subject: [PATCH 60/64] Update Microsoft.PowerShell_profile.ps1 flushdns appeared twice in the show-help function, removed the additional appeareance --- Microsoft.PowerShell_profile.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bd638950..571d0f04 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -676,7 +676,6 @@ $($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory $($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. $($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. $($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. -$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. $($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. $($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard. $($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. From 66fc050128289079462fbc734cf42cae57bcde1b Mon Sep 17 00:00:00 2001 From: Mat18115 Date: Sun, 10 Aug 2025 18:43:43 +0200 Subject: [PATCH 61/64] fix: guard empty LastExecutionTime to avoid ParseExact null error --- Microsoft.PowerShell_profile.ps1 | 66 +++++++++++++++++++------------- 1 file changed, 39 insertions(+), 27 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bd638950..410aa1a4 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -122,6 +122,16 @@ if (Test-Path($ChocolateyProfile)) { Import-Module "$ChocolateyProfile" } +# Safely read and parse the last execution date once to avoid exceptions when the file is missing or empty +$lastExecRaw = if (Test-Path $timeFilePath) { (Get-Content -Path $timeFilePath -Raw).Trim() } else { $null } +[datetime]$lastExec = $null +if (-not [string]::IsNullOrWhiteSpace($lastExecRaw)) { + [datetime]$parsed = [datetime]::MinValue + if ([datetime]::TryParseExact($lastExecRaw, 'yyyy-MM-dd', $null, [System.Globalization.DateTimeStyles]::None, [ref]$parsed)) { + $lastExec = $parsed + } +} + # Check for Profile Updates function Update-Profile { # If function "Update-Profile_Override" is defined in profile.ps1 file @@ -151,8 +161,9 @@ function Update-Profile { # Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval) if (-not $debug -and ` ($updateInterval -eq -1 -or ` - -not (Test-Path $timeFilePath) -or ` - ((Get-Date) - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd', $null)).TotalDays -gt $updateInterval)) { + -not (Test-Path $timeFilePath) -or ` + $null -eq $lastExec -or ` + ((Get-Date) - $lastExec).TotalDays -gt $updateInterval)) { Update-Profile $currentTime = Get-Date -Format 'yyyy-MM-dd' @@ -196,8 +207,9 @@ function Update-PowerShell { # Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval) if (-not $debug -and ` ($updateInterval -eq -1 -or ` - -not (Test-Path $timeFilePath) -or ` - ((Get-Date).Date - [datetime]::ParseExact((Get-Content -Path $timeFilePath), 'yyyy-MM-dd', $null).Date).TotalDays -gt $updateInterval)) { + -not (Test-Path $timeFilePath) -or ` + $null -eq $lastExec -or ` + ((Get-Date).Date - $lastExec.Date).TotalDays -gt $updateInterval)) { Update-PowerShell $currentTime = Get-Date -Format 'yyyy-MM-dd' @@ -259,14 +271,14 @@ if ($EDITOR_Override){ $EDITOR = $EDITOR_Override } else { $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 codium) { 'codium' } - elseif (Test-CommandExists notepad++) { 'notepad++' } - elseif (Test-CommandExists sublime_text) { 'sublime_text' } - else { 'notepad' } + elseif (Test-CommandExists pvim) { 'pvim' } + elseif (Test-CommandExists vim) { 'vim' } + elseif (Test-CommandExists vi) { 'vi' } + elseif (Test-CommandExists code) { 'code' } + elseif (Test-CommandExists codium) { 'codium' } + elseif (Test-CommandExists notepad++) { 'notepad++' } + elseif (Test-CommandExists sublime_text) { 'sublime_text' } + else { 'notepad' } Set-Alias -Name vim -Value $EDITOR } # Quick Access to Editing the Profile @@ -292,7 +304,7 @@ function winutil { # Open WinUtil dev-release function winutildev { - # If function "WinUtilDev_Override" is defined in profile.ps1 file + # If function "WinUtilDev_Override" is defined in profile.ps1 file # then call it instead. if (Get-Command -Name "WinUtilDev_Override" -ErrorAction SilentlyContinue) { WinUtilDev_Override @@ -383,7 +395,7 @@ function hb { $response = Invoke-RestMethod -Uri $uri -Method Post -Body $Content -ErrorAction Stop $hasteKey = $response.key $url = "http://bin.christitus.com/$hasteKey" - Set-Clipboard $url + Set-Clipboard $url Write-Output "$url copied to clipboard." } catch { Write-Error "Failed to upload the document. Error: $_" @@ -422,13 +434,13 @@ function pgrep($name) { } function head { - param($Path, $n = 10) - Get-Content $Path -Head $n + 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 + param($Path, $n = 10, [switch]$f = $false) + Get-Content $Path -Tail $n -Wait:$f } # Quick File Creation @@ -444,7 +456,7 @@ function trash($path) { $item = Get-Item $fullPath if ($item.PSIsContainer) { - # Handle directory + # Handle directory $parentPath = $item.Parent.FullName } else { # Handle file @@ -515,8 +527,8 @@ function sysinfo { Get-ComputerInfo } # Networking Utilities function flushdns { - Clear-DnsClientCache - Write-Host "DNS has been flushed" + Clear-DnsClientCache + Write-Host "DNS has been flushed" } # Clipboard Utilities @@ -574,9 +586,9 @@ function Set-PredictionSource { if (Get-Command -Name "Set-PredictionSource_Override" -ErrorAction SilentlyContinue) { Set-PredictionSource_Override; } else { - # Improved prediction settings - Set-PSReadLineOption -PredictionSource HistoryAndPlugin - Set-PSReadLineOption -MaximumHistoryCount 10000 + # Improved prediction settings + Set-PSReadLineOption -PredictionSource HistoryAndPlugin + Set-PSReadLineOption -MaximumHistoryCount 10000 } } Set-PredictionSource @@ -602,9 +614,9 @@ Register-ArgumentCompleter -Native -CommandName git, npm, deno -ScriptBlock $scr $scriptblock = { param($wordToComplete, $commandAst, $cursorPosition) dotnet complete --position $cursorPosition $commandAst.ToString() | - ForEach-Object { - [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) - } + ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } } Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock From ec4e1d4c64abad3d8bce23aef5602742ae693131 Mon Sep 17 00:00:00 2001 From: brich4750 <150873204+brich4750@users.noreply.github.com> Date: Sun, 14 Sep 2025 23:10:22 -0400 Subject: [PATCH 62/64] Update Microsoft.PowerShell_profile.ps1 Fixes Line 70-when not using Override for timeFilePath. --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bd638950..abb4443e 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -67,7 +67,7 @@ if ($timeFilePath_Override){ # then use it instead $timeFilePath = $timeFilePath_Override } else { - $timeFilePath = "$env:USERPROFILE\Documents\PowerShell\LastExecutionTime.txt" + $timeFilePath = [Environment]::GetFolderPath("MyDocuments") + "\PowerShell\LastExecutionTime.txt" } # Define the update interval in days, set to -1 to always check From b4ca6591ad0e1eb43541076d0e8b059cc7edf047 Mon Sep 17 00:00:00 2001 From: JamesDBartlett3 <37491308+JamesDBartlett3@users.noreply.github.com> Date: Fri, 24 Oct 2025 17:03:57 -0500 Subject: [PATCH 63/64] housekeeping: - de-duplicated entries in $helpText - alphabetized entries within each section in $helpText --- Microsoft.PowerShell_profile.ps1 | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index bd638950..c35235ab 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -632,17 +632,20 @@ function Show-Help { $helpText = @" $($PSStyle.Foreground.Cyan)PowerShell Profile Help$($PSStyle.Reset) $($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) +$($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor. $($PSStyle.Foreground.Green)Update-Profile$($PSStyle.Reset) - Checks for profile updates from a remote repository and updates if necessary. $($PSStyle.Foreground.Green)Update-PowerShell$($PSStyle.Reset) - Checks for the latest PowerShell release and updates if a new version is available. -$($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor. $($PSStyle.Foreground.Cyan)Git Shortcuts$($PSStyle.Reset) $($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset) $($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. $($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. $($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. +$($PSStyle.Foreground.Green)gcl$($PSStyle.Reset) - Shortcut for 'git clone'. $($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. $($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'. +$($PSStyle.Foreground.Green)gpull$($PSStyle.Reset) - Shortcut for 'git pull'. +$($PSStyle.Foreground.Green)gpush$($PSStyle.Reset) - Shortcut for 'git push'. $($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'. $($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. @@ -667,17 +670,6 @@ $($PSStyle.Foreground.Green)mkcd$($PSStyle.Reset) - Creates and changes to $($PSStyle.Foreground.Green)nf$($PSStyle.Reset) - Creates a new file with the specified name. $($PSStyle.Foreground.Green)pgrep$($PSStyle.Reset) - Lists processes by name. $($PSStyle.Foreground.Green)pkill$($PSStyle.Reset) - Kills processes by name. -$($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'. -$($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'. -$($PSStyle.Foreground.Green)gc$($PSStyle.Reset) - Shortcut for 'git commit -m'. -$($PSStyle.Foreground.Green)gpush$($PSStyle.Reset) - Shortcut for 'git push'. -$($PSStyle.Foreground.Green)gpull$($PSStyle.Reset) - Shortcut for 'git pull'. -$($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory. -$($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) - Adds all changes and commits with the specified message. -$($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) - Adds all changes, commits with the specified message, and pushes to the remote repository. -$($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information. -$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache. -$($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) - Copies the specified text to the clipboard. $($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard. $($PSStyle.Foreground.Green)reload-profile$($PSStyle.Reset) - Reloads the current user's PowerShell profile. $($PSStyle.Foreground.Green)sed$($PSStyle.Reset) - Replaces text in a file. From 976b7bc592e87a34c3ff29128b9bdc24dabe888c Mon Sep 17 00:00:00 2001 From: Jacob Clayden Date: Fri, 2 Jan 2026 12:15:48 +0000 Subject: [PATCH 64/64] Change lastExec variable to Nullable[datetime] --- Microsoft.PowerShell_profile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.PowerShell_profile.ps1 b/Microsoft.PowerShell_profile.ps1 index 7c1925ca..da4512b8 100644 --- a/Microsoft.PowerShell_profile.ps1 +++ b/Microsoft.PowerShell_profile.ps1 @@ -139,7 +139,7 @@ if (Test-Path($ChocolateyProfile)) { # Safely read and parse the last execution date once to avoid exceptions when the file is missing or empty $lastExecRaw = if (Test-Path $timeFilePath) { (Get-Content -Path $timeFilePath -Raw).Trim() } else { $null } -[datetime]$lastExec = $null +[Nullable[datetime]]$lastExec = $null if (-not [string]::IsNullOrWhiteSpace($lastExecRaw)) { [datetime]$parsed = [datetime]::MinValue if ([datetime]::TryParseExact($lastExecRaw, 'yyyy-MM-dd', $null, [System.Globalization.DateTimeStyles]::None, [ref]$parsed)) {