简体   繁体   中英

Move folders and contents with Powershell

OK, trying to copy folders and contents from a UNC path (shared drive) to another UNC path (NAS) based on date (Before 01 Jan 2015). Yes I know the code says 2017 but once I get it working on test then I'll change the date and run on prod.

#Original file path
$path = "UNC Path"
#Destination file path
$destination = "Different UNC Path"
#It makes a filelist of what's inside the $path path
Foreach($file in (Get-ChildItem $path)) { 
#If the lastwrite time is before the given date
If($file.LastWriteTime -lt "01/01/2017") { 
#It copies the file to the destination
Copy-Item -Path $file.fullname -Destination $destination -Force } }

It copies the contents of folders fine but not the folders. I think I'm missing a -recurse but putting it after Get-ChildItem $path didn't work.

I plan to get this working then add a Remove-Item line to remove all the old items from the file server.

Thoughts? Suggestions of better ways to accomplish this?

Thanks,

I think you're just missing the -Recurse from Get-ChildItem , but I would do it like so:

Get-ChildItem -Path $Path -Recurse `
| Where-Object { $_.LastWriteTime -lt '2017-01-01' } `
| ForEach-Object {
    Copy-Item -Path $_.FullName -Destination ($_.FullName.Replace($source,$destination)) -Force;
}

If you've got hidden or system files to copy, you'll also want the -Force parameter on Get-ChildItem .

Actually, you might need to do this:

Get-ChildItem -Path $Path -Recurse `
| Where-Object { $_.LastWriteTime -lt '2017-01-01' } `
| ForEach-Object {
    if ($_.PSIsContainer -and !(Test-Path($_.FullName.Replace($source,$destination)) {
        mkdir ($_.FullName.Replace($source,$destination));
    }
    else {
        Copy-Item -Path $_.FullName -Destination ($_.FullName.Replace($source,$destination)) -Force;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM