0

I have found a powershell function, which virtually does what I need, but not quite...

I want to find all child folders within a parent that ONLY have one file inside.

I have found some code which sucesfully finds all the correct children folders, now I'm not too sure how to do the move...

I've created a 'Foreach' loop, but not sure entirely how to move.... would Move-Item do it? Not sure

Please help

$RootFolder = "c:\myfolder"
$FoldersWithOnlyOneFile = Get-ChildItem $RootFolder -Recurse | `
    Where {$_.PSIsContainer -and @( Get-ChildItem $_.Fullname | Where {!$_.PSIsContainer}).Length -eq 1 `
                            -and @( Get-ChildItem $_.Fullname | Where {$_.PSIsContainer}).Length -eq 0 }


Foreach($folder in $FoldersWithOnlyOneFile)
{
    $Folder.FullName
   Get-ChildItem $Folder.FullName
}

2 Answers 2

0

Within your 2nd foreach loop use some combination of the following

$file = Get-ChildItem $Folder.FullName
move-item   $file.Fullname "C:\some\where\else" # moves only the file
remove-item $folder.Fullname                    # remove empty source dir after file move
move-item $folder.Fullname "C:\some\where\else" # moves the folder and the file
0

use the following as the lower part of your script:

$destinationRoot = "C:\some\where\else"
ForEach($folder in $FoldersWithOnlyOneFile)
{   
   # the folder to move to
   $destinationFolder = "$destinationRoot\$($Folder.Name)"
   # if it not exists, create the folder
   if (!(Test-Path $destinationFolder))
   {
        New-Item -Path $destinationFolder -ItemType Directory 
   }
   # move the single file (works with multiple too) to the destination
   Get-ChildItem $Folder.FullName -File | Move-Item -Destination $destinationFolder
   # remove the now empty original folder
   Remove-Item $Folder.FullName
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .