【问题标题】:Powershell script for comparing two directories based on file names only仅基于文件名比较两个目录的 Powershell 脚本
【发布时间】:2015-01-09 08:57:58
【问题描述】:

我有两个具有相同目录结构的磁盘。 C:\FilesD:\Files

C:\FilesD:\Files 下都有多个目录但名称相同等,但其中的文件扩展名不同。在C:\Files 中,它们是*.csv,在D:\Files 中,一个进程监视文件(从C:\ 复制),一旦完成,将文件更改为*.processed

我想要一个可以执行该副本的脚本。即从C:\Files复制文件到D:\Files,这些文件还没有通过仅比较文件名来处理。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你想要这样的东西。您要比较的属性称为BaseName,powershell 会帮助您将其添加到IO.FileSystemInfo 类(FileInfo.BaseName exists in PowerShell but not in straight .NET)中。 BaseName 只是文件的名称,不包含任何您不关心的扩展名。

    $sourceFiles = Get-ChildItem C:\files -Recurse -File -Filter "*.csv"
    $destinationFiles = Get-ChildItem D:\files -Recurse -File 
    
    foreach($sourceFile in $sourceFiles) {
      $exists = $destinationFiles | Where-Object {$_.BaseName -eq $sourceFile.BaseName}
      if(!$exists) {
        Copy-Item $sourceFile.fullname -Destination "D:\Files\$($sourceFile.BaseName)"
      }
    }
    

    【讨论】:

      【解决方案2】:
      dir .\ *csv -Recurse -File | cp -ea Ignore -WhatIf -Destination {
          $dest=$_.FullName-replace'^C:','D:'-replace'\.csv','.processed'
          if(Test-Path $dest){
              Write-Host Already exists -ForegroundColor Yellow
              $null
          }else{
              Write-Host Copying... -ForegroundColor Green
              $dest-replace'\.processed$','.csv'
          }
      }
      

      注意 WhatIf 参数:如果您要真正复制项目,则必须删除它。 此外,您可能希望使用write-host cmdlet 删除 2 行。 也请注意,我已将 C:D: 驱动器硬编码为源驱动器和目标驱动器。

      【讨论】:

        猜你喜欢
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多