Home > database >  powershell Script for moving specific files from a folder based on a filename.txt
powershell Script for moving specific files from a folder based on a filename.txt

Time:02-06

I have a folder that contains 2000 Jpeg images I want to copy some images from this folder to another folder based on the filename that I have in sort.txt file. I have a filename in text format. how this can be done?

Source is E:\SORT\RUSH Destination is E:\SORT\SORTED filename list is E:\sort.txt

$file_list = Get-Content E:\sort.txt
foreach ($file in $file_list) {
    $subf = $file.Split('-')[0]    
    $source = "E:\SORT\RUSH"
    Copy-Item $source E:\SORT\SORTED -WhatIf
}

CodePudding user response:

Ok, so now we know the input textfile only contains file BaseNames (no extension), you need to check if such a file can be found in the $source directory.

Try

$source      = 'E:\SORT\RUSH'
$destination = 'E:\SORT\SORTED'

# first, make sure the destination folder exists
$null = New-Item -Path $destination -ItemType Directory -Force

# make sure no duplicates are in the text file
$file_list = Get-Content -Path 'E:\sort.tx' | Select-Object -Unique
foreach ($file in $file_list) {
    # create the full path and filename for the file to copy
    $sourceFile = Join-Path -Path $source -ChildPath "$file.jpg"
    # if the file can be found, copy it
    if (Test-Path -Path $sourceFile -PathType Leaf) {
        Copy-Item -Path $sourceFile -Destination $destination
    }
    else {
        Write-Warning "Could not find file '$sourceFile'"
    }
}
  •  Tags:  
  • Related