Where this code required?
In many scenario, we will got the requirement for moving the specific files from the large number of files from one location to another location based someย filterย on the file name. This code will helps with same situation. The below code will split the filename before “-” and compare the existing list “filterLists” to findย
STEP #1
Declare the souce and target path locations.
$srcpath = “C:\Powershelltest\Source”
$dstpath = “C:\Powershelltest\Destination”
STEP #2
Fetch all the child file list to make the loop to start the validation of each files.
$fileList = Get-ChildItem -Path $srcpath -Force -Recurse
foreach ($file in $fileList)
{
}
STEP #3
Second level of loop for validating whether filename is mathing with our input
foreach($filelist in $filterLists)
{
#Our Logic
}
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
############################################################ #Project : Move files to another directory by File name filter #Developer : Thiyagu S (dotnet-helpers.com) #Tools : PowerShell 5.1.15063.1155 #E-Mail : mail2thiyaguji@gmail.com ############################################################ #set Source and Destination folder location $srcpath = "C:\Powershelltest\Source" $dstpath = "C:\Powershelltest\Destination" #Set the files name which need to move to destination folder $filterLists = @("70022333","70022867") #Get all the child file list with source folder $fileList = Get-ChildItem -Path $srcpath -Force -Recurse #loop the source folder files to find the match foreach ($file in $fileList) { #checking the match with filterlist foreach($filelist in $filterLists) { #$key = $file.BaseName.Substring(0,8) #Spliting value before "-" for matching with filterlists value $splitFileName = $file.BaseName.Substring(0, $file.BaseName.IndexOf('-')) if ($splitFileName -in $filelist) { $fileName = $file.Name Move-Item -Path $($file.FullName) -Destination $dstpath } } } |
Output
After Execution
What do you think?
I hope you have an idea ofย Move files to another directory Based on Filename with Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave A Comment