Search code examples
powershellget-childitem

Keep first layer of folders from Get-ChildItem when moving


I am working on some PowerShell script that automatically moves folders and files from the 'X-Drive' folder and move it into the 'Old' folder which also is inside the 'X-Drive' folder, but I want it to keep the first layer folders only, all what's inside can be moved but only the folder needs to be kept, but it also needs to be in the 'Old' folder.

$exclude = @('Keep 1', 'Keep 2')
Get-ChildItem -Path "C:\X-Drive" -Recurse -Exclude $exclude |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-0) } |
    Move-Item -Destination "C:\X-Drive\Old" -ErrorAction 'SilentlyContinue'

Solution

  • Enumerate the subfolders of C:\X-D_rive, then move their content to corresponding subfolders in C:\X-Drive\old, e.g. like this:

    $refdate = (Get-Date).AddDays(-1)
    Get-ChildItem 'C:\X-Drive' -Directory -Exclude $exclude | ForEach-Object {
        $dst = Join-Path 'C:\X-Drive\old' $_.Name
        If (-not (Test-Path -LiteralPath $dst)) {
            New-Item -Type Directory -Path $dst | Out-Null
        }
        Get-ChildItem $_.FullName -Recurse | Where-Object {
            $_.LastWriteTime -lt $refdate
        } | Move-Item -Destination $dst
    }
    

    You may want to add old to $excludes, BTW.

    The code assumes you're running PowerShell v3 or newer.