读取文件,然后使用 Powershell 脚本将内容从一个文件夹移动到另一个文件夹

瓦巴夫·古普塔

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

我有一个文件 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 脚本实现此目的?

感谢这方面的帮助!提前致谢。

跟随

这应该不会太难:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Powershell将文本文件从一个文件夹移动到另一个文件夹

PowerShell 将集合移动到 SCCM 中的另一个文件夹?

需要一个Powershell脚本,该脚本会将文件夹和文件从一个位置移动到另一个位置

如何使用Powershell将文件夹的内容复制到另一个特定的文件夹?

PowerShell 脚本通过创建两个同名的子文件夹来将 jpg 文件从一个文件夹复制到另一个文件夹

如何使用Powershell将文件从一个文件夹复制并重命名到另一个文件夹?

如何使用PowerShell仅将新文件从一个文件夹复制到另一个文件夹

如何使用powershell将具有不同名称的文件从一个文件夹复制到另一个文件夹?

将特定邮件从一个文件夹移动到另一个文件夹

Python脚本将特定文件从一个文件夹移动到另一个文件夹

Powershell脚本将具有大致相同名称的文件从文件夹复制到另一个文件夹

使用sudo将文件夹移动到另一个文件夹

Powershell:将父文件夹中的所有子目录和内容复制到另一个文件夹目标

将文件从一个文件夹从文本文件的文件名列表移动到另一个文件夹

将整个文件夹从其父文件夹移动到另一个文件夹

使用shutil将文件从一个文件夹移动到另一个文件夹时出错

Google云端存储-将文件从一个文件夹移动到另一个文件夹-使用Python

使用 Node js 将所有 .txt 文件从一个文件夹移动到另一个文件夹

如何使用 Azure Devops 将 azure GIT repos 文件从一个文件夹移动到另一个文件夹

Shell脚本重命名并将文件从一个文件夹移动到另一个文件夹

Applescript如何将文件从一个文件夹移动到另一个文件夹。无法将整数类型错误

如何在TortoiseSVN中将文件(或文件夹)从一个文件夹移动到另一个文件夹?

Python将文件和目录从一个文件夹移动到另一个文件夹

如何将FTP服务器中的CSV文件从一个文件夹移动到另一个文件夹?

IOException同时将文件从一个文件夹移动到另一个文件夹

每5分钟将文件从一个文件夹移动到另一个文件夹的批处理程序

将文件从一个文件夹移动到另一个具有相同名称的文件夹

根据列表将所有文件从一个文件夹移动到另一个文件夹

我已经设置了文件权限,但是我无法将图像从一个文件夹移动到另一个文件夹