Reputation: 567
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 - i.e., to create the "B1" folder that's missing at the destination directory?
Upvotes: 1
Views: 459
Reputation:
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
Upvotes: 2
Reputation: 17462
try this
$DirSource="C:\temp\Folder1"
$DirDestination="C:\temp\Folder2"
Get-ChildItem $DirSource -directory -Recurse | %{New-Item $_.FullName.Replace($DirSource, $DirDestination) -ItemType Directory -Force}
Upvotes: 1