【问题标题】:Powershell copy, retain folder structurePowershell复制,保留文件夹结构
【发布时间】:2018-07-28 23:48:12
【问题描述】:

我试图实现以下目标,从 txt 文件中获取计算机名称,搜索特定文件扩展名,将文件与文件夹结构一起复制,并在目标中根据计算机名称创建文件夹并粘贴到那里,请参阅我的 powershell 命令下面,当我尝试使用单台计算机时它工作正常,但是当添加多台计算机时我得到错误。

请告诉我需要哪些修改?提前致谢

$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
}

【问题讨论】:

  • 你遇到了什么错误?
  • $computername 是一个字符串数组,你也必须迭代。
  • 您正在寻找robocopy。除非有充分的理由,否则不要尝试在 PowerShell 中重新发明它。

标签: powershell


【解决方案1】:

根据我的评论,迭代从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
    }
}

运行脚本后的示例树:

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

【讨论】:

  • 感谢您的更新,我可以从远程计算机获取文件,但是出现以下错误,是否与权限有关? Get-ChildItem:找不到路径“\\\c$\Program Files\”,因为它不存在。在 line:3 char:5 + Get-ChildItem $src -Recurse *.opt | ForEach-Object { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (\\\c$\ Program Files\:String) [Get-ChildItem], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
  • 根据信息显示文件/路径确实存在,很可能是权限问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 2013-06-18
  • 2010-12-11
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多