0
votes

Below is my scenario which I need to achieve:

I have a file test.txt .This file contains file names. So suppose, test.txt has below two lines in it:

file1.txt
file2.txt

Please note that these two files (file1.txt, file2.txt) are present in a folder (src_folder).

Below is the action that I need to perform:

  1. I need to read this test.txt file
  2. For every file entry found in test.txt file (in our case file1.txt and file2.txt), copy these two files from src_folder to a different folder (say suppose tgt_folder).

How can I achieve this using powershell script?

Appreciate help on this! Thanks in advance.

1
Do you have a minimal-reproducible-example of what you tried so far?T-Me

1 Answers

1
votes

This shouldn't be too difficult:

$sourceFolder = 'D:\Test\src_folder'
$destination  = 'D:\Test\tgt_folder'

Get-Content -Path 'D:\Path\To\test.txt' | ForEach-Object {
    Copy-Item -Path (Join-Path -Path $sourceFolder -ChildPath $_) -Destination $destination
}

If you're worried that test.txt may contain empty lines, do:

Get-Content -Path 'D:\Path\To\test.txt' | Where-Object { $_ -match '\S' } | ForEach-Object { .. }

as per your comment you need to have two destinations, depending on the file extension, use below code:

$sourceFolder   = 'D:\Test\src_folder'
$csvDestination = 'D:\Test\tgt_folder'
$txtDestination = 'D:\Test\new_tgt_folder'

# test if the destination folders exist. If not create them first
if (!(Test-Path -Path $csvDestination)) {
    $null = New-Item -Path $csvDestination -ItemType Directory
}
if (!(Test-Path -Path $txtDestination)) {
    $null = New-Item -Path $txtDestination -ItemType Directory
}

Get-Content -Path 'D:\Path\To\test.txt' | Where-Object { $_ -match '\S' } | ForEach-Object {
    $file = Join-Path -Path $sourceFolder -ChildPath $_.Trim()
    switch ([System.IO.Path]::GetExtension($file)) {
        # you can add more options here if there are other extensions to handle differently
        '.csv'  {$destination = $csvDestination; break}
        default {$destination = $txtDestination}  # this is for .txt or any other extension
    }
    if (Test-Path -Path $file -PathType Leaf) {
        Copy-Item -Path $file -Destination $destination
    }
    else {
        Write-Warning "File '$file' not found"
    }
}