Skip to content

Instantly share code, notes, and snippets.

@rodmhgl
Last active November 17, 2016 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rodmhgl/3b050c052dc628adfdf9961708c62fea to your computer and use it in GitHub Desktop.
Save rodmhgl/3b050c052dc628adfdf9961708c62fea to your computer and use it in GitHub Desktop.
Just looking to get input on the best way to handle parameter sets
function Get-RSFileHash {
<#
.Synopsis
Returns an MD5 filehash when given a file path
.DESCRIPTION
Returns an MD5 filehash when given a file path
.EXAMPLE
Get-RSFileHash -Filename c:\temp\filetohash.txt
.EXAMPLE
Get-ChildItem c:\temp\*.txt | get-rsfilehash
#>
[CmdletBinding()]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0,
ParameterSetName="String")]
[string[]]$Filename,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0,
ParameterSetName="ChildItem")]
[System.IO.FileInfo]$InputObject
)
Begin { }
Process
{
switch ($PsCmdlet.ParameterSetName) {
"String" {
foreach ($file in $Filename) {
if (test-path -Path $file -PathType Leaf) {
try {
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$stream = [System.io.file]::Open($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
#$stream = [System.IO.File]::Open($file,[System.IO.Filemode]:‌​:Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$stream.Close()
#$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file)))
Write-Debug "$file - $hash"
Write-Output $hash.Replace('-',$null)
}
catch {
throw "Unable to generate hash for $file - $($_)"
}
}
}
}
"ChildItem" {
foreach ($object in $InputObject) {
$file = $object.fullname
if (test-path -Path $file -PathType Leaf) {
try {
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$stream = [System.IO.File]::Open($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$stream.Close()
Write-Debug "$file - $hash"
Write-Output $hash.Replace('-',$null)
}
catch {
throw "Unable to generate hash for $file - $($_)"
}
}
}
}
}
}
End { }
}
$someFilePath = "C:\temp\users.csv"
get-childitem -Path "C:\temp\Validation.ps1" | Get-RSFileHash
Get-RSFileHash -Filename C:\temp\Validation.ps1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment