r/PowerShell • u/Incrediblecodeman • 2d ago
Question Good powershell profile tips
I’ve been having way too much fun customizing my PowerShell profile lately. 😂
Here’s what I’ve got so far:
root — Prompts for my Domain Admin credentials and launches a new elevated PowerShell session.
Green errors — Because Don Jones taught me that errors don’t have to be angry red.
Custom prompt — Shows my current path and the time, so I can tell how long commands took.
save-clip — My homemade clipboard vault! Password-encrypts whatever’s on my clipboard and saves it to a file. Even works with images.
Admin indicator — Makes it obvious when I’m running elevated.
Extended scrollback — Because nothing hurts quite like scrolling up to find something important, only to discover PowerShell already ate it. 😭
record — My next addition! A one-word shortcut to start a PowerShell transcript, timestamp the log file, and record my session. Maybe a stoprecord companion too.
I’m starting to think my PowerShell profile is becoming its own operating system.
What other clever functions, shortcuts, or quality-of-life improvements have you all added to yours? I’m looking for ideas worth stealing. 😂
5
u/wonkifier 1d ago edited 1d ago
I run pwsh on a remote linux container normally.
I whipped up a PSReadline handler that kicks off a background thread that starts a timer and updates my window title by prefixing it with the elapsed time. And a prompt command that stops the timer and restores the original title.
So while a command is running, I can track it in my terminal tabs.
I don't notice it most of the time, but when I do, it really pays off.
2
u/Incrediblecodeman 1d ago
Oh heck! Can you show a sample please dude that’s fuck as fuck
2
u/wonkifier 1d ago
Here's a version that strips out some internal stuff that isn't generally relevant.
The main one that bit me was that subshells would get their own timers and fight the title, so those are detected and skipped. (little brute forcey) And yes, this was Claude assisted, and there are edge cases, but it works for my environment. Cheat from it as you like.
<# .SYNOPSIS Shows an elapsed-time counter in the terminal tab title while a command runs. .DESCRIPTION Starts a counter when PSReadLine accepts a line and stops it at the next prompt. Lines that launch a program which sets its own title (a nested pwsh by default; see $Global:TitleTimerSkip) aren't timed, so the two don't fight over the title. The line is parsed rather than string-matched so the check sees the whole pipeline ('git log | pwsh') and wrapped commands ('sudo pwsh', '/usr/bin/pwsh'). Any matching bareword counts, so 'git commit -m pwsh' also goes untimed; a missing timer is the cheaper mistake. Dot-source it into an interactive session (safe to repeat): . ./TitleTimer.ps1 Changes to the embedded C# need a fresh pwsh; a loaded type can't be replaced. .NOTES On Unix the current title can't be read back, so this owns the idle title instead of restoring it. Set $Global:TitleTimerBaseTitle to customize it. #> if (-not ('TitleTimer' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Diagnostics; using System.Globalization; using System.Threading; public static class TitleTimer { const int TickMs = 1000; const int FirstFrameMs = 1000; // short commands never touch the title static readonly object Sync = new object(); // lock holder static readonly Stopwatch Clock = new Stopwatch(); // Static so it stays rooted; a collected Timer stops firing. static readonly Timer Ticker = new Timer(OnTick, null, Timeout.Infinite, Timeout.Infinite); static string baseTitle = ""; static string onScreen; static bool active; public static void Start(string title) { lock (Sync) { baseTitle = title ?? ""; onScreen = baseTitle; // caller already set it active = true; Clock.Restart(); Ticker.Change(FirstFrameMs, Timeout.Infinite); } } public static void Stop() { lock (Sync) { if (!active) return; active = false; Ticker.Change(Timeout.Infinite, Timeout.Infinite); Write(baseTitle); // under the lock, so no stale tick can land after it } } static void OnTick(object state) { lock (Sync) { if (!active) return; try { long elapsed = Clock.ElapsedMilliseconds; Write(Render(elapsed) + " | " + baseTitle); // One-shot, aligned to the next whole second, so ticks never overlap or skip. int due = (int)(TickMs - (elapsed % TickMs)); Ticker.Change(due < 20 ? due + TickMs : due, Timeout.Infinite); } catch { // An unhandled exception on a pool thread kills the process. active = false; } } } static void Write(string title) { if (title == onScreen) return; onScreen = title; Console.Write("\x1b]0;" + title + "\x07"); // single write so it can't be interleaved } static string Render(long ms) { long s = ms / 1000; if (s < 60) return s.ToString(CultureInfo.InvariantCulture) + "s"; if (s < 3600) return string.Format(CultureInfo.InvariantCulture, "{0}:{1:00}", s / 60, s % 60); return string.Format(CultureInfo.InvariantCulture, "{0}:{1:00}:{2:00}", s / 3600, (s / 60) % 60, s % 60); } } '@ } # Programs that set their own title. Add 'ssh', 'vim', 'less', etc. to taste. if (-not $Global:TitleTimerSkip) { $Global:TitleTimerSkip = [System.Collections.Generic.HashSet[string]]::new( [string[]]@('pwsh', 'powershell'), [StringComparer]::OrdinalIgnoreCase) } if (-not $Global:TitleTimerBaseTitle) { $Global:TitleTimerBaseTitle = { Split-Path -Leaf $PWD.Path } } function Global:Get-CommandLeafName { <# .SYNOPSIS Leaf names of every bareword in the whole command line containing $Ast. .DESCRIPTION Checks all barewords, not just command names, so 'sudo pwsh' is caught. The cost is that 'git commit -m pwsh' goes untimed. #> [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory)] [System.Management.Automation.Language.Ast]$Ast ) $root = $Ast while ($root.Parent) { $root = $root.Parent } $commands = $root.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true) foreach ($command in $commands) { foreach ($element in $command.CommandElements) { if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $element.StringConstantType -eq 'BareWord') { # /usr/bin/pwsh and pwsh.exe are both pwsh [System.IO.Path]::GetFileNameWithoutExtension($element.Value) } } } } function Global:Start-TitleTimer { <# .SYNOPSIS Starts the timer for the line containing $CommandAst, unless it's skipped. .DESCRIPTION PSReadLine calls this once per command in the line; every call reaches the same verdict. #> [CmdletBinding()] param ( [Parameter(Mandatory)] [System.Management.Automation.Language.CommandAst]$CommandAst ) foreach ($name in Get-CommandLeafName -Ast $CommandAst) { if ($Global:TitleTimerSkip.Contains($name)) { [TitleTimer]::Stop() return } } $title = & $Global:TitleTimerBaseTitle $Host.UI.RawUI.WindowTitle = $title # keeps RawUI's cache in sync with the idle title [TitleTimer]::Start($title) } if (-not $Global:TitleTimerInstalled) { # Wrap the existing prompt; the install flag stops a re-run from wrapping our own wrapper. $existing = Get-Command prompt -CommandType Function -ErrorAction Ignore $Global:TitleTimerInnerPrompt = $existing ? $existing.ScriptBlock : { "PS $($PWD.Path)> " } function Global:prompt { [TitleTimer]::Stop() & $Global:TitleTimerInnerPrompt } Set-PSReadLineOption -CommandValidationHandler { param($CommandAst) # A throw here rejects the line, so never let a timer problem block Enter. try { Start-TitleTimer -CommandAst $CommandAst } catch { $null } } # The validation handler only runs from ValidateAndAcceptLine. Set-PSReadLineKeyHandler -Chord Enter -Function ValidateAndAcceptLine $Global:TitleTimerInstalled = $true }1
1
u/MonkeyNin 16h ago
So while a command is running, I can track it in my terminal tabs.
If it's a longer running task, you can emit an
\aand the terminal can play a "work complete" sound
3
u/purplemonkeymad 2d ago
Changing the error colour is one that i think is a good idea for the original terminal, the default red on blue can be hard to see. You can also change the background colour to make the contrast of red better, and if you are using windows terminal you can even use a picture.
Some of those I wouldn't put in my profile, they would be better as a module.
My tip is to keep your profile lightweight, otherwise you end up with 5 second startup times.
2
u/Incrediblecodeman 2d ago
Omg is that why? So a module just lives in that folder and my alias works the same way… cool
2
u/purplemonkeymad 2d ago
Make sure your new modules have a manifest with an explicit list of exported functions/aliases. That is what allows powershell to autoload them.
1
2
u/SrBlackVoid 1d ago
+1 on the lightweight profile recommendation, but there are a couple tricks you can do to offset loading times for things you really want in there but take a little while longer than others.
Recommend you first benchmark what components you want running in your profile to see which are the main time sinks (you can use Measure-Command or the Profiler module for this). I've found for me it was a couple module imports.
Then add this:
Register-EngineEvent -SourceIdentifier PowerShell.OnIdle -MaxTriggerCount 1 -Action { # Put stuff here }This runs the -Action block when the session is first idle (so pretty much right when the command line appears). I know it's technically not eliminating that processing time, but it does offset it. I've found it feels better overall, and more often than not the stuff I'm bringing in at those times aren't being used the nanosecond the input line comes up, so it's not really noticeable.
I also recently wondered if there's a way to 'lazy-load' components for things that are usually dependent on another command being run (like waiting to import Terminal-Icons until the first time you run ls/dir/Get-ChildItem). This is akin to running Lazy.nvim on NeoVim and setting command triggers on plugin loads. Haven't quite cracked this yet (running into tradeoffs here and there with some approaches, open to recommendations), but it's another idea to explore.
2
u/lan-shark 2d ago
My profile is isn't too crazy.:
Custom start-up message
Prompt that uses
~instead of$HOMEIf the profile is running under 5.1, set the
$IsWindows,$IsLinux, and$IsMacOSvariables for convenienceTurn on
-AutoSizeforFormat-TableandExport-Excel
Couple of Bash-y aliases
If running on Windows, alias
whichto(Get-Command).SourceAlias
latoGet-ChildItem -Force
Some Git helpers:
Find-InGitDif (
gdf) - find instances of a word in the diff between two branches. So if you wanted to find all new errors in your current branch,gdf -Word "throw" -BaseBranch "main"Invoke-GitFetchPull (
gfp) - Does what it says in the name, with an optionalgit switchin between if you pass it a branch name
Besides that, a couple helper functions for a work related project. I'll move these commands over to modules one of these days but my startup time is still well under one second so I'm okay for now
1
2
u/Lonely_Noyaaa 1d ago
I put my helper functions in a module years ago and my profile dropped from four seconds to under one. The manifest with exported functions is the part everyone misses.
1
4
u/MonkeyNin 16h ago
First some keybinds
Set-PSReadLineKeyHandler -Chord 'Tab' -Function MenuComplete
Set-PSReadLineKeyHandler -Chord 'Alt+Enter' -Function AddLine <# -Description 'For pwsh 7 mult-line express #>Because windows defaults to old oem/latin encodings, I tell it to use utf8. This sets all 3 values:
$OutputEncoding =
[Console]::OutputEncoding = [Console]::InputEncoding =
[System.Text.UTF8Encoding]::new( <# bool: encoderShouldEmitUTF8Identifier #> $false )Admin indicator — Makes it obvious when I’m running elevated.
I have a red number for total errors, and it hides if there are none. It's useful because sometimes errors are not written to the console. Or it'll show one error but 3 were generated
pansies lets you write colors that work on PS 5 and Pwsh 7 ( and you can write to any stream, not just write-host )
Import-Module Pansies
function Prompt {
@(
"`n"
# last path breadcrumbs, dim colors
(( pwd ) -split '\\' | Select -last 2 ) -join '>' |
New-Text -bg 'gray20' -fg 'gray50'
"`n"
# red errors only if existing
if( $error.count -gt 0 ) {
$error.Count | New-Text -fg 'red'
}
# rest of prompt
" pwsh> "
) -join ''
}1
u/reevesjeremy 1d ago
I work in multiple user context for different purposes to separate sessions out. So each profile has different modules that load specific to that account. One of them which is consistent is a Set-WindowTitle module that sets the PowerShell window to whoami - Original Title. So I know which window is for which user in the taskbar. Then it loads each module that I want for that user. And then does a Get-Module so I know which modules are loaded in each session. Reminds me of what’s available every so often.
1
u/Incrediblecodeman 1d ago
Some dude put the timer in the title bar that seems sick. To tell how long scripts run? So good
1
15
u/MadBoyEvo 2d ago
https://consolemonster.dev maybe it will give you some ideas