Scenario – A file is present at many locations in folder and its subfolders. We need to find the file in all the locations of given path and replace it with the new updated file. The new updated file name may be same as old one or may be different too…
Above scenario is implemented using PowerShell script –
——————————————————————————
<#
.Synopsis
Search and Replace File
.Discription
It searches and then replaces file.
#>
param ([parameter(Mandatory=$True,Position=0)]
[string][ValidateNotNullOrEmpty()]$FileLocationToSearch,
[Parameter(Mandatory=$true, Position=1)]
[string][ValidateNotNullOrEmpty()]$FileName,
[Parameter(Mandatory=$true, Position=1)]
[string][ValidateNotNullOrEmpty()]$FilelocationForReplace)
$FilePaths = Get-ChildItem -Path $FileLocationToSearch -Recurse -File | Where-Object {$_.Name -eq $FileName} | Select -ExpandProperty FullName
foreach ($File in $FilePaths)
{
$DestFilePath = Split-Path -Path $File
Write-Host “—————————————————–”
Write-Host $File
Remove-Item $File
Write-Host $File “DELETED!!!”
Copy-Item -Path $FilelocationForReplace -Destination $DestFilePath -Force
Write-Host $FilelocationForReplace ” — Copied Successfully to $DestFilePath”
Write-Host “—————————————————–“
}
————————————————————————————————————–
Flow of program –
1) It is finding file from all folders and subfolders from a given location as input
2) In foreach loop, for every location found, it is deleting the found file and then copying the updated file back on that location
—–End of Article—–