Reputation: 89
I want to split directory path using power shell. My full path is D:\data\path1\path2\abc.txt and i want to split it to path2\abc.txt. Can someone let me know how can I do that.
Upvotes: 2
Views: 14472
Reputation: 1
Sorry for the super late post! I think you may have got the fix. But here is something you can try.
You can try using the substring() function as well.
$fullPath = "D:\data\path1\path2\abc.txt"
$rootPath = "D:\data\path1\"
$filePath = $fullPath.substring($rootPath.length, ($fullPath.length - $rootPath.length) )
Something like this may help you.
Upvotes: 0
Reputation: 12319
$last2parts = "D:\data\path1\path2\abc.txt".Split("\") | Select-Object -Last 2
$last2parts -join "\"
In reply to your comment on another solution try this. Just remove your constant d:\data\path1. Then perform the split
$last2parts = "D:\data\path1\path2\abc.txt".Replace("D:\data\path1","")
$last2parts =$last2parts.Split("\") | Select-Object -Last 2
$last2parts -join "\"
Or try perhaps this if you want everything after D:\data\path1
$lastparts = "D:\data\path1\path2\abc.txt".Replace("D:\data\path1","")
$lastparts =$lastparts.Split("\")
$lastparts -join "\"
Upvotes: 2
Reputation: 2379
$PathAsString = "D:\data\path1\path2\abc.txt"
[System.IO.Path]::Combine($(Split-Path -leaf $(Split-Path $PathAsString)),$(Split-Path -leaf $PathAsString))
Uses the system's delimiter rather than specifying Windows' '\' character. Honestly if I knew this was only ever going to run on Windows systems I'd go with @ChiliYago's answer since you can't put the path delimiter character in a file or directory name like you can in Linux.
Upvotes: 1