'Execute command by pressing enter with no input in PowerShell
This is a PowerShell version of this question. I would like PowerShell to do ls whenever I press enter without any text typed in the prompt. How to achieve it?
Solution 1:[1]
The following code uses Set-PSReadLineKeyHandler to define a script block to be run on Enter. You may put it into your $Profile file to have it always available.
Tested using Windows PowerShell 5.1 and PowerShell Core 7.2.1.
Set-PSReadLineKeyHandler -Chord Enter -ScriptBlock {
# Copy current command-line input
$currentInput = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $currentInput, [ref] $null)
# If command line is empty...
if( $currentInput.Length -eq 0 ) {
# Enter new console command
[Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, 0, 'Get-ChildItem')
}
# Simulate pressing Enter
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
