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.If used with the following test files:
The results are:
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.