Reputation: 1
I need to find how deep does the folder go at a given path. The issue is that the script refuses to work at all. It prints nothing not a single line.
$nmlfpEngD = "\\nml-fp\EngDesignLib\"
$nmlfPrdD = "\\nml-fp\PrdDesignLib\"
$csvFilePath = "\\nml-fp\Users\Scripts\Scripts\Aras\CSVOutput\GetSubFolders.csv"
$subfolders = Get-ChildItem -Path $nmlfpEngD* -Directory -Recurse -Force
foreach ($subfolder in $subfolders) {
$resultObject = [PSCustomObject]@{
StringCount = $subfolder.FullName.ToString().Split('\').Count
SubfolderName = $subfolder.Name
Path = $subfolder.FullName
#Exists = 1
}
$resultObject | Export-Csv -Path $csvFilePath -NoTypeInformation -Append
Write-Host $resultObject
}
When Recurse
is removed it gets the folder names at depth level 1. But this defeats the purpose.
Is this not the correct use of Recurse
?
Upvotes: 0
Views: 223
Reputation: 61208
Personally, I like using LiteralPath
rather than Path
on UNC paths, but that does not explain why your code fails to write to the file.
When using the -Recurse
switch, there is no need to end the path with \*
.
Also, I would use Select-Object
here instead of a foreach loop and have it create the objects to collect in a variable using calculated properties.
Then write the whole thing out in one go to the CSV file.
Please try
$nmlfpEngD = '\\nml-fp\EngDesignLib'
$nmlfPrdD = '\\nml-fp\PrdDesignLib'
$csvFilePath = '\\nml-fp\Users\Scripts\Scripts\Aras\CSVOutput\GetSubFolders.csv'
$dirsep = [System.IO.Path]::DirectorySeparatorChar
# you can give both paths to Get-ChildItem as array by simply adding a comma in between
$result = Get-ChildItem -LiteralPath $nmlfpEngD, $nmlfPrdD -Directory -Recurse |
# because these are UNC paths, we need to trim off the first two backslashes
Select-Object @{Name = 'StringCount'; Expression = {$_.FullName.Trim($dirsep).Split($dirsep).Count}},
@{Name = 'SubfolderName'; Expression = {$_.Name}},
@{Name = 'Path'; Expression = {$_.FullName}}
# output on screen
$result | Format-Table -AutoSize
# output to Csv
$result | Export-Csv -LiteralPath $csvFilePath -NoTypeInformation
Upvotes: 0