#---------------------------------------------------------------------------------------------------------------------
#  Script:   Download Attachments
#  Author:   www.xapity.com
#  Date:     12-10-2016
#  Version:  1.0
#  Comments: Used in a Xapity PowerShell Activity to copy attachments from the Parent work item to local disk
#
#---------------------------------------------------------------------------------------------------------------------
Import-Module SMLets -Force

$AttachmentStore="C:\Temp\AttachmentStore\"
$AttachmentPath = $AttachmentStore + $ParentID + "\"

$ParentObject = Get-SCSMObject -Id $ParentGUID 
$WorkItemHasAttachMentClass = Get-SCSMRelationshipClass -name System.WorkItemHasFileAttachment$
$files = Get-SCSMRelatedObject -SMObject $ParentObject -Relationship $WorkItemHasAttachMentClass

If($files -ne $Null)
 {
   New-Item -Path $AttachmentPath -ItemType "directory" -Force | Out-Null
   Write-host "Created folder: $attachmentPath"
   foreach ($attachment in $Files)
         {
           Try {
                   $fs = [IO.File]::OpenWrite(($AttachmentPath + $attachment.DisplayName))
                  $memoryStream = New-Object IO.MemoryStream
                  $buffer = New-Object byte[] 8192
                  [int]$bytesRead|Out-Null
                  while (($bytesRead = $attachment.Content.Read($buffer, 0, $buffer.Length)) -gt 0)
                     {
                        $memoryStream.Write($buffer, 0, $bytesRead) 
                     }        
                  $memoryStream.WriteTo($fs)  
                     }
            Finally
               {
                $fs.Close()
                $memoryStream.Close()
                write-host "Dowloaded: $attachment.name"
               }
         } #End of ForEach
   } #End of IF