Powershell确定base64字符串文件扩展名

时间:2017-11-20 16:56:10

标签: powershell

我有一个XML文件,其中包含以Base64编码的文件附件(InfoPath)。当我使用Powershell解码附件的Base64字符串时,似乎我必须将文件路径和扩展名写入WriteAllBytes命令,但我不知道原始文件是PDF,图像文件,DOCX,有没有办法让它把字符串写入原始文件名和/或扩展名,我只需指定它需要去的文件夹?示例代码:

$b64str = $xml.myRootNode.attachmentNode
$someFileName = somehow get original filename
$someFileExtension = somehow get original extension
$filepath = "C:\myFolder\$someFileName.$someFileExtension"
$bytes = [Convert]::FromBase64String($b64str)
[IO.File]::WriteAllBytes($filepath,$bytes)
编辑:感谢评论员的努力,找到答案。对于那些将来必须这样做的人,可能使用Powershell从库中提取InfoPath表单中的附件提示提示:InfoPath附件base64字符串由三部分组成:标题,文件名,和文件内容。标题长度为24个字节,但在字节20处包含文件名的长度。使用该数字乘以2(对于Unicode),然后将提取的文件名提取到新的字节数组中。最后,创建一个新数组来携带内容的字节(全长减去24的起始标题长度和文件名字节),这就是你从base64转换回去的东西。这是我最终做的(仅适用于InfoPath XML文件):

$b64str = $xml.myRootNode.attachmentNode
$bytes = [Convert]::FromBase64String($b64str)
$arrFileNameBytes = @()
$fileNameByteLen = $bytes[20]*2
for($i=0;$i -lt $fileNameByteLen;$i+=2){
  $arrFileNameBytes+=$bytes[24+$i]
}
$arrFileContentBytes = @()
$fileContentByteLen = $bytes.length-(24+$fileNameByteLen)
for($i=0;$i -lt $fileContentByteLen;$i++){
  $arrFileContentBytes+=$bytes[24+$i+$fileNameByteLen]
}
$fileName = [System.Text.Encoding]::ASCII.GetString($arrFileNameBytes)
$fileName = $filename.trim()
$fileName = $filename.substring(0,$filename.length-1)
$filepath = "C:\MyFolder\$fileName"
[IO.File]::WriteAllBytes($filepath,$arrFileContentBytes)

0 个答案:

没有答案
相关问题