0

I'm having some issues on some of the formatting. My code looks for the new files in a folder structure and returns those items, but I would like to trim the result to only show the first 3 folders in the path. Is there anyway to do this using split-path? Example:

What I have returned in the File is: \\Folder1\Folder2\Folder3\Folder4\File.txt

What I would like to see after the split-path is: \\Folder1\Folder2\Folder3
code:

$File = Get-ChildItem -File -Recurse $Path | Where { $_.LastWriteTime -ge (Get-Date).Addminutes(-5) } 

foreach ($item in $file){

$ItemDirectory = $Item.Directory 
$result = split-path $ItemDirectory -Parent
$result    

Thanks

2

This should work regardless of how many sub folders are in the path:

$result = $ItemDirectory
While (($result -split '\\' | ? { $_ }).Count -gt 3) {
   $result = Split-Path $result -Parent
}
$result
|improve this answer|||||
  • To make use the 4th folder can I just change the 3 to a 4? – psstdnt Jan 28 '16 at 23:10
  • Yes, the 3 represents folder depth so change that to expand the result. – xXhRQ8sD2L7Z Jan 29 '16 at 1:07
0

You might want to try
$result = split-path (split-path $itemDirectory -parent)

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.