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
############################################################ #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.