Minggu, 13 Februari 2011

Powershell - Fillters in Functions

I am working with a function that needs a specific set of subprocesses run. I tried adding a nested function, but, Powershell didn't seem to take to that idea too well. Instead, I added a filter for checking MD5 hashes to my function. I got the MD5 snippet from Vadims Podams post:
http://www.vistax64.com/powershell/207882-get-md5-digest-powershell.html
which gave me:
function Hash-MD5 ($file) {
$hasher = [System.Security.Cryptography.MD5]::Create()
$inputStream = New-Object System.IO.StreamReader ($file)
$hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
$inputStream.Close()
$builder = New-Object System.Text.StringBuilder
$hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }
$output = New-Object PsObject
$output | Add-Member NoteProperty HashValue ([string]$builder.ToString())
$output.hashvalue
}
Modifying this I was able to pass in the pipelined object and get what I needed with some tweaking. The filter is bold text. I also bolded the use of the filter in the $command:

function Check-FileMD5
{
param(
[string]$path,
[switch]$recurse,
[switch]$fileName,
[switch]$hash
)

# Notify user script is running

Write-Host Searching for duplicates -ForegroundColor Green

# Filter for testing hashes

Filter MD5Hash
{
$hasher = [System.Security.Cryptography.MD5]::Create()
$inputStream = New-Object System.IO.StreamReader ($_.fullname)
$hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
$inputStream.Close()
$builder = New-Object System.Text.StringBuilder
$hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }
$output = New-Object PsObject
$output | Add-Member NoteProperty HashValue ([string]$builder.ToString())
$_.fullname + " :: " + $output.hashvalue
}


# Correct input string: add ending slash

if(!$path.EndsWith("\"))
{
$path = $path + "\"
}

# Build command

if($recurse)
{
$command = "Get-ChildItem -Path $path -recurse | Where {`$_.PSIsContainer -eq `$false} | select fullname"
}
else
{
$command = "Get-ChildItem -Path $path | Where {`$_.PSIsContainer -eq `$false} | select fullname"
}

if($hash)
{
$command = $command + " | MD5Hash"
}

Write-Host "The command to be processed is: $command"
Invoke-Expression $command
}
To use this function I type:
Check-FileMD5 -path C:\Data -hash -recurse

0 komentar:

Posting Komentar

 
Powered by Blogger