Powershell动态将图片添加到Word

Powershell动态将图片添加到Word

需要一点帮助,我正在尝试将图片动态插入到 word 文档中。背景知识,我有一个大约有 1000 个 png 的文件夹,我希望将每个 png 插入到它自己的 word 文档中,然后另存为 word .docx(保存我知道如何获取),目前我有一个循环来获取每个文档,但我似乎无法弄清楚如何添加图片,而无需对每个文件的路径进行硬编码。请指教,对 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() 
}

答案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)

相关内容