How can i only copy folders with robocopy in powershell?

房东的猫 提交于 2020-01-16 05:10:06

问题


How can i copy only the folders in a directory with powershell and 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
}

Edit

Thanks works great

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

回答1:


Corrected errors, modified code below.

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



回答2:


You could do something like:

$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"
    }
}


来源:https://stackoverflow.com/questions/54694212/how-can-i-only-copy-folders-with-robocopy-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!