LoginSignup
4
4

More than 5 years have passed since last update.

Powershell が遅かったので早くした(ハッシュ生成、ファイル書き込み)

Last updated at Posted at 2018-11-20

はじめに

こんにちは、のんびりエンジニアのたっつーです。
ブログを運営しているのでよろしければ見てください。

powershell を使って大量にファイルを処理していたのですが、あまりにも遅くて高速化を行ったのでその時の改善内容を残しておきます、誰かのお役に立てればよいです。

powershell 自身の問題およびコマンドの実行の遅さが原因なのかなと感じました、対策としては.NETオブジェクトを利用するのが一番良い結果が出ていると思います。

ハッシュの生成

変更前

  • hash.tmp に生成したい文字列を格納
  • certutil コマンドで生成したハッシュ値を $hash に格納
Write-Output "文字列" | Set-Content hash.tmp
$hash = (certutil -hashfile hash.tmp MD5)[1..1]

(Get-FileHashコマンドがあるけどツッコミは無しで)

変更後

  • $md5, $utf8 オブジェクトを事前に生成
  • $hash にハッシュ値を格納
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UT8Encoding

for ...
   $hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes("文字列")))
   $hash = $hash.Replace("-", "").ToLower()

ファイル書き込み

変更前

  • Write-Output で出力した内容
  • パイプで受け取り、Add-Content でファイルに出力
Write-Output "文字列" | Add-Content hash.log -Encoding Unicode

変更後

  • 事前に $file オブジェクトを生成
  • $file の WriteLine を使ってファイルに出力
$file = New-Object System.IO.StreamWriter("hash.log", $false, [System.Text.Encoding]::GetEncoding("unicode"))

for ...
   $file.WriteLine("文字列")

$file.Close()

参考

よければ ブログ「初心者向けUnity情報サイト」の方にも色々記載しているのでぜひご参照いただければと思います。

4
4
3

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
4
4