遍历子目录并(1)将文件复制到另一个目录(2)将它们重命名为它们的 md5 哈希

Loop through subdirs and (1) copy files to another dir (2) renaming them to their md5 hash

考虑以下目录结构:

rootdir
  subdir_1
     12345.tif
     56789.tif
  subdir_2
     00000.tif
  ...
  subdir_n
     99999.tif
     54321.tif
     54345.tif

我需要:

  1. 遍历此结构
  2. 计算每个tif文件的md5
  3. 将 [md5.tif] 复制到另一个文件夹(忽略文件夹结构)。

因此所需的输出将是:

newdir
   2070e4cfb8f24209647d3c9ec55098ee.tif
   52e31fe630cebe73cc959d371bd6b353.tif
   eec032f144f5af1be2b7f0535a2010d2.tif
   936ed95431293660e3499d88e5ae22b0.tif
   8bc884dce30d89b53b120adb8bd658b2.tif
   ec87470ae6683b539ea69004894e23dd.tif

我现在有(在 PS 2.0 bc 这就是我必须使用的):

Get-ChildItem "D:\rootdir" -filter *.tif |
  Foreach-Object {
    $content = Get-Content $_.FullName
    $md5     = New-Object -TypeName  

    System.Security.Cryptography.MD5CryptoServiceProvider
    $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($content)))

    ## Write-Host $hash = CB-A9-EB-00-92-18-06-71-D9-DD-7C-2A-08-D9-D9-EF

    Set-Content $_.FullName('newroot/'+ $hash +'.tif')
}

这里的第一个问题是MD5中间有-。那么我在这里做错了什么?

二、为什么新文件没有写入文件系统?

如有任何帮助,我们将不胜感激!

首先,这些破折号是 [System.BitConverter]::ToString() 的结果。如果需要,您可以删除它们。其次,如果你正在复制一个文件,你应该调用 Copy-Item 而不是 Set-Content。像这样:

$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
Get-ChildItem "D:\rootdir" -filter *.tif -Recurse |
Foreach-Object {
    $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($_.fullname)))
    $hash = $hash -replace "-","" # drop all dashes off $hash

    Copy-Item -Path $_.fullname -Destination "newroot/$hash.tif"
}