r/PowerShell • • 13d 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. 😂

82 Upvotes

52 comments sorted by

View all comments

6

u/wonkifier 12d ago edited 12d 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/BlackV 12d ago

Nice, that sounds useful

2

u/Incrediblecodeman 12d ago

Oh heck! Can you show a sample please dude that’s fuck as fuck

2

u/wonkifier 12d 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

u/Incrediblecodeman 12d ago

That’s! Wow we can really do like ….. anything we want.

1

u/MonkeyNin 11d 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 \a and the terminal can play a "work complete" sound