Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell how to make the prompt change on key press?

I'm new to Powershell. I'm trying to create my own custom prompt that shows a truncated version of the current dir unless you expand it by pressing CTRL + R. Moreover, I would like to do this:

$short\dir\path...>
*user presses CTRL+R*
$really\really\long\full\dir\path>
*Full dir path is shown as long as CTLR + R is held down*
like image 678
coderrick Avatar asked Aug 09 '15 02:08

coderrick


People also ask

How do I simulate a keystroke in PowerShell?

The tilde (~) represents the ENTER keystroke. You can also use {ENTER} , though they're not identical - that's the keypad's ENTER key.

How do I wait for input in PowerShell?

Use Read-Host to Enable the press any key to continue in the PowerShell. Read-Host is the most common method to prompt user input. You can use this method to pause the execution when prompting user input in the PowerShell. After pressing the key, you need to press Enter to exit the pause mode.


1 Answers

This isn't a super elegant solution, but it basically turns Ctrl + Alt + R into a hotkey for displaying the current directory. You can change the chord to "Ctrl+R" but you'll be overwriting a default PSReadlineKeyHandler for powershell. It looks like it gets stuck on the command, but if you begin typing the next line will appear. You will need to add both of these to your Microsoft.Powershell_Profile.ps1 located in $env:USERPROFILE\Documents\WindowsPowershell\

function prompt {
    if(($pwd | split-path -Parent | Split-Path -Leaf) -match ':')
    {
        "$pwd\>"
    }
    elseif (($pwd | Split-Path -Leaf) -match ':')
    {
        "$pwd>"
    }
    else {
        "...\$($pwd | split-path -Parent | Split-Path -Leaf)\$($pwd | Split-path -Leaf)\>"
    }
}

Set-PSReadlineKeyHandler -Chord "Ctrl+Alt+R" -ScriptBlock {
    write-host $pwd -nonewLine
}

Hopefully that helps!

like image 121
HeedfulCrayon Avatar answered Oct 04 '22 22:10

HeedfulCrayon