使用powershell查找word和excel文档的Last Saved By

时间:2011-04-13 07:47:51

标签: excel powershell ms-word ms-office

我有一个包含子文件夹的文件夹,我想运行一个PowerShell脚本,找到所有办公文档(目前是word和excel 2003,2007和2010)并打印我们可以找到的“上次保存的”属性在文件的属性,详细信息选项卡上。

有人可以帮忙吗?

---解决方案---

$word = New-Object -Com Word.Application
$word.Visible = $false #to prevent the document you open to show
$doc = $word.Documents.Open($path)

$binding = "System.Reflection.BindingFlags" -as [type]
Foreach($property in $doc.BuiltInDocumentProperties) {
   try {
      $pn = [System.__ComObject].invokemember("name",$binding::GetProperty,$null,$property,$null)
      if ($pn -eq "Last author") {
         $lastSaved = [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null)
         write-host "Last saved by: "$lastSaved      
      }        }
   catch { }
}

$doc.Close()
$word.Quit()

对正确的答案做了一些调整,现在它正在运作。

1 个答案:

答案 0 :(得分:5)

这并不像人们希望的那么容易。您可以使用

轻松打开Powershell中的Word文档
$word = New-Object -COM Word.Application
$word.Visible = $false #to prevent the document you open to show
$doc = $word.Document.Open("path-to-document")

但是文档属性存储在属性BuiltInDocumentProperties中,它本身就是动态COM对象(因此不能直接使用)

我使用的方法是遍历每个属性,然后检索值:

$binding = "System.Reflection.BindingFlags" -as [type]
Foreach($property in $doc.BuiltInDocumentProperties) {
   try {
      $pn = [System.__ComObject].invokemember("name",$binding::GetProperty,$null,$property,$null)
      if ($pn -eq "Last save time") {
         $lastSaved = [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null)
      }
   }
   catch { }
}

只需打印$ pn变量即可获取所有可用属性的名称。