简体   繁体   中英

How do I Compare Two Folders and Create Missing Subfolders in PowerShell

Hi folks,

In PowerShell, I would like to compare two folders; [Folder1] and [Folder2], and for every folder missing in [Folder1], create it in [Folder2]. How do I do this?

For example:

> tree .
├───Folder1
│   ├───A0
│   ├───A1
│   ├───B0
│   └───B1
└───Folder2
    ├───A0
    ├───A1
    └───B1

Here's what I've tried so far:

I've assigned my source and destination folders, and retrieved the list of folder in each as follows:

$Source = "C:\Temp\Folder1"
$Destination = "C:\Temp\Folder2"
$SrcObj = Get-ChildItem $Source
$DestObj = Get-ChildItem $Destination

I then compared the two folders, as such:

Compare-Object -ReferenceObject $SrcObj -DifferenceObject $DestObj

Which resulted in the following output:

InputObject  SideIndicator
-----------  -------------
B1           <=

Given the output above, I thought that I could then pipe the Compare-Object command's output directly to the New-Item cmdlet, but that doesn't seem to be working for me.

How can I achieve my objective - ie, to create the "B1" folder that's missing at the destination directory?

Following your approach, and only in the direction towards destination you could do:

$Source      = "C:\Temp\Folder1"
$Destination = "C:\Temp\Folder2"
$SrcObj      = Get-ChildItem $Source -Dir
$DestObj     = Get-ChildItem $Destination -Dir

Compare-Object -Ref $SrcObj -Diff $DestObj -Property Name |
  Where-Object SideIndicator -eq '<=' |
    New-Item -ItemType Directory -Path {Join-Path $Destination $_.Name} -WhatIf

If the output looks OK, remove the trailing -WhatIf

try this

$DirSource="C:\temp\Folder1"
$DirDestination="C:\temp\Folder2"

Get-ChildItem $DirSource -directory -Recurse | %{New-Item $_.FullName.Replace($DirSource, $DirDestination) -ItemType Directory -Force}

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