Home > Enterprise >  How do I improve performance of Get-Content $picture conversion into a byte array?
How do I improve performance of Get-Content $picture conversion into a byte array?

Time:06-05

Using Powershell, I insert a picture into a SQL database varbinary(max) column via an API.

I use Get-Content -Encoding byte to convert the picture to a byte array, but it is slow:

[byte[]]$picture = Get-Content $picturePath -Encoding byte

Is there a way to improve performance?

CodePudding user response:

I ended up with this (much faster) solution:

[system.io.stream]$Stream = [system.io.File]::OpenRead($picturePath)
try {
  [byte[]]$picture = New-Object byte[] $Stream.length
  [void] $Stream.Read($picture, 0, $Stream.Length);
} finally {
  $Stream.Close();
}

CodePudding user response:

Following the hint from @zett42, I tested "Get-Content", "Get-Content with the -Raw switch" and the "system.io.stream" solution (enter image description here

NB "Encoding -byte" is not supported in PowerShell 7.2. In 7.2 use the -AsByteStream switch (https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-5.1 / https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-7.2)

  • Related