how to add more error handling for get-hash

by matt_will_fix_it at 2013-02-07 22:44:09


I’m trying to create a script that will generate MD5 hashes of all files created by an application installer on the file system. So far I’ve come up with this. It seems to work sometimes, but when I run some complex application installers, sometimes the script will stop logging half way through (eg it just stops). I’m guessing this is because the file passed to get-hash is only a temporary file and is removed or locked by the time get-hash tries to access it and generate the checksum.

Is there any way to add some error handling in around this, so that if get-hash can’t access the file, that it moves on instead of stopping?

[code2=powershell]Import-Module Pscx -RequiredVersion
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = “c:"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

$created = Register-ObjectEvent $watcher “Created” -Action {
$strFileName = $($eventArgs.FullPath)
$strHashValue = get-hash -LiteralPath $strFileName
add-content C:\users\admin\Desktop\created.txt -value "$strHashValue $strFileName "

If I change the script “write-host” instead of “get-hash” (as per the code below), it correctly reports all the files created to the console, so i suspect its something in the get-hash not been able to access the files.

[code2=powershell]$created = Register-ObjectEvent $watcher “Created” -Action {
write-host “Created: $($eventArgs.FullPath)”
by DonJ at 2013-02-08 06:40:58
If the code “just stops” and doesn’t throw an exception, no. If it throws an exception, yes, you can use a Try{} block.