Last active
November 17, 2016 21:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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