How can I remove a partial path from the Get-Location output?

I am trying to write a custom prompt for PowerShell and I was wondering how I am filtering out 1 ... n directories in the output 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 show PS...blah\blah>

or whatever. I tried (get-container) - 1

it but it doesn't work.

+3


source to share


3 answers


Ansgar Wicher's answer will give you the last directory, but if you want to make multiple directories at the end of the file path (using 3-dot notation) you can pass the directory path to the 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)



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 usually use a uri cast when I have to run stuff through the browser or across connections to Linux machines (since it uses "/" as the path separator), but there's no reason not to use the string method for normal operations.

+1


source


Use Split-Path

with a parameter -Leaf

if you only want the last element of the path:



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

      

+3


source


I would like to make a more dynamic function. I am just using inline manipulation. You can do some nesting logic Split-Path

, but the string manipulation approach would be much more concise. Since what you want to return will not be a fully tested path, I would rather suggest 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"
    }
}

      

Function call example

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's valid, it will carve the path into as many tail-pieces as you like. We will use -join

it to restore it. If you provide a number $depth

that is too high, the entire journey will be refunded. So if you only wanted to have 3 folders showing installation $depth

for 3.

+2


source







All Articles