简体   繁体   中英

Powershell copy, retain folder structure

Im trying to achieve the following, get computers name from a txt file, search for particulat file extension, copy the files along with folder structure and in destination create folder based on the computer name and paste there, please see my powershell commands below, when im trying with single computer it works fine, but when adding mutiple computers im getting error.

Please tell me what are the modifications required? Thanks in advance

$computername = Get-Content -Path "C:\Test\computers.txt"
$src = "\\$ComputerName\c$\test"
  Get-ChildItem $src -Recurse *.opt |  foreach {
  $split = $_.Fullname  -split '\\'
  $DestFile =  $split[1..($split.Length - 1)] -join '\' 
  $DestFile =  "C:\Test1\$DestFile"
  $null = New-Item -Path  $DestFile -Type File -Force
  Copy-Item -Path  $_.FullName -Destination $DestFile -Force
}

As per my comment, iterate the lines read from computers.txt:

## Q:\Test\2018\07\28\SO_51572359.ps1

$computers = Get-Content -Path "C:\Test\computers.txt"

ForEach($ComputerName in $computers){
    $src = "\\$ComputerName\c$\test"
    Get-ChildItem $src -Recurse *.opt | ForEach-Object {
        $split = $_.Fullname  -split '\\'
        $DestFile =  $split[1..($split.Length - 1)] -join '\' 
        $DestFile =  "C:\Test1\$DestFile"
        $null = New-Item -Path  $DestFile -Type File -Force
        Copy-Item -Path  $_.FullName -Destination $DestFile -Force
    }
}

Sample tree after running script:

> tree c:\Test1 /F
Folder PATH listing for volume ThisPC
Volume serial number is 0000xxxx xxxx:xxxx
C:\TEST1
└───RemotePC
    └───c$
        └───test
                Test.opt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM