使用Powershell移动文件夹和内容

时间:2016-04-11 15:04:34

标签: powershell

好的,尝试根据日期(2015年1月1日之前)将文件夹和内容从UNC路径(共享驱动器)复制到另一个UNC路径(NAS)。是的,我知道2017年的代码,但是一旦我开始测试,那么我将改变日期并继续生产。

#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 } }

它会复制文件夹的内容,但不会复制文件夹。我想我错过了一个-recurse,但是在Get-ChildItem $ path之后将它放在了不起作用。

我打算让这个工作正常,然后添加一个Remove-Item行来删除文件服务器中的所有旧项目。

思考?建议更好的方法来实现这一目标?

谢谢,

1 个答案:

答案 0 :(得分:0)

我认为您错过-Recurse中的Get-ChildItem,但我会这样做:

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

如果您要隐藏或系统文件要复制,您还需要-Force上的Get-ChildItem参数。

实际上,您可能需要这样做:

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;
    }
}
相关问题