Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

前端 未结 5 1391
独厮守ぢ
独厮守ぢ 2021-02-05 02:20

I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).

Lets say, there

5条回答
  •  遇见更好的自我
    2021-02-05 03:02

    I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.

    Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force
    

    Plus I needed to Filter and only copy *.config files.

    This didn't work, with "\*" because it did not recurse

    Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force
    

    I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.

    Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse | 
    ForEach-Object {
      $childPath = "$_".substring($sourcePath.length+1)
      $dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
      Copy-Item -Verbose -Path $_ -Destination $dest -Force   
    }
    

提交回复
热议问题