Search code examples
powershellcommand-linedirectory-structureposh-git

Using powershell to move sub-folder contents up one level; different parent folders


I've looked through various questions on SO but can't get the script to work. New to Powershell and I'm sure this easy - any help would be great

I have a directory structure of 170 folders:

    G:\Data\ 
            folder1\
                     DCIM1\*jpgs
                     DCIM2\*jpgs

            folder2\
                     DCIM1\*jpgs
                     DCIM2\*jpgs

I would like to move all the jpgs from each DCIM subfolder into the parent folder one level up:

      G:\Data\ 
            folder1\*jpgs         
            folder2\*jpgs

Each parent folder has a different name, and potentially differently named DCIM subfolders, but all the jpgs are named with their folder prefix (e.g., DCIM1_001.jpg).

I have tried Powershell:

G:\> $files = Get-ChildItem "G:\data"
>> Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
>> $files | Remove-Item -Recurse 

but get a destination is null error. I have tried a wildcard too:

 G:\> $files = Get-ChildItem "G:\data\*"
    >> Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
    >> $files | Remove-Item -Recurse 

But I take it I have that completely wrong. What am I missing?


Solution

  • You can use Split-Path to get the parent directory:

    $JPGs = Get-ChildItem -Path "C:\brief\datefolder" -Recurse -Filter "*.jpg"
        foreach ($JPG in $JPGs) {
    
            $Parent_Directory = Split-Path -Path $JPG.FullName -Parent
            $Destination_Path = Split-Path -Path $Parent_Directory -Parent
            
            Move-Item -Path $JPG.FullName -Destination $Destination_Path
                if ($null -eq (Get-ChildItem -Path $Parent_Directory)) {
    
                    Remove-Item -Path $Parent_Directory
    
                }
        }
    

    It's just a means of assigning it to a variable and moving along the line.