简体   繁体   中英

How can i only copy folders with robocopy in powershell?

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

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

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

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