akimo.dev

How to replace home directory with "~" on PowerShell

PowerShell displays the current full path by default. It's long, so I'd like to replace it with ~ like Bash.

Prepare a profile

You can customize your PowerShell with $profile. It doesn't exist by default, so you need to run touch $profile.

Customize

To customize the prompt, use function prompt. Here is a built-in one.

function prompt {
    $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
      else { '' }) + 'PS ' + $(Get-Location) +
        $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}

Source:

about_Prompts - PowerShell | Microsoft Learn
docs.microsoft.com

It seems using $(Get-Location) to get the current path, but we can't use it as a string (even if we use $pwd). So let's use Convert-Path instead.

function prompt {
    $currentDir = (Convert-Path .)

    $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
      else { '' }) + 'PS ' + $currentDir +
        $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}

Now we can use $currentDir as a string. All that is left is checking if it includes $home and replacing it.

function prompt {
    $currentDir = (Convert-Path .)

    if ($currentDir.Contains($HOME)) {
        $currentDir = $currentDir.Replace($HOME, "~")
    }

    $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
      else { '' }) + 'PS ' + $currentDir +
        $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}

Afterword

This time we made just a little customize for PowerShell, but we can do more things with a profile. I'm happy if this article will be helpful for you.

Here is my profile for your reference.

akimon658/pwsh-profile: My PowerShell profile
github.com