Mastering Set-PSReadLineKeyHandler: Customize Your PowerShell Experience
Welcome back to Wahman’s PowerShell blog! Today we’re diving into a powerful cmdlet that can dramatically enhance your command line productivity: Set-PSReadLineKeyHandler.
If you’ve ever wanted to customize the behavior of your PowerShell console, remap keys, or even create your own hotkeys — this cmdlet is your best friend.
What is Set-PSReadLineKeyHandler?
Set-PSReadLineKeyHandler allows you to bind keystrokes to custom behavior (called a key handler). This enables everything from simple key reassignments to advanced scripting triggered by key presses.
Official description: “Binds keys to user-defined or PSReadLine key handler functions.”
Basic Usage
The syntax is simple:
Set-PSReadLineKeyHandler -Key <ConsoleKey>[-Chord ...] -Function <string> [-BriefDescription <string>] [-Description <string>]
or for a script block:
Set-PSReadLineKeyHandler -Key <ConsoleKey> -ScriptBlock { your code }
Examples
1. Beginner: Clear the screen with Ctrl+L
Similar to Linux terminals, bind Ctrl+L to clear the screen:
Set-PSReadLineKeyHandler -Key Ctrl+L -Function ClearScreen
Now hitting Ctrl+L will clear your console – no more typing cls!
2. Intermediate: Insert current date/time with F5
This example adds a script block that inserts the current date/time at the cursor when you hit F5.
Set-PSReadLineKeyHandler -Key F5 -ScriptBlock {
[System.Console]::Write("$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')")
}
Great when you’re adding timestamps to logs or notes.
3. Advanced: Toggle directory view with Ctrl+D
Bind Ctrl+D to display the current directory contents via Get-ChildItem:
Set-PSReadLineKeyHandler -Key Ctrl+D -ScriptBlock {
Get-ChildItem | Out-Host
}
This gives you a bash-like quick directory view.
4. Expert: Clipboard integration with Ctrl+Shift+V
Let’s map Ctrl+Shift+V to paste clipboard content into the console with proper escaping:
Set-PSReadLineKeyHandler -Chord Ctrl+Shift+V -ScriptBlock {
$clipboard = Get-Clipboard
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($clipboard)
}
This turns your PowerShell into a clipboard-friendly environment!
Remove Custom Binds
If you’d like to remove a keybinding:
Remove-PSReadLineKeyHandler -Key Ctrl+L
Wrap Up
Set-PSReadLineKeyHandler is a must-know for anyone looking to enhance their PowerShell experience. Whether it’s remapping common tasks or building advanced shortcuts, it can save time and make your console environment truly your own.
Happy scripting, and I will see you in the next post!
Leave a Reply