Is there an easy way of stripping the root directory when retrieving a recursive list of files in a directory?
e.g.
Get-ChildItem -Recurse "C:\Test\Folder" | Where { ! $_.PSIsContainer } | Select FullName | Out-File "C:\Test\Folder\items.txt"
But instead of this giving me:
C:\Test\Folder\shiv.png
C:\Test\Folder\Another\kendall.png
C:\Test\Folder\YetAnother\roman.png
It gives me:
Folder\shiv.png
Folder\Another\kendall.png
Folder\YetAnother\roman.png
Is this possible in one line or do I have to write a loop?
Also is there an output method that doesn't create gaps between lines or also spit out the name of the select property at the top? (In this case 'FullName'), or would I just have to loop manually and ignore them?
CodePudding user response:
The problem you're having with the "gap" is because of Powershell's formatting when displaying objects. If you want to get the plain values, you could use the -ExpandProperty
switch:
select -Expand FullName
As for your problem though, you could do something like this:
$dir = "C:\Test\Folder"
Get-ChildItem $dir -Recurse -File | foreach {
$_.FullName.Replace("$dir\", "")
} | Out-File "C:\Test\Folder\items.txt"
Note that this would be case sensitive. If that's an issue, you could use regex:
$dir = "d:\tmp"
$pattern = [Regex]::Escape($dir) "\\?"
Get-ChildItem $dir -Recurse -File | foreach {
$_.FullName -replace $pattern, ""
}
CodePudding user response:
This does what you ask:
Get-ChildItem -Recurse "C:\Test\Folder" | Where { ! $_.PSIsContainer } | Select -ExpandProperty FullName | % { $_.Split("\")[2..1000] -Join "\" }
Output:
Folder\shiv.png
Folder\Another\kendall.png
Folder\YetAnother\roman.png
Explanation:
The result of Get-ChildItem
is split on the \
character which returns an array. The next bit [2..1000]
slices the array from element 2 (and the rest of the array up until the specified number, so just take a sufficiently large number). Finally we join the array into a new string with the -Join
operator.