以下是我需要实现的方案:
我有一个文件test.txt。此文件包含文件名。因此,假设test.txt中包含以下两行:
file1.txt
file2.txt
请注意,这两个文件(file1.txt,file2.txt)位于文件夹(src_folder)中。
以下是我需要执行的操作:
如何使用Powershell脚本实现这一目标?
对此有帮助!预先感谢。
答案 0 :(得分: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"
}
}