2

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?

1 Answer 1

5

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.