I'm a beginner when it comes to powershell but recently I've been asked to create a script for the infrastructure guys.
Basically I have a list of file names in a text file. The files exist in two different locations, lets say locationA and locationB. The files could be sitting in different sub-folders within the folder root.
What I need to do is find each file listed in the text file. Search for the file in locationA then find the file in locationB, more than likely a different folder structure then over write the file in the same location where it exists in locationB with the file in locationA.
I'm assuming this will need to be done through an array. What I'm having trouble with is finding the files in each location and then over write the associated by file name.
Any help will be greatly appreciated. I've just come across this site and intend to use it a lot more in future.
My code so far:
$FileList = 'C:\File_Names.txt'
$Src ='\\server\Temp'
$Dst ='\\server\Testing'
Foreach ($File in $FileList) {
Get-ChildItem $Src -Name -Recurse $File
}
$FileList = 'C:\File_Names.txt'
$Src ='\\server\Temp'
$Dst ='\\server\Testing'
Get-ChildItem $Src -Recurse -Include (Get-Content $FileList) | ForEachObject {
$destFile = Get-ChildItem $Dst -Recurse -Filter $_.Name
switch ($destFile.Count) {
0 { Write-Warning "No matching target file found for: $_"; break }
1 { Copy-Item $_.FullName $destFile.FullName }
default { Write-Warning "Multiple target files found for: $_" }
}
}
Get-ChildItem $Src -Recurse -Include (Get-Content $FileList)
searches the subtree of $Src
for any files whose name is contained in file $FileList
(-Include
operates on the leaf (file-name) components of the paths only, and accepts an array of names, which is what Get-Content
returns by default).
Get-ChildItem $Dst -Recurse -Filter $_.Name
searches the subtree of $Dst
for a file of the same name ($_.Name
); note that -Filter
is used in this case, which is preferable for performance reasons, but only an option with a single name / name pattern.
The switch
statement then ensures that copy action is only taken if exactly 1 file in the destination subtree matches.
In the Copy-Item
call, accessing the source and destination file's .FullName
property ensures that the files are referenced unambiguously.