如何在Powershell中仅使用robocopy复制文件夹?

时间:2019-02-14 15:47:20

标签: powershell robocopy

如何使用Powershell和robocopy仅复制目录中的文件夹?

Get-ChildItem 'C:\temp\test' |

ForEach-Object {
    $newname = ($_.BaseName -Replace '[^\x20-\x5D,\x60-\x7E]+', '-')
    write-host $_.BaseName
    write-host $newname
    robocopy.exe 'C:\temp\test\'$_.BaseName 'C:\temp\test\copy\'$newname
}

修改

谢谢,谢谢!

Get-ChildItem 'C:\temp\test' |

ForEach-Object {
    $newname = ($_.BaseName -Replace '[^\x20-\x5D,\x60-\x7E]+', '-')
    if (($_.GetType()).Name -eq "DirectoryInfo"){
        write-host "folder"
    }
    write-host $_.BaseName
    write-host $newname
    robocopy.exe "C:\temp\test\$($_.BaseName)" "C:\temp\test\copy\$newname"
}

2 个答案:

答案 0 :(得分:0)

已更正的错误,下面修改了代码。

Get-ChildItem 'C:\temp\test' |

ForEach-Object {
    $newname = ($_.BaseName -Replace '[^\x20-\x5D,\x60-\x7E]+', '-')
    write-host $_.BaseName
    write-host $newname
    robocopy.exe "C:\temp\test\$($_.BaseName)" "C:\temp\test\copy\$newname"
}

答案 1 :(得分:0)

您可以执行以下操作:

$items = Get-ChildItem 'C:\temp\test'

foreach($item in $items){
    if(($item.GetType()).Name -eq "DirectoryInfo"){
        $newname = ($item.BaseName -Replace '[^\x20-\x5D,\x60-\x7E]+', '-')
        Write-Host $item.BaseName
        Write-Host $newname
        robocopy.exe "C:\temp\test\$($_.BaseName)" "C:\temp\test\copy\$newname"
    }else{
        Write-Host "$item is not a directory"
    }
}