Ad

How To Search In Multiple Text Files In Dir For File Names Of Jpg And Then Move Them To Corresponding Folders

- 1 answer

I have this folder with both text files and jpg files. Each text file contains information like

2021-01-12T07:22:14;0;R0010313.JPG 
2021-01-12T07:23:03;0;R0010314.JPG

where the R number corresponds to a jpg file of that name. Now, I want to read each text file, get the name of the jpgs and then move the jpgs to a new folder named the same as the text file then move on to the next text file. I managed to create the new folders with the correct name so now I just need to move the correct jpgs to the right folder. This is what I have so far:

$path = "C:\Users\Yo\Desktop\Brunnar" #Path where all the TXT files are
$TxtFiles = Get-ChildItem -Path $path -filter "*.txt"
$JpgFiles = Get-ChildItem -Path $path -filter "*.JPG"

$files = Get-Childitem $path | Where-Object { ! $_.PSIsContainer} #Get all files in the folder

#For each file in this folder
foreach ($file in $files){
    ## If it is a txt file
    if ([io.path]::GetExtension($file.Name) -eq ".txt"){ # If it is a .txt file
    
        $foldername = [io.path]::GetFileNameWithoutExtension($file) #Remove the fileextension in the foldername
        if (!(Test-Path "$path\$foldername")){ #If the folder doesn't exist
            New-Item "$path\$foldername" -ItemType "directory" #Create a new folder for the file
        }
       ## Move-Item $file.FullName "$path\$foldername" #Move file into the created folder
     

    Get-ChildItem -LiteralPath C:\Users\Yo\Desktop\Brunnar -Filter *.txt -File -Recurse | foreach {

    #$fileData = @{
       # "File"=$_.FullName;
        $content =(Get-Content -LiteralPath $_.FullName -Raw)
       
    #}
        if($content -match $JpgFiles.Name){
   
            #move jpg to the new folder
        } 
    
    }
    }
      
}


Ad

Answer

Take a look at the following snippet (not tested).
It shows all the needed steps to perform your task but might need some adjustments.

$Path = 'C:\Users\Yo\Desktop\Brunnar'

# Process only the txt files in the direcotry
foreach ($TextFile in (Get-ChildItem -Path "$($Path)\*.txt" -File)) {
    # Get the content of the text file
    $Content = Get-Content -Path $TextFile.FullName

    # Get the r number from content
    $JPGFileName = $Content.Split(';')[2]

    # Create folder if not exists
    if (-not (Test-Path -Path "$($Path)\$($TextFile.BaseName)")) {
        New-Item -Path "$($Path)\$($TextFile.BaseName)" -ItemType Directory
    }

    # Move the jpg file to the new path
    if (Test-Path -Path "$($Path)\$($JPGFileName)") {
        Move-Item -Path "$($Path)\$($JPGFileName)" -Destination "$($Path)\$($TextFile.BaseName)\$($JPGFileName)"
    }
}
Ad
source: stackoverflow.com
Ad