Neptune443

Untitled

Nov 17th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Get-RSFileHash {
  2. <#
  3. .Synopsis
  4.    Returns an MD5 filehash when given a file path
  5. .DESCRIPTION
  6.    Returns an MD5 filehash when given a file path
  7. .EXAMPLE
  8.    Get-RSFileHash -Filename c:\temp\filetohash.txt
  9. .EXAMPLE
  10.    Get-ChildItem c:\temp\*.txt | get-rsfilehash
  11. #>
  12.  
  13.     [CmdletBinding()]
  14.     [OutputType([string])]
  15.     Param
  16.     (
  17.         [Parameter(Mandatory=$true,
  18.                    ValueFromPipeline=$true,
  19.                    Position=0,
  20.                    ParameterSetName="String")]
  21.         [string[]]$Path,
  22.         [Parameter(Mandatory=$true,
  23.                    ValueFromPipeline=$true,
  24.                    Position=0,
  25.                    ParameterSetName="FileInfo")]
  26.         [IO.FileInfo[]]$InputObject
  27.     )
  28.  
  29.     BEGIN {"------------"}
  30.     Process
  31.     {
  32.         if($PSCmdlet.ParameterSetName -eq "string") {
  33.             $file = $Path
  34.         } else {
  35.             $file = $InputObject.FullName
  36.         }
  37.         foreach($file in $file){
  38.             if (test-path -Path $file -PathType Leaf) {
  39.                 try {
  40.                     $md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
  41.                     $stream = [System.IO.File]::Open($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
  42.                     $hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
  43.                     $stream.Close()
  44.                     Write-Debug "$file - $hash"
  45.  
  46.                     Write-Output $hash.Replace('-',$null)
  47.                 }
  48.                 catch {
  49.                     throw "Unable to generate hash for $file - $($_)"
  50.                 }
  51.             }
  52.         }
  53.     }
  54. }
  55.  
  56. $someFilePath = "C:\ps\test.txt","C:\ps\test.tx3"
  57. $files =  get-childitem -Path $someFilePath
  58. $files | Get-RSFileHash
  59. Get-RSFileHash -path $someFilePath[0]
  60. Get-RSFileHash -path $someFilePath
  61. Get-RSFileHash -InputObject $files[0]
  62. Get-RSFileHash -InputObject $files
  63. $someFilePath | Get-RSFileHash
Advertisement
Add Comment
Please, Sign In to add comment