I have this simple cmdlet that correctly copies files and folders to a second directory:
Copy-Item -Path 'G:\xyz\Test\A' -Recurse -Destination 'G:\xyz\Test\B\'
However I am unable to tweak it to only copy the latest file in each folder within its folder (i.e. also copying the folder structure). I have written the following, but this doesn't copy folder names and does not go down all the hierarchies of sub-folders.
Get-ChildItem -Path 'G:\xyz\Test\A' -Directory | ForEach-Object {
Get-ChildItem -Path 'G:\xyz\Test\A' -File -Recurse |
Sort-Object LastWriteTime | Select-Object -Last 1 |
Copy-Item -Destination 'G:\xyz\Test\B\'
}
Could someone please identify my errors!