【问题标题】:Powershell find file in one location over write in another based on namePowershell根据名称在一个位置查找文件而不是在另一个位置写入文件
【发布时间】:2017-06-10 20:29:36
【问题描述】:

我是 powershell 的初学者,但最近有人要求我为基础架构人员创建一个脚本。

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

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

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

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

到目前为止我的代码:

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

Foreach ($File in $FileList) { 
    Get-ChildItem $Src -Name -Recurse $File
}

【问题讨论】:

    标签: arrays file powershell find move


    【解决方案1】:
    $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 仅对路径的叶(文件名)组件进行操作,并接受array 名称,这是 Get-Content 默认返回的)。

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

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

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

    【讨论】:

    • 绝对比我的脚本更有效率。 +1
    • @MavCoder:很抱歉听到这个消息;没有什么容易想到的。我建议您提出一个 问题来更详细地描述该问题,最好是通过MCVE (Minimal, Complete, and Verifiable Example)
    【解决方案2】:
    $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"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多