Hey Powershell Peeps. Was curious if/when Powershell will get a bash style command substitution?
In Linux, I can have something like the below:
root$: systemctl status httpd
root$: ^status^restart
That allows to quickly rerun commands with different options. I’d love to see this with Powershell, but it appears to be missing.
I have found you can use something like the below, but it’s not as simple, and almost not worth the effort:
*Invoke-Expression ((Get-History -Count 1).CommandLine -replace ‘status’,‘restart’)
*
I believe you must be running PowerShell core on Linux. I am very new to Linux but what I have found is that, 1. PSReadline doesn’t seem to load automatically the first time on Linux you have to Import the module manually. (Import-Module PSReadline) 2. There’s a PowerShell module called PSCompletions that may add some additional behavior like you might be looking for. (Install-Module PSCompletions).
There are plenty of other shells or terminals than what come with your distro and desktop environment (DE). There’s Ghosty and Micro https://micro-editor.github.io/ to name a couple. In my research there are a ton if you like the extremly busy and colorful terminals. I’m more of a minimalist when it comes to that stuff. On the Windows side there are third party terminals too. There was a cool one I played with called cursor, when it was in BETA, but now they’ve added AI and they want money for it.
But yes PowerShell has ways to remember previous commands once you get PSReadline working and maybe even some third party modules that make it behave more like a Linux konsole/terminal/shell.
Option 3: Bring the ^ Operator to PowerShell (Custom Function)
If you want to replicate the exact Bash behavior, add a short function to your PowerShell profile.
Open your profile script by running:
powershell
notepad $PROFILE
Use code with caution.
Paste the following function inside the file, which acts as a quick-replacement runner:
powershell
function r^ {
param([string]$ReplacementString)
# Split by the caret character
$parts = $ReplacementString -split '\^'
if ($parts.Count -lt 2) {
Write-Warning "Format must be: r^ old^new"
return
}
$old = $parts[0]
$new = $parts[1]
# Grab the last executed command from PSReadLine history
$lastCmd = (Get-PSReadLineHistory)[-1].CommandLine
# Perform the string replacement
if ($lastCmd -match [regex]::Escape($old)) {
$newCmd = $lastCmd -replace [regex]::Escape($old), $new
Write-Host "Running: $newCmd" -ForegroundColor Cyan
Invoke-Expression $newCmd
} else {
Write-Warning "Could not find '$old' in the previous command."
}
}
Use code with caution.
Save the file and restart PowerShell or reload your profile (. $PROFILE).