PowerShell - Removing folder from path of string

Viewed 80

Basically I have a path "root/main/EVILFOLDER/first/second/third/etc" And I want to remove EVILFOLDER/ specifically the 3rd segment of the path. The thing is EVILFOLDER could be anything so I can't just hardcode it as such and the path length and number of "/" could be any varying length.

I have this, and it works, but elegant it is not.

$path = "root/main/EVILFOLDER/first/second/third/etc"
$basePath = "{0}/{1}/" -f $path.Split('/')
$subFolder = "{3}/" -f $shortPath.Split('/')
$subFolderIndex = $shortPath.IndexOf($subFolder)
$newPath = $basePath + $shortPath.Substring($subFolderIndex)

Ultimately I was hoping I could write it as somethingl ike "{0}/{1}/{3}... " to get the rest of the path listing. Ideas?

3 Answers

Give this a try:

'root/main/EVILFOLDER/first/second/third/etc',
'root/main/EVILFOLDEREVILFOLDEREVILFOLDER/first/',
'root/main/EVILFOLDEREVILFOLDEREVILFOLDER',
'root/main/zzz/first/second/third/etc',
'root/main/tinyEvil/aaaa/bbbb/cccc/dddd/eee' | ForEach-Object {
    $good1, $good2, $notgood, $good3 = $_ -split '(?=/)',4
    $newName = -join( $good1, $good2, $good3 )

    [PSCustomObject]@{
        OldName = $_
        NewName = $newName
    }
}

# Results

OldName                                         NewName
-------                                         -------
root/main/EVILFOLDER/first/second/third/etc     root/main/first/second/third/etc
root/main/EVILFOLDEREVILFOLDEREVILFOLDER/first/ root/main/first/
root/main/EVILFOLDEREVILFOLDEREVILFOLDER        root/main
root/main/zzz/first/second/third/etc            root/main/first/second/third/etc
root/main/tinyEvil/aaaa/bbbb/cccc/dddd/eee      root/main/aaaa/bbbb/cccc/dddd/eee

Basically we care about preserving $good1 and $good2, it may or may not be a $good3 after $notGood but this should be able to handle it.

$data = 'root/main/EVILFOLDER/first/second/third/etc' -split "/";
$data[0,1]+$data[3..$data.length] -join "/"

-split is fine but this regular expression should do the trick too :

$NewPath = $Path -replace "^([^/]+/[^/]+)/[^/]+(.*)", '$1$2'

^ start of the string

([^/]+/[^/]+) first block to keep where [^/]+ will keep any chars (at least 1) but /, so this corresponding to "any chars/any chars"

/[^/]+ chars to remove ("/any chars except /")

(.*) second block to keep : "any chars (can be no char)"

replace with $1$2 corresponding to blocks to keep 1 and 2

If your path uses backslashes, then you need to escape them in the regex : ^([^\\]+\\[^\\]+)\\[^\\]+(.*)

Related