PowerShell – How to Copy and Replace 100 New Files in a Directory

powershell

I have a 100 files in one directory. These are new files that need to replace old files that are located in many sub directories. What I think that should be done is: search for one file at a time and then replace it. So far I have come up with a way to find the files in the directories but can't seem to use each file name to replace it with the new one.

$files = @(Get-ChildItem D:\topLevelDir\*.txt)
foreach ($file in $files) { gci -Path C:\Users\MyUserName\ -filter $file.Name -Recurse -ErrorAction SilentlyContinue -Force}

I tought it would be a simple task but I am struggeling a bit. What can I do to use the list and replace each file? How can I use the Where-object command to use each file name and replace the new file with the old?

Best Answer

Where-Object is great for receiving a list of objects and combing through them based on some condition. Use $_ to interact with each object you feed it one at a time.

$newFiles = "C:\Users\username\new"
$oldFiles = "C:\Users\username\originals"

Get-ChildItem $newFiles | ForEach-Object {

    $currentFile = $_

    $oldFileLocation = Get-ChildItem -Recurse $oldFiles | Where-Object { $_ -Match "$currentFile"} | Select-Object -ExpandProperty DirectoryName

    if($oldFileLocation) {   # if this variable is not null, we've found original file location
        Write-Host "found file [$currentFile] in location: [$oldFileLocation]. overwriting the original."
        Copy-Item -Path $newFiles\$currentFile -Destination $oldFileLocation -Force
    }
    else {
        Write-Warning "could not find file [$currentFile] in location [$oldFiles]."
    }

}

If used with the following test files:

C:\Users\username\new\
-file1.txt
-file2.txt
-file3.txt
-file4.txt

C:\Users\username\originals\
-foldera\file2.txt
-folderb\foo\file3.txt
-folderc\file1.txt

The results are:

found file [file1.txt] in location: [C:\Users\username\originals\folderc]. overwriting the original.
found file [file2.txt] in location: [C:\Users\username\originals\foldera]. overwriting the original.
found file [file3.txt] in location: [C:\Users\username\originals\folderb\foo]. overwriting the original.
WARNING: could not find file [file4.txt] in location [C:\Users\username\originals].

Depending on the specific scenario you apply this to, you may want to add checks to handle a file that is found in more than one subdirectory.

Related Question