【问题标题】:Powershell copy folders and files and re-create parent folder as sub folderPowershell复制文件夹和文件并将父文件夹重新创建为子文件夹
【发布时间】:2016-08-17 11:43:25
【问题描述】:

我创建了简单的 powershell 脚本来将文件和文件夹从一个位置复制到共享计算机中的多个位置,这很有效,但我们必须每周运行一次此脚本来复制和覆盖现有内容

问题是下次运行脚本时,在与子文件夹相同的父文件夹中创建父文件夹,例如:

Folder1 已复制(下次脚本运行或该文件夹是否存在)如下所示

文件夹 1\文件夹 1

正如您在图片中看到的那样,这会正确复制文件夹和内容,但如果该文件夹存在,或者这将在同一个文件夹中创建具有相同名称的新子文件夹

这是要审核的脚本副本。

Clear-Host
#source path
$sourceDir = '\\source\Users\asdew\Desktop\dep' 

#Array with Sites Path
$targetDir = @(

               #Sites in pc1
               '\\Apc20\Users\afded\Desktop\site01',

               #Sites in pc2

               '\\Apc10\Users\adsed\Desktop\site02'

                )

$i=0

Foreach ($dest in  $targetDir){

Get-ChildItem $sourceDir   -Recurse   | % {

   $dest = $targetDir[$i] + $_.FullName.SubString($sourceDir.Length)

    If (!($dest.Contains('.')) -and !(Test-Path $dest))

    {
        mkdir $dest
    }



       #Copy Files and over write existen files.
   Write-Host "copy  start. Please wait..We are copying your files.." -ForegroundColor DarkYellow

   Copy-Item $_.FullName -Destination $dest -Force  -PassThru -ErrorAction SilentlyContinue

   If(-not $?)

    {Write-Warning "Your copy Failed!!"  -InformationAction} 

   else 
    {Write-Host "Your copy was Success!" -ForegroundColor Green}


   }

    $i =  $i+1
}

我希望有人可以帮助我解决这个问题。 问候

【问题讨论】:

    标签: powershell copy


    【解决方案1】:

    我认为 Copy-Item 应该完成所有工作。试试下面的代码

    Clear-Host
    #source path
    $sourceDir = '\\source\Users\asdew\Desktop\dep' 
    #Array with Sites Path
    $targetDir = @(
    
               #Sites in pc1
               '\\Apc20\Users\afded\Desktop\site01',
    
               #Sites in pc2
    
               '\\Apc10\Users\adsed\Desktop\site02'
    
                )
    
    
    Foreach ($dest in  $targetDir){
        Get-ChildItem $sourceDir | Copy-Item -Recurse -Destination $dest -ErrorAction Continue -Force
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多