将文件夹从服务器复制到另一个 - Powershell

问题描述

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

[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”中的服务器,当我运行脚本时,我收到一个错误,该文件夹已经存在。有什么方法可以指定将文件夹复制到新服务器吗?我承认我的方法可能完全偏离了这一点,而且我可能使它变得比需要的更难。

解决方法

<#
.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'