【问题标题】:powershell get-item | copy-item not keeping folder structure for just one folderpowershell 获取项目 |复制项不只为一个文件夹保留文件夹结构
【发布时间】:2019-05-02 20:54:00
【问题描述】:

我正在尝试使用 powershell 脚本将所有文件夹/子文件夹/子文件从服务器上的一个文件夹移动到另一个文件夹,同时始终保持相同的文件结构。为此,我正在使用 Get-childItem |复制项目。除了目录中的第一个文件夹外,所有文件夹、子文件夹和子文件都在正常移动。而是将此文件夹中的所有这些子文件/子文件夹输出到目标。但是,它确实保留了它们的结构,只是不包括它们的父目录。我的代码如下:

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force 
  • filepath 被改写以提高可读性
  • $sourceFilePath 是我要复制的源文件夹
  • $destination server / $destinationClient 是在解释的“文件路径”中使用的变量

我无法弄清楚为什么此代码适用于所有其他文件夹、子文件夹和文件,除了这个单个文件夹及其项目。任何帮助将不胜感激,如果有任何其他信息可以帮助,请告诉我。


感谢@Christian Müller 的回答:

New-Item $destinationFilePath -name "MissingFolder" -type directory -Force | Out-Null

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*filepath*" -f $destinationServer, $destinationClient) -Recurse -Force

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这是一个非常奇怪的错误,也让我自己感到惊讶! :)

    似乎当目标基目录不存在时,它只是被创建而不是内容。

    因此,通过这种构造,您甚至可以在 ISE 中调试此行为:

    $sourceFilePath = "c:\temp\Test1"
    $destPath = "c:\temp\Test2"
    $a=Get-ChildItem $sourceFilePath -Force
    
    rm -Force $destPath
    foreach($x in $a) {
        $x | Copy-Item -Destination "$destPath" -Recurse -Force 
    }
    
    dir $destPath
    

    先创建目标目录,解决问题,新建项目:

    $sourceFilePath = "c:\temp\Test1"
    $destPath = "c:\temp\Test2"
    $a=Get-ChildItem $sourceFilePath -Force
    
    rm -Force $destPath
    
    New-Item -ItemType Directory -Force -Path $destPath
    foreach($x in $a) {
        $x | Copy-Item -Destination "$destPath" -Recurse -Force 
    }
    
    dir $destPath
    

    但对于我的示例来说,它可以工作,根本不使用“Get-ChildItem”,而是

    Copy-Item c:\temp\test1 -Destination c:\temp\test2 -Recurse -Force
    

    这对你也有用吗?

    Copy-Item $sourceFilePath -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force 
    

    【讨论】:

    • 克里斯蒂安,感谢您的帮助!你是对的,首先创建目录似乎可以修复这个错误。我最终在我之前创建了一个新行来创建丢失文件夹的目录,它现在可以完美运行。真是一个奇怪的错误!我的最终代码是:

      New-Item $destinationFilePath -name "AlertSubscriptionService" -type directory -Force | Out-Null
      Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*filepath*" -f $destinationServer, $destinationClient) -Recurse -Force
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2019-01-23
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多