Home > Net >  Execute command by pressing enter with no input in PowerShell
Execute command by pressing enter with no input in PowerShell

Time:03-11

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?

CodePudding user response:

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()
}
  • Related