【问题标题】:Copy folders from server to another - Powershell将文件夹从服务器复制到另一个 - Powershell
【发布时间】:2021-08-17 00:02:58
【问题描述】:

我正在尝试编写一个脚本来将文件夹从一台服务器复制到另一台服务器。我可能会解决这个问题,但我尝试将目录从一台服务器复制到一个数组中,将目录从第二台服务器复制到一个数组中,比较它们,然后在服务器中创建不需要的文件夹拥有它们:

[array]$folders = Get-ChildItem -Path \\spesety01\TGT\TST\XRM\Test -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName 
[array]$folders2 = Get-ChildItem -Path \\sutwove02\TGT\TST\XRN -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName 


$folders | ForEach-Object {
    if ($folders2 -notcontains "$_") {
      New-Item "$_" -type directory


    }
}

问题是“$_”(在 ForEach 循环中)指的是“$folders”中的服务器,当我运行脚本时,我收到一个错误,指出该文件夹已经存在。有没有办法指定将文件夹复制到新服务器?我接受我的方法可能完全不适用,我可能会使其变得比需要的更难。

【问题讨论】:

  • 如果您希望第二个将所有目录都放在第一个...那么只需将所有第一个目录都放在第二个中。不必费心对其进行测试,只需设置错误处理即可吃掉错误。
  • Robocopy 是一个内置的 Windows 应用程序,如果您想要“简单”的方式,它可以完全按照您的意愿进行操作。
  • 是否需要在远程服务器上创建目录,而不是在本地?
  • 刚接触 SO 你可能不知道这一点,但习惯上点击左侧的 图标accept the answer that best solved your problem。这将帮助其他有类似问题的人更容易地找到它,并有助于激励人们回答你的问题。你甚至会因为这样做而获得声誉积分;)
  • 是的,我不知道。谢谢你让我知道。我是(非常)新来的,所以很抱歉并感谢您的提示。

标签: powershell foreach directory


【解决方案1】:
<#
.SYNOPSIS
using path A as reference, make any sub directories that are missing in path B
#>

Param(
    [string]$PathA,
    [string]$PathB
)

$PathADirs = (Get-ChildItem -Path $PathA -Recurse -Directory).FullName
$PathBDirs = (Get-ChildItem -Path $PathB -Recurse -Directory).FullName

$PreList = Compare-Object -ReferenceObject $PathADirs -DifferenceObject $PathBDirs.replace($PathB,$PathA) | 
    Where-Object -Property SideIndicator -EQ "<=" |
        Select-Object -ExpandProperty 'InputObject'

$TargetList = $PreList.Replace($PathA,$PathB)

New-Item -Path $TargetList -ItemType 'Directory'

【讨论】:

  • 这很漂亮,应该标记为答案。
  • 我不明白@MackJ,如果这个答案有帮助,为什么不将其标记为已回答,因为您提出了这个问题?
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多