200mg
200mg

Reputation: 531

Compare Two variables and select matching lines from each

I have an issue where a junior tech accidentally deleted a partition. We were able to recover some of the files, but not the structure. We are restoring the file structure and older files off a month old backup tape. I am trying to match the new data with no structure to the old data being restored from tape.

So far I am capturing the old and new file attributes and storing them in a variable. This is what I have so far to grab the file attribs.

$newpath = "C:\new"
$oldpath = "C:\old"

$newdata = Get-ChildItem -Recurse $newpath |ForEach-Object {Get-ItemProperty $_} |
           Select-Object Name, Directory, LastWriteTime, Fullname,
               @{n='Folder';e={Split-Path "$_.Directory" -Parent | Split-Path -Leaf}}

$olddata = Get-ChildItem -Recurse $oldpath |ForEach-Object {Get-ItemProperty $_} |
           Select-Object Name, Directory, LastWriteTime, Fullname,
               @{n='Folder';e={Split-Path "$_.Directory" -Parent | Split-Path -Leaf}}

This is a sample of the "new" data variable (this example is just the attribs of one file, there is 2T worth of files):

Name          : firefox_2017-01-11_13-58-52.png
Directory     : C:\New\2017-01\PHX-A
LastWriteTime : 1/11/2017 1:58:52 PM
FullName      : C:\New\2017-01\PHX-A\firefox_2017-01-11_13-58-52.png
Folder        : PHX-A

This is a sample of the old data:

Name          : firefox_2017-01-11_13-58-52.png
Directory     : C:\old\accounting\some_folder\screenshots_new\2017-01\PHX-A
LastWriteTime : 1/11/2017 1:58:52 PM
FullName      : C:\DROPBOX\Dropbox\001\W\03SCRIPTS\TEMP\screenshots_new\2017-01\PHX-A\firefox_2017-01-11_13-58-52.png
Folder        : PHX-A

I would like to match on the Folder and Name and then copy the actual files by using Copy-Item $newdata.FullName to the $olddata.FullName or $olddata.Directory and overwrite.

Does anyone know how I can accomplish that?

Upvotes: 0

Views: 87

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200213

Create a hashtable from the old data, using Name\Folder as the key and the directory as the value, then lookup the destination for the new data in that hashtable.

$oldpath = ...
$newpath = ...

$olddata = @{}
Get-ChildItem $oldpath -Recurse | ForEach-Object {
  $olddata[(Join-Path $_.Directory.Name $_.Name)] = $_.DirectoryName
}

Get-ChildItem $newpath -Recurse | Where-Object {
  $key = Join-Path $_.Directory.Name $_.Name
  $olddata.ContainsKey($key)
} | ForEach-Object {
  Copy-Item $_.FullName $olddata[$key] -Force
}

Upvotes: 1

Related Questions