DEV Community

Akimo
Akimo

Posted on • Originally published at akimon658.github.io

3 3

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) { '>>' }) + '> '
}
Enter fullscreen mode Exit fullscreen mode

Source: about Prompts - PowerShell | Microsoft Docs

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) { '>>' }) + '> '
}
Enter fullscreen mode Exit fullscreen mode

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) { '>>' }) + '> '
}
Enter fullscreen mode Exit fullscreen mode

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.

github.com/akimon658/pwsh-profile

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay