Reputation: 69
I would like to use a loop for my program that grabs the file names of only the .dll
in the folder and subfolders of that directory. It then searches a specified location/path for a .dll
with the same file name and if it exists it replaces it. So far my program copies all files from one location to the other and once they are copied I need the above stated to be worked out.
My biggest issue is how do you search by filenames in a loop at a specified location and if it exists, replace it? Below code is locally in random places before I put the correct paths using servers and other drives.
#sets source user can edit path to be more precise
$source = "C:\Users\Public\Music\Sample Music\*"
#sets destination
$1stdest = "C:\Users\User\Music\Sample Music Location"
#copies source to destination
Get-ChildItem $source -recurse | Copy-Item -destination $1stdest
#takes 1stdest and finds only dlls to variable
#not sure if this is right but it takes the .dlls only, can you do that in the foreach()?
Get-ChildItem $1stdest -recurse -include "*.dll"
Upvotes: 1
Views: 4896
Reputation: 13537
Here you go, you'll need to edit your paths back in. Also, note that $1stDest
was changed to enumerate the list of files in the destination folder.
The logic goes through all of the files in $source, and looks for a match in $1stDest
. if it finds some, it stores them in $OverWriteMe
. The code then steps through each file to be overwritten and copies it.
As written, it uses -WhatIf
, so you'll have a preview of what would happen before running it. If you like what you see, remove the -WhatIf
on line 15.
$source = "c:\temp\stack\source\"
#sets destination
$1stdest = get-childitem C:\temp\stack\Dest -Recurse
#copies source to destination
ForEach ($file in (Get-ChildItem $source -recurse) ){
If ($file.BaseName -in $1stdest.BaseName){
$overwriteMe = $1stdest | Where BaseName -eq $file.BaseName
Write-Output "$($file.baseName) already exists @ $($overwriteMe.FullName)"
$overwriteMe | ForEach-Object {
copy-item $file.FullName -Destination $overwriteMe.FullName -WhatIf
#End of ForEach $overwriteme
}
#End Of ForEach $file in ...
}
}
1 already exists @ C:\temp\stack\Dest\1.txt
What if: Performing the operation "Copy File" on target "Item: C:\temp\stack\source\1.txt Destination: C:\temp\stack\Dest\1.txt".
5 already exists @ C:\temp\stack\Dest\5.txt
What if: Performing the operation "Copy File" on target "Item: C:\temp\stack\source\5.txt Destination: C:\temp\stack\Dest\5.txt".
Upvotes: 1