大家下午好,
我猜这很简单,但对我来说真的很烦人;我有一个带有文件列表的文本文件,在相同的文件夹中有很多其他文件,但我只需要特定的文件。
$Filelocs = get-content "C:UsersmeDesktoptomoveCodelocations.txt"
Foreach ($Loc in $Filelocs){xcopy.exe $loc C:Redactedoutput /s }
我想这会像一样通过列表
"C: \redated\Policies\IT\Retracted Documents\Policy_Control0.docx">
然后移动并在一个新的地方创建文件夹结构,然后复制文件,但它没有。
如有任何帮助,我们将不胜感激。
谢谢大型
xcopy
无法知道文件夹结构。在类似C:foobarbaz.txt
的路径中,基本目录可以是C:
、C:foo
或C:foobar
中的任何一个。
使用路径列表时,必须自己构建目标目录结构。解析从文本文件到相对路径的路径,加入目标目录,创建文件的父目录,最后使用PowerShell自己的Copy-Item
命令复制文件。
$Filelocs = Get-Content 'locations.txt'
# Base directory common to all paths specified in "locations.txt"
$CommonInputDir = 'C:redactedPolicies'
# Where files shall be copied to
$Destination = 'C:Redactedoutput'
# Temporarily change current directory -> base directory for Resolve-Path -Relative
Push-Location $CommonInputDir
Foreach ($Loc in $Filelocs) {
# Resolve input path relative to $CommonInputDir (current directory)
$RelativePath = Resolve-Path $Loc -Relative
# Resolve full target file path and directory
$TargetPath = Join-Path $Destination $RelativePath
$TargetDir = Split-Path $TargetPath -Parent
# Create target dir if not already exists (-Force) because Copy-Item fails
# if directory does not exist.
$null = New-Item $TargetDir -ItemType Directory -Force
# Well, copy the file
Copy-Item -Path $loc -Destination $TargetPath
}
# Restore current directory that has been changed by Push-Location
Pop-Location
可能的改进,作为练习:
- 自动确定在";locations.txt";。不琐碎,但也不太难
- 确保代码异常的安全。将
Push-Location
和Pop-Location
之间的所有内容封装在try{}
块中,并将Pop-Location
移动到finally{}
块中,这样即使发生脚本终止错误,也会恢复当前目录。请参阅about_Try Catch_Finally