3

A little assistance with this, I'm trying to dynamically insert Pictures into a word document. Little background, I have a folder of about 1000 png's I wish to insert each png into it's own word document, and then save as a word .docx(Saving I know how to get), currently I have a loop to get each document, but I can't seem to figure out how to Add the picture, without hardcoding each file's path. Please Advise, still kinda new to powershell

    $Source = "C:\test"

$word_app = New-Object -ComObject word.application

Get-Childitem -Path $Source -recurse |  Where-Object { $_.extension -eq  ".png"} | % {
  $word_app.Visible = $True  
  $objDoc = $word_app.Documents.Add()  
  $objSelection = $word_app.Selection 

  $objShape = $word_app.Shapes 
  [void] $objShape.AddPicture() 
}
2
  • For each iteration of your ForEach-Object (%), the current .png file will be represented by $_.
    – root
    Commented Jan 22, 2019 at 19:17
  • 1
    And don't forget to save.
    – harrymc
    Commented Jan 22, 2019 at 19:58

1 Answer 1

1
$Source = Get-Childitem -Path C:\test -recurse |  Where-Object { $_.extension -eq  '.png'}
    $word_app = new-object -comobject word.application

     ForEach ( $i in $Source ) {
        $word_app.Visible = $True
        $objDoc = $word_app.documents.add()
        $objSelection = $word_app.Selection
        $ImageName = $i.FullName
        $objSelection.InlineShapes.AddPicture($ImageName)
        $objSelection.InsertCaption(-1, "`t $i")
        $filename = "c:\\test\\” + $i.BaseName + ".docx"
        $objDoc.SaveAs([REF]$filename)
        $objDoc.Close()
     }

    # Close Word
    $word_app.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objDoc)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .