【问题标题】:Read a file and then move the content from one folder to another using Powershell script读取文件,然后使用 Powershell 脚本将内容从一个文件夹移动到另一个文件夹
【发布时间】:2020-09-12 19:58:07
【问题描述】:

以下是我需要实现的场景:

我有一个文件 test.txt 。这个文件包含文件名。所以假设,test.txt 有以下两行:

file1.txt
file2.txt

请注意,这两个文件(file1.txt、file2.txt)存在于一个文件夹(src_folder)中。

以下是我需要执行的操作:

  1. 我需要阅读这个 test.txt 文件
  2. 对于在 test.txt 文件中找到的每个文件条目(在我们的例子中为 file1.txt 和 file2.txt),将这两个文件从 src_folder 复制到不同的文件夹(假设为 tgt_folder)。

如何使用 powershell 脚本实现这一点?

感谢您对此的帮助!提前致谢。

【问题讨论】:

标签: powershell


【解决方案1】:

这应该不会太难:

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

如果您担心 test.txt 可能包含空行,请执行以下操作:

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

根据您的评论,您需要有两个目的地,具体取决于文件扩展名,使用以下代码:

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

【讨论】:

  • 谢谢@Theo..问题有细微的变化..这个test.txt文件可以包含两种类型的文件(.csv和.txt)..如果是.csv然后复制它到 tgt_folder.. 如果是 .txt 则将其复制到 new_tgt_folder。你能再帮忙吗?
  • 谢谢@Theo..这主要符合我的目的。唯一需要注意的是,如果某些用户错误地输入了带有一些初始空格的文件名,则此代码无法处理..您能帮我吗?是的,一旦解决了这个问题,我肯定会将其标记为已接受的答案.. :)
  • @VaibhavGupta 好的,也修复了文本文件中的空格。我还添加了一个额外的测试,以确保在尝试复制之前文件存在。
  • 嗨@Theo..不知何故,当我的文本文件与服务器同步时..它将多行转换为单行..所以我介绍了';'终止文本文件中的单个文件名.. 但是现在,我怎样才能排除 ';'在读取文件时?例如如下:
  • @VaibhavGupta 在这种情况下使用(Get-Content -Path 'D:\Path\To\test.txt' -Raw) -split ';' | Where-Object { .. }
猜你喜欢
  • 2021-05-24
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
相关资源
最近更新 更多