简体   繁体   中英

Read a file and then move the content from one folder to another using Powershell script

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.

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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM