Powershell 根据名称在一个位置查找文件覆盖另一个位置

Powershell find file in one location over write in another based on name

我是 Powershell 的初学者,但最近我被要求为基础设施人员创建一个脚本。

基本上我有一个文本文件中的文件名列表。 这些文件存在于两个不同的位置,假设是 locationA 和 locationB。这些文件可能位于文件夹根目录中的不同子文件夹中。

我需要做的是找到文本文件中列出的每个文件。 在 locationA 中搜索文件,然后在 locationB 中找到文件,很可能是不同的文件夹结构,然后用 locationA 中的文件覆盖 locationB 中存在的相同位置的文件。

我假设这需要通过数组来完成。我遇到的问题是在每个位置找到文件,然后按文件名覆盖关联文件。

任何帮助将不胜感激。我刚刚接触到这个网站,并打算在未来更多地使用它。

到目前为止我的代码:

$FileList = 'C:\File_Names.txt' 
$Src ='\server\Temp' 
$Dst ='\server\Testing' 

Foreach ($File in $FileList) { 
    Get-ChildItem $Src -Name -Recurse $File
}
$FileList = Get-Content 'C:\File_Names.txt' 
$SrcDir ='\server\Temp' 
$DstDir ='\server\Testing' 
Foreach ($File in $FileList) { 
    $SrcFile = Get-ChildItem $SrcDir -Recurse $File -EA SilentlyContinue
    $DstFile = Get-ChildItem $DstDir -Recurse $File -EA SilentlyContinue
    if (($Srcfile.count -eq 1) -and ($DstFile.count -eq 1)){
        Copy-Item $SrcFile $DstFile
    } Else {
        "More/less than one Source and/or Destination file $File"
    }
}
$FileList = 'C:\File_Names.txt' 
$Src ='\server\Temp' 
$Dst ='\server\Testing' 

Get-ChildItem $Src -Recurse -Include (Get-Content $FileList) | ForEachObject {
  $destFile = Get-ChildItem $Dst -Recurse -Filter $_.Name
  switch ($destFile.Count) {
    0 { Write-Warning "No matching target file found for: $_"; break }
    1 { Copy-Item $_.FullName $destFile.FullName }
    default { Write-Warning "Multiple target files found for: $_" }
  }
}
  • Get-ChildItem $Src -Recurse -Include (Get-Content $FileList)$Src 的子树中搜索其名称包含在文件 $FileList 中的任何文件(-Include 对叶(文件-name) 仅路径的组成部分,并接受名称的 array,默认情况下是 Get-Content returns).

  • Get-ChildItem $Dst -Recurse -Filter $_.Name$Dst 的子树中搜索同名文件 ($_.Name);请注意,在这种情况下使用 -Filter,出于性能原因,这是更可取的,但仅具有 单个 名称/名称模式的选项。

  • switch 语句确保仅当目标子树中的 1 文件完全匹配时才执行复制操作。

  • Copy-Item 调用中,访问源文件和目标文件的 .FullName 属性 确保文件被明确引用。