lavacode
lavacode

Reputation: 155

How to remove partial path from Get-Location output?

I'm trying to write a custom prompt for PowerShell and I was wondering how I would filter out the 1...n directories in the output of Get-Location.

function prompt {
  "PS " + $(get-location) + "> "
}

So, if the path is too long I would like to omit some of the directories and just display PS...blah\blah> or something. I tried (get-container) - 1 but it doesn't work.

Upvotes: 3

Views: 347

Answers (3)

Ansgar Wiechers' answer will give you the last directory but if you want a way to do multiple directories at the end of the filepath (using the triple dot notation) you can cast the directory path to a uri and then just get and join the segments:

function prompt {
    $curPath = pwd
    $pathUri = ([uri] $curPath.ToString())

    if ($pathUri.Segments.Count -le 3) {
        "PS {0}>" -f $curPath
    } else {
        "PS...{0}\{1}>" -f $pathUri.Segments[-2..-1].trim("/") -join ""
    }
}

Or using just a string (no uri cast)

function prompt {
        $curPath = pwd
        $pathString = $curPath.Tostring().split('\') #Changed; no reason for escaping

        if ($pathString.Count -le 3) {
            "PS {0}>" -f $curPath
        } else {
            "PS...{0}\{1}>" -f $pathString[-2..-1] -join ""
        }
    }

$a = prompt
Write-Host $a

Then just change -2 to whatever you want to be the first directory and -le 3 to match. I typically use the uri cast when I have to run stuff through a browser or over connections to Linux machines (as it uses "/" as a path separator) but there is no reason to not use the string method for normal operations.

Upvotes: 1

Matt
Matt

Reputation: 46710

I wanted to make a more dynamic function. I do just basic string manipulation. You could do some logic nesting Split-Path but the string manipulation approach is just so much more terse. Since what you want to be returned wont be a fully validated path I feel better offering this solution.

Function Get-PartialPath($path, $depth){
    If(Test-Path $path){
        "PS {0}>" -f (($path -split "\\")[-$depth..-1] -join "\")
    } else {
        Write-Warning "$path is not a valid path"
    }
}

Sample Function call

Get-PartialPath C:\temp\folder1\sfg 2
PS folder1\sfg>

So you can use this simple function. Pass is a string for the path. Assuming it is valid then it will carve up the path into as many trailing chunks as you want. We use -join to rebuild it. If you give a $depth number that is too high the whole path will be returned. So if you only wanted to have 3 folders being shown setting the $depth for 3.

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200213

Use Split-Path with the -Leaf parameter if you want just the last element of a path:

function prompt {
  "PS {0}> " -f (Split-Path -Leaf (Get-Location))
}

Upvotes: 3

Related Questions