1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PowerShellでNAS内に同じファイルがあるかを調べる

Last updated at Posted at 2021-06-21

仕事でたくさんのPDFファイルを扱うのですがコピーも多いので、NASに同じファイルがあるかを調べるスクリプトを作りました。

NASのファイル一覧をCSVファイルに出力する

NASへのファイルアクセスを減らしたいので、一旦NASの中のファイル情報(フルパス、ファイルサイズ、最終書き込み日時)をCSVファイルに出力します。下のスクリプトをNASの検索対象のフォルダで実行してfilelist.csvを作成します。

NASのデータを集める
Get-ChildItem *.pdf -Attributes Archive -Recurse | Select-Object Name,FullName,Length,LastWriteTime | Export-Csv filelist.csv -Encoding UTF8

ファイルを検索する

先のスクリプトで出力されたfilelist.csvを検索したいファイルがあるフォルダに移動して下のスクリプトを実行します。

ファイルを検索する
$m = Import-Csv filelist.csv -Encoding UTF8
Get-ChildItem *.pdf -Attributes Archive -Recurse | ForEach-Object {
  $h = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
  $s = 'None'
  foreach($t in $m){
    if (($_.Length -eq $t.Length) -And ([DateTime]::$_.LastWriteTime -eq [DateTime]::$t.LastWriteTime)){
      if ($h -eq (Get-FileHash $t.FullName -Algorithm SHA256).Hash){
        $s = $t.FullName
        break
  }}}
  Write-Host $_.FullName,$s
}

プログラムは、「ファイルサイズ」が同じで、「最終書き込み日時」が同じで、「SHA256のハッシュ値」が同じであるかを調べています。(コピーするとファイル名が変更される場合があるので、ファイル名が同じであるかは調べていません。)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?