I haven’t posted anything in a while but it’s not because I’ve been idle. I’ve been doing a massive amount of PowerShell and will be blogging some real cools stuff in the coming weeks.
For now, I’m offering a little tidbit I wrote yesterday for reading a file into a binary byte array. It was necessary for Publishing RDL files in Sequel Server Reporting Services – more on that later too.
function read-filebytes($fileItem={Throw "fileItem is required for read-filebytes"})
{
try {
[system.io.stream]$stream = [system.io.File]::OpenRead($fileItem.fullname)
[byte[]]$filebytes = New-Object byte[] $stream.length
[void] $stream.Read($filebytes, 0, $stream.Length);
$filebytes
} -finally {
$stream.Close();
}
} -catch {
Write-Error "Error reading file $fileItem - $_"
return
I’m using the TryCatchFinally Cmdlet it’s really made error management much easier.
The real trick to this script is:
This pre-allocates the memory for the Stream Read method. Not a common technique in PowerShell.
Cash
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.