【问题标题】:How can i only copy folders with robocopy in powershell?我如何只能在 powershell 中使用 robocopy 复制文件夹?
【发布时间】:2019-02-15 15:11:49
【问题描述】:

如何使用 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"
}

【问题讨论】:

  • 您基本上是将BaseName 重命名为Copy 并复制C:\Temp\Test 下的所有内容(其中还包含copy 文件夹以及再次copy)。所以copy 每次运行脚本时都会有它自己的副本。

标签: powershell robocopy


【解决方案1】:

更正错误,修改代码如下。

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】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多