PowerShell搜索字符串并复制文件

PowerShell搜索字符串并复制文件,powershell,Powershell,我正在准备一个脚本来查找文件中的一些文本(“test”和“test1”是本场景中的关键字),一旦找到所有文件,就应该将它们复制到不同的位置,同时保持文件夹结构 例如: 路径c:\src包含10个文件,其中3个包含搜索词。 这3个文件应复制到c:\dst\ 对于c:\src的所有子目录,所有内容都应该是递归的 因此,如果路径c:\src\somefolder\中有其他具有相同搜索词的文件,则应将它们复制到c:\dst\somefolder\ 这是我的代码: Write-Host "" Write-

我正在准备一个脚本来查找文件中的一些文本(“test”和“test1”是本场景中的关键字),一旦找到所有文件,就应该将它们复制到不同的位置,同时保持文件夹结构

例如: 路径c:\src包含10个文件,其中3个包含搜索词。 这3个文件应复制到c:\dst\

对于c:\src的所有子目录,所有内容都应该是递归的

因此,如果路径c:\src\somefolder\中有其他具有相同搜索词的文件,则应将它们复制到c:\dst\somefolder\

这是我的代码:

Write-Host ""
Write-Host "Note: Path must end with '\'"
Write-Host ""

# Var.
$sourceDir = Read-Host 'Source path'
$targetDir = Read-Host 'Destination path'

# Decl.
$tree = gci -Directory -Name -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 ( $folders in $tree ) { mkdir $targetDir\$folders -Force }

# Copy Founded Files
$ftc = Get-ChildItem $sourceDir -Recurse | Select-String "test","test2" | Select Path |
foreach{    
  $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length); 
  Copy-Item $_ -destination $targetFile
}
我想不出错误在哪里。 有人知道我怎么解决吗


建议的错误是:复制项:找不到单位。名为“@{Path=C”的单元不存在。

您的脚本有一些严重的错误

  • gci构建树中的
    -Name
    参数仅保留 subdir名称,因此重建树部分只有一个平面结构,而lateron上的gci文件无法匹配
  • 您的选择字符串模式匹配两次,因为第二个包含第一个,所以我添加了
    -Unique
    参数来选择路径
  • 使用Get Item$\ Path生成复制项的targetFile name传递
这在(不同的)测试树上起作用:

## 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
}

您期望得到什么结果,实际得到什么结果?您是否看到任何错误消息?如果是,它们是什么?请编辑您的问题以包含此信息。对于初学者,您需要知道别名为
gc
和别名为
gci
之间的区别。例如在获得所需文件后在
gci
cmdlet中,您需要阅读使用
gc
cmdlet的内容,然后将其传送到
Select String
@VivekKumarSingh。如果我想对代码应用建议的更改,您可以告诉我如何操作?谢谢,我只看到创建固定targetdir时出现问题,因为递归sourcedir时,您必须检查结果targetdir for every file.@LotPings不幸的是,提出了一个复制错误,据我所知,脚本似乎找不到源文件的路径:(