我准备了一个脚本来查找文件中的一些文本(' test'以及' test1'是这个场景中的关键字)并且所有文件都已经过了发现,应该在保持文件夹结构的同时将它们复制到不同的位置。
例如: 路径c:\ src包含10个文件,3个包含搜索词。 应将这3个文件复制到c:\ dst \
对于c:\ src。
的所有子目录,所有内容都应该是递归的因此,如果在路径c:\ src \ somefolder \中有其他文件具有相同的搜索词,则应将它们复制到c:\ dst \ somefolder \
这是我的代码:
{{1}}
我无法弄清楚错误的位置。 有谁知道我怎么解决它?
建议的错误是:复制项:无法找到该单位。一个名为' @ {Path = C'不存在。
答案 0 :(得分:0)
你的脚本有一些严重的错误
-Name
参数树只留下了
subdir名称,因此重建树部分只有一个扁平结构,文件后面的gci不能匹配。-Unique
参数来选择路径这在一个(不同的)测试树上工作:
## Q:\Test\2018\05\17\SO_50391092.ps1
Write-Host ""
Write-Host "Note: Path must end with '\'"
Write-Host ""
# Var.
#$sourceDir = Read-Host 'Source path'
#$targetDir = Read-Host 'Destination path'
$sourceDir = "C:\test"
$targetDir = "A:\Test"
# Decl.
$tree = gci -Directory -Recurse $sourceDir
# Check if $sourceDir exist
if(!(Test-Path -Path $sourceDir )){
"Source is not a valid path!" ; pause
exit 1
}
# Check (and create) $targetDir
if(!(Test-Path -Path $targetDir )){mkdir $targetDir -Force}
# Rebuild Tree
foreach ( $folder in $tree ) {
mkdir ($folder.fullname.replace($sourceDir,$targetDir)) -Force |Out-Null
}
# Copy Found Files
$ftc = Get-ChildItem $sourceDir -Recurse | Select-String "test","test2" | Select -Unique Path |
foreach{
$sourceFile = Get-Item $_.Path
$targetFile = $sourceFile.Fullname.Replace($sourceDir,$targetDir)
$sourceFile | Copy-Item -Destination $targetFile
}