Normally I wouldn't even post without some framework together, but I'm stumped on where to begin.
I have a directory of hundreds of subfolders that should only be one level deep but some are two levels deep:
- C:\MainDirectory\SubfolderA\
- C:\MainDirectory\SubfolderB\
- C:\MainDirectory\SubfolderC\
- C:\MainDirectory\SubfolderC\SubfolderC1\
I need to recursively go through the MainDirectory, and if there's a second sublevel of files, then move just those files up one level (so that SubfolderC1's files are actually placed in SubfolderC) and then those files need to have SubFolderC1's name appended to the front of the file.
Ex:
- C:\MainDirectory\SubfolderC\SubfolderC1\FileA.type
would become:
- C:\MainDirectory\SubfolderC\SubfolderC1FileA.type
I don't know the subfolders or filenames ahead of time, they could be named anything.
The following feels like a start.
$source = "C:\MainDirectory"
$levels = Get-ChildItem $source -Directory -Recurse | ForEach-Object {$_.PSPath.Split('\').Count}
if ($levels -gt 3) {
}
But I don't know how to use the results for anything meaningful.
Editing to add progress. This seems to at least tell me what directory exceeds the threshold:
Get-ChildItem $source -Directory -Recurse | ForEach-Object {$path = $_.FullName; $levels = $_.PSPath.Split('\').Count;
if ($levels -gt 3){
Write-Output $path
}
}
Now I just need to use $path to get the corresponding child file, move it up a directory, rename it based off of its former parent folder.
Edited - Progress has been made:
$source = "C:\MainDirectory"
Get-ChildItem $source -Recurse | ForEach-Object {
$components = $_.FullName.Split("\")
$levels = $components.Count
if ($levels -gt 3) {
Write-Output $_.FullName
}
}
Now I just need to move the files up one level and rename them.
ETA: Last Revision for the time being. I hate to do it, but if I just re-run the script at the end then I can move the files up another directory with Split-Path function:
$gparentdir = Split-Path (Split-Path -parent $_.FullName) -Parent
The whole process is dirty and inelegant and any cleaning up would be great but I'll paste what I got as my answer.