$sqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$sqlConnection.ConnectionString = 'Server=rejk-p-sql003\sql01;Database=AfcCookedIFSv2;Trusted_Connection=True;'
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()


$sqlCommand.CommandText = @"
--select datalength(photodata) as Len, PhotoData from cmn.ObjCustomer where CustomerRefNumber = 102111037
select photodata from pom.objordercardordering where orderid = 9712549
"@

$reader = $sqlCommand.ExecuteReader()

if($reader.HasRows) {
    while($reader.read()) {
        $data = $reader['PhotoData']
        $len = $reader['Len']
    }
} else {
    [pscustomobject]@{
        CardEngravedID = $num
        EquipmentType = ''
        FileName = ''
        MessageReceptionDate = ''
        ServiceProviderID = ''
        ContractorID = ''
        StaffID = ''
        DeviceID = ''
        Contractor = ''
        ServiceProvider = ''
    }
}

$reader.Close()
$sqlConnection.Close()

[System.Text.Encoding]::Default.GetString($data) | Set-Content -Path C:\users\ewpmni\desktop\test.png