環境:Windows 7, Visual Studio 2008
System.Management.Automation.dll を使用するため、Microsoft Windows SDK をインストールする必要があります。
Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1
http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&displaylang=en
前回、PowerShellでハッシュ値を計算してみましたが、今回はファイルのハッシュ値を取得するコマンドレット(Get-Hash)を作成してみます。コマンドレットの作成については、CodeZineを参考にさせていただきました。
CodeZine - Windows PowerShell 独自コマンドレットの開発
http://codezine.jp/article/detail/3191
1.新しいプロジェクト(Gine.PowerShell.Cmdlets)を作成、クラス(GetHash.cs)を追加し、System.Management.Automation.dll, System.Configuration.Install.dll を参照に追加します。
2.GetHash.cs にコマンドレット実行時のコードを記載します。
using System;
using System.Management.Automation;
using System.Security.Cryptography;
using System.IO;
namespace Gine.PowerShell.Cmdlets
{
[Cmdlet(VerbsCommon.Get, "Hash")]
public class AddEventEntry : Cmdlet
{
private string _Path;
[Parameter(Mandatory = true, Position = 0)]
public string Path
{
get
{
return _Path;
}
set
{
_Path = value;
}
}
protected override void ProcessRecord()
{
StreamReader stream = new StreamReader(_Path);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(stream.BaseStream);
string result = BitConverter.ToString(hash).ToLower().Replace("-", "");
WriteObject(result);
}
}
}
3.インストールとスナップイン登録を行うスナップインクラスを作成します。新しい項目の追加で、クラス(GinePSSnapIn.cs)を追加しコードを記載します。
using System.ComponentModel;
using System.Management.Automation;
namespace Gine.PowerShell.Cmdlets
{
[RunInstaller(true)]
public class GinePSSnapIn : PSSnapIn
{
public override string Name
{
get
{
return "Gine.PowerShell.Cmdlets";
}
}
public override string Description
{
get
{
return "はじめてのコマンドレット";
}
}
public override string Vendor
{
get
{
return "CodeZine";
}
}
}
}
4.作成したコマンドレットをインストールします。
ビルドして出来たdll(Gine.PowerShell.Cmdlets.dll)を「C:\Windows\System32\WindowsPowerShell\v1.0」にコピーし、InstallUtilを実行してインストールします。
コマンド例)
InstallUtil.exe C:\Windows\System32\WindowsPowerShell\v1.0\Gine.PowerShell.Cmdlets.dll
※InstallUtil.exeは、デフォルトでは、
「C:\Windows\Microsoft.NET\Framework64\v2.0.50727」 や
「C:\Windows\Microsoft.NET\Framework\v2.0.50727」にあります。
5.実行
PowerShellを起動しスナップインの登録を行えば準備は完了です。Get-Hashコマンドレットの実行が可能になります。
Add-PSSnapin "Gine.PowerShell.Cmdlets"
Get-Hash C:\Users\xxxx\Downloads\xxxxx.zip