以下是我需要实现的场景:
我有一个文件 test.txt 。这个文件包含文件名。所以假设 test.txt 中有以下两行:
file1.txt
file2.txt
请注意,这两个文件(file1.txt、file2.txt)存在于一个文件夹(src_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] 删除。
我来说两句