【发布时间】:2021-12-27 15:46:52
【问题描述】:
我的 SQL 服务器中有一个 varbinary(max) 列,其中包含如下所示的二进制文件:
0x255044462D312E340D0A25E2E3CFD30D...
我想在 powershell 中检索此值,以便我可以运行发送电子邮件的逻辑。
#Get the attachment binary into a variable from sql server
$Query = "SELECT AttachmentBinary FROM [dbo].MyFiles"
$e= Invoke-Sqlcmd -Query $Query -ServerInstance $server (etc.etc.)
在 powershell 中运行 $e.Attachmentbinary 会给我一个十进制数字列表,我认为这是 powershell 显示二进制文件的方式:
37
80
68
70
45
(and so on)
现在的问题是,当我准备文件并发送电子邮件时..
$contentStream = New-Object System.IO.MemoryStream(,$e.Attachmentbinary)
$MailAttachment = New-Object System.Net.Mail.Attachment($contentStream, "application/pdf")
$SMTPMessage.Attachments.Add($MailAttachment)
.. 它给我发送了一个 1kb 的文件。也就是说,
$e.AttachmentBinary.Length #Returns 1024 for some reason..
我确定数据库中的二进制数据是正确的。添加附件时,问题似乎出在第二部分。
如何纠正?
【问题讨论】:
-
查看 MemoryStream 类的constructor overloads,您需要
System.IO.MemoryStream($e.Attachmentbinary)。那里的逗号使它使用带有两个参数的重载,这些参数希望字节缓冲区作为第一个参数,第二个是布尔值(可写) -
P.S.您可能需要明确地将
$e.Attachmentbinary转换为[Byte[]]$e.Attachmentbinary -
@Theo 您的解决方案有效,但我还必须为我的 Invoke-Sqlcmd 命令增加 -MaxBinaryLength 78680。
-
本题与
tsql无关。请去掉这里引错人的标签,浪费时间
标签: arrays powershell smtp