Powershell split-path formatting

formattingpathpowershell

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

Best Answer

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