Steve Harrison
Steve Harrison

Reputation: 23

Split and append paths

I have a scenario where i have a variable ($patharray) containing an array of paths. eg:

/Partners/ftpuser1/Reports/ 
/Partners/ftpuser2/Jan2016/29.01.2016/    
/Partners/ftpuser2/Jan2016/30.01.2016/ 
/Partners/Ftpuser3/January 2016/29.1.16/ 
/Partners/ftpuser4/January 16/ 
/Partners/ftpuser5/TS 2016/January/2901/ 
/Partners/ftpuser5/TS 2016/January/3001/

from this I need to create a new array by splitting each path down to first folder, then firstfolder/second folder and so on. so for above it would need to be:

/Partners
/Partners/ftpuser1
/Partners/ftpuser1/Reports
/Partners
/Partners/ftpuser2
/Partners/ftpuser2/Jan2016
/Partners/ftpuser2/Jan2016/30.01.2016
/Partners
/Partners/ftpuser3
/Partners/ftpuser3/January 2016
...

Although I can happily split the array by something like:

$newpatharray = $patharray -split "/"

I'm not sure how I can iterate in such a way to combine the various strings for each object in $patharray to get the output format I need. It would need to account for any path depth as well.

Can anyone please assist?

Upvotes: 2

Views: 59

Answers (2)

Matt
Matt

Reputation: 46710

A simple method that works on one string would be something like this:

$path = "/Partners/ftpuser1/Reports/" 

# The where-object will drop the leading and trailing entries from the splits. 
$split = $path -split "/" | Where-Object{![string]::IsNullOrWhiteSpace($_)}
for($splitIndex = 0; $splitIndex -lt $split.Count; $splitIndex++){
    # Need to add back leading slash

    "/" + ($split[0..$splitIndex] -join "/")
}

Could easily wrap that up in a ForEach-Object to process many paths.

A loop involving Split-Path might be more reliable for this (I got my hand slapped for string manipulation on paths once). You would have to changes the slashes of the output though as Split-Path would reverse them.

function Split-PathRecursive($path){
    # Split the path to get the parent
    $parent = Split-Path $path -Parent

    if($parent -ne "\"){
        # The parent is not the root path. Continue to process.
        $parent
        Split-PathRecursive $parent
    }
}

$pathArray = .....

$pathArray | ForEach-Object{
    # Get all the parent paths. Also need to change the slashes and how it is sorted.
    (Split-PathRecursive $_) -replace "\\","/" | Sort-Object
    # Display the full path as well
    $_
}

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200433

Split each path, then recombine its elements. Try something like this:

$patharray | ForEach-Object {
  $a = $_.TrimEnd('/') -split '/'
  for ($i=1; $i -lt $a.Count; $i++) {
    $a[0..$i] -join '/'
  }
}

Upvotes: 2

Related Questions