0
votes

I created simple powershell script to copy files and folders from one location to many location in share computers, this work well but we have to run this script one time every week to copy and over write existen content

The problem is the script next time run create the parents folder inside same parent agian as sub folder for exampel:

Folder1 copied (Next time script run or if the folder exist) this look like

Folder1\folder1

enter image description here enter image description here

as you can see in the pics this copy correctly the folder and content but if the folder exist or this will create new sub folder in the same folder with the same name

Here is copy of the script to be reviewd.

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
}

I hope some one can help me to resolve this issue. Regards

1

1 Answers

0
votes

I think Copy-Item should do all the job. Try the following code

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
}