If you are a Windows user who wants to enjoy some of the features of bash, such as syntax coloring, history search, and customizable key bindings, you might be interested in PSReadLine. PSReadLine is a PowerShell module that provides a bash-inspired readline implementation for Windows. It enhances the command-line editing experience of PowerShell and makes it more interactive and user-friendly.
In this blog post, we will show you how to install and use PSReadLine for bash on Windows. We will also share some tips and tricks to make the most of this module and improve your productivity. By the end of this post, you will be able to:
- Install PSReadLine on Windows
- Configure PSReadLine settings and options
- Use PSReadLine key bindings and functions
- Customize PSReadLine prompt and colors
- Troubleshoot common PSReadLine issues
Table of Contents
What is PSReadLine?
PSReadLine is a PowerShell module that provides a bash-inspired readline implementation for Windows. Readline is a library that allows users to edit commands using keyboard shortcuts and provides features such as history search, completion, and undo/redo. Bash, the default shell in Linux and macOS, uses readline to enhance its command-line interface.
PSReadLine was created by Jason Shirk in 2013 as an open-source project on GitHub. It aims to bring some of the benefits of readline to PowerShell users on Windows. Some of the features of PSReadLine include:
- Syntax coloring: PSReadLine highlights commands, parameters, variables, operators, and other elements with different colors to make them easier to read and debug.
- Simple syntax error notification: PSReadLine underlines syntax errors with red squiggles and shows a tooltip with the error message when you hover over them.
- A good multi-line experience: PSReadLine allows you to edit multi-line commands with ease. You can move the cursor across lines, insert or delete lines, and copy or paste lines.
- Customizable key bindings: PSReadLine supports two modes of key bindings: Emacs and Windows. Emacs mode mimics the key bindings of Emacs, a popular text editor in Linux. Windows mode uses the key bindings that are familiar to Windows users. You can also create your own key bindings or modify the existing ones.
- Many configuration options: PSReadLine lets you customize various aspects of its behavior and appearance, such as history size, edit mode, prompt function, colors, bell style, and more.
- Bash style completion: PSReadLine offers a menu-based completion system that shows a list of possible completions when you press Tab. You can select a completion with the arrow keys or type a filter string. You can also cycle through completions with Tab or Shift+Tab.
- Bash/zsh style interactive history search: PSReadLine allows you to search through your command history interactively by pressing Ctrl+R or Ctrl+S. You can type a partial command or a keyword and PSReadLine will show the matching commands from your history. You can also navigate through the matches with the arrow keys or Ctrl+R/Ctrl+S.
How to Install PSReadLine on Windows
If you are using Windows 10 or PowerShell 6+, you don’t need to install PSReadLine because it is already included in your system. However, if you are using an older version of Windows or PowerShell, you will need to install it manually.
To install PSReadLine on Windows, you will need to use PowerShellGet, a module that lets you install PowerShell modules from online repositories. PowerShellGet is included in Windows 10 and PowerShell 6+, but if you are using an older version of Windows or PowerShell, you will need to install it first by following these instructions.
Once you have PowerShellGet installed, you can install PSReadLine by running this command in PowerShell:
Install-Module -Name PSReadline -Scope CurrentUser -Force -SkipPublisherCheck
This command will download and install the latest version of PSReadLine from the PowerShell Gallery, an online repository for PowerShell modules. The -Scope CurrentUser parameter specifies that the module will be installed only for the current user account. The -Force parameter overrides any prompts or warnings during the installation process. The -SkipPublisherCheck parameter skips the verification of the publisher’s digital signature.
To verify that PSReadLine is installed correctly, run this command in PowerShell:
Get-Module -Name PSReadline
This command will show information about the PSReadLine module, such as its name, version, path, and exported commands. If you see something like this, it means that PSReadLine is installed successfully:
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.2.0 PSReadline {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler...}
How to Configure PSReadLine Settings and Options
PSReadLine has many settings and options that you can configure to customize its behavior and appearance. You can view the current settings and options by running this command in PowerShell:
Get-PSReadLineOption
This command will show the values of various PSReadLine options, such as EditMode, HistorySaveStyle, ContinuationPrompt, Colors, and more. For example, you might see something like this:
EditMode : Windows
AddToHistoryHandler :
HistoryNoDuplicates : True
MaximumHistoryCount : 4096
HistorySearchCursorMovesToEnd : False
HistorySearchCaseSensitive : False
HistorySaveStyle : SaveIncrementally
HistorySavePath : C:\Users\user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
...
To change the value of an option, you can use the Set-PSReadLineOption command with the name and value of the option as parameters. For example, to change the edit mode from Windows to Emacs, you can run this command:
Set-PSReadLineOption -EditMode Emacs
To change the color of a syntax element, you can use the Set-PSReadLineOption command with the -Colors parameter and a hashtable that maps the element name to the color value. For example, to change the color of commands from yellow to green, you can run this command:
Set-PSReadLineOption -Colors @{ Command = 'Green' }
You can find the list of available syntax elements and color values in the documentation.
To make your PSReadLine settings and options persistent across sessions, you will need to add them to your PowerShell profile. A PowerShell profile is a script that runs every time you start a new PowerShell session. You can use it to customize your PowerShell environment and load modules, functions, aliases, and variables.
To find the path of your PowerShell profile, run this command in PowerShell:
$profile
This command will show something like this:
C:\Users\user\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If the file does not exist, you can create it by running this command:
New-Item -Path $profile -ItemType File -Force
Then, you can edit the file with your preferred text editor and add your PSReadLine settings and options as commands. For example, your profile might look something like this:
Import-Module PSReadline
Set-PSReadLineOption -EditMode Emacs
Set-PSReadLineOption -Colors @{
Command = 'Green'
Parameter = 'Cyan'
Operator = 'Magenta'
}
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineKeyHandler -Key Ctrl+r -Function ReverseSearchHistory
Set-PSReadLineKeyHandler -Key Ctrl+s -Function ForwardSearchHistory
Set-PSReadLineKeyHandler -Key Ctrl+o -ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$line`n")
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
The last command in this example is a custom key binding that executes the current line and inserts a new line below it. This is useful for running commands without leaving a blank line in the history.
After saving your profile, you can reload it by running this command in PowerShell:
. $profile
Alternatively, you can restart your PowerShell session to apply the changes.
How to Use PSReadLine Key Bindings and Functions
PSReadLine provides many key bindings and functions that allow you to edit commands using keyboard shortcuts. You can view the current key bindings by running this command in PowerShell:
Get-PSReadLineKeyHandler
This command will show a table of key bindings and their corresponding functions. For example, you might see something like this:
Key Function Description
--- -------- -----------
Ctrl+a BeginningOfLine Move the cursor to the start of the line.
Ctrl+b BackwardChar Move the cursor back one character.
Ctrl+c CopyOrCancelLine Copy the region to the clipboard, or if no region is active, cancel editing the line with CancelLine.
Ctrl+d DeleteCharOrExit Delete the character under the cursor, or if the line is empty, exit the shell.
Ctrl+e EndOfLine Move the cursor to the end of the line.
Ctrl+f ForwardChar Move the cursor forward one character.
Ctrl+h BackwardDeleteChar Delete the character before the cursor.
Ctrl+k KillLine Cut the text from the cursor to the end of the line.
Ctrl+l ClearScreen Clear the screen, leaving the current input at the top of the screen.
Ctrl+m AcceptLine Attempt to execute the current input as a command.
Ctrl+n NextHistory Replace the current input with the next item from PSReadline history.
Ctrl+p PreviousHistory Replace the current input with the previous item from PSReadline history.
...
You can use these key bindings to perform various editing operations on your commands, such as moving the cursor, deleting or inserting characters, copying or pasting text, searching or replacing text, and more.
You can also create your own key bindings or modify the existing ones by using the Set-PSReadLineKeyHandler command. This command takes a -Key parameter that specifies the key combination and a -Function parameter that specifies the function to bind. For example, to bind Ctrl+o to a function that executes the current line and inserts a new line below it, you can run this command:
Set-PSReadLineKeyHandler -Key Ctrl+o -ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$line`n")
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
The -ScriptBlock parameter allows you to specify a custom code block that defines the function logic. You can access some of the PSReadLine internal methods and properties by using [Microsoft.PowerShell.PSConsoleReadLine]:: syntax.
You can find the list of available key bindings and functions in the documentation.
How to Customize PSReadLine Prompt and Colors
PSReadLine also allows you to customize your PowerShell prompt and colors. The prompt is the text that appears before your command input, usually indicating your current location, user name, and other information. The colors are used to highlight different syntax elements in your commands, such as commands, parameters, variables, operators, and more.
To customize your prompt, you can use the Set-PSReadLineOption command with the -PromptText parameter and a string that defines your prompt format. For example, to change your prompt to show your user name, computer name, and current time in brackets, you can run this command:
Set-PSReadLineOption -PromptText "[$env:USERNAME@$env:COMPUTERNAME $(Get-Date -Format HH:mm:ss)]$ "
The $env:USERNAME and $env:COMPUTERNAME variables are built-in environment variables that store your user name and computer name. The $(Get-Date -Format HH:mm:ss) expression is a subexpression that evaluates to the current time in hours, minutes, and seconds. The $ symbol at the end indicates where your command input starts.
To customize your colors, you can use the Set-PSReadLineOption command with the -Colors parameter and a hashtable that maps syntax element names to color values. For example, to change your colors to use a dark theme with blue commands, yellow parameters, green variables, and red operators, you can run this command:
Set-PSReadLineOption -Colors @{
Command = 'Blue'
Parameter = 'Yellow'
Variable = 'Green'
Operator = 'Red'
}
You can find the list of available syntax element names and color values in the documentation.
To make your prompt and colors persistent across sessions, you will need to add them to your PowerShell profile as explained in the previous section.
How to Troubleshoot Common PSReadLine Issues
PSReadLine is a powerful and useful module that enhances your PowerShell experience, but it is not perfect. Sometimes, you might encounter some issues or errors when using PSReadLine. Here are some of the common PSReadLine issues and how to troubleshoot them:
PSReadLine is not loaded or enabled: If you don’t see any syntax coloring or key bindings when using PowerShell, it might be because PSReadLine is not loaded or enabled. To check if PSReadLine is loaded, run this command:
Get-Module -Name PSReadline
If you don’t see any output, it means that PSReadLine is not loaded. To load it, run this command:
Import-Module PSReadline
If you see an error message like this, it means that PSReadLine is not installed or not found:
Import-Module : The specified module 'PSReadline' was not loaded because no valid module file was found in any module directory.
To install PSReadLine, follow the instructions in the installation section.
If you see an output like this, it means that PSReadLine is loaded but not enabled:
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.2.0 PSReadline {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler...}
To enable PSReadLine, run this command:
Set-PSReadlineOption -Enable
This command will enable PSReadLine for the current session. To make it permanent, add it to your PowerShell profile.
PSReadLine throws an error or exception: If you see an error or exception message from PSReadLine when using PowerShell, it might be because of a bug or a conflict with another module or function. To troubleshoot this issue, you can try the following steps:
Update PSReadLine to the latest version by running this command:
Update-Module -Name PSReadline -Force
This command will download and install the latest version of PSReadLine from the PowerShell Gallery. The -Force parameter overrides any prompts or warnings during the update process.
Disable or remove any other modules or functions that might interfere with PSReadLine by running these commands:
Get-Module | Where-Object { $_.Name -ne 'PSReadline' } | Remove-Module -Force
Get-Command | Where-Object { $_.CommandType -eq 'Function' } | Remove-Item -Force
These commands will remove all modules except PSReadLine and all functions from the current session. The -Force parameter overrides any prompts or warnings during the removal process.
Restart your PowerShell session and try again.
If none of these steps resolve the issue, you can report it to the PSReadLine GitHub repository. You can also search for existing issues or solutions there.
Summary
In this blog post, we have shown you how to use PSReadLine for bash on Windows. We have covered how to install and configure PSReadLine settings and options, how to use PSReadLine key bindings and functions, how to customize PSReadLine prompt and colors, and how to troubleshoot common PSReadLine issues. We hope that this post has helped you to improve your PowerShell experience and productivity.
Disclaimer: The information provided in this blog post is for educational purposes only. We are not affiliated with or endorsed by Microsoft, PowerShell, or PSReadLine. We do not guarantee the accuracy, completeness, or reliability of the information in this post. Use it at your own risk.