删除"分享"来自Excel工作簿

时间:2015-02-13 19:07:04

标签: powershell scripting

我正在尝试使用密码将工作簿保存到新位置并保持文件名相同。 filname每周更新一次,并附上一个日期,因此它永远不会相同。有两件事我遇到了麻烦:

  1. 使用SaveAs方法在不同路径中保存具有相同名称的文件&
  2. 我无法添加密码,因为工作簿已共享。
  3. 我在PowerShell中编写了这个脚本,如果可能的话,我想在脚本中取消共享工作簿。不幸的是,我似乎无法找到实现这一目标的方法。这是我到目前为止......我真的很感激任何建议。

    $xls = new-object -com excel.application 
    $xls.Visible = $False
    $xlsWB = $xls.Workbooks.Open("path\*.xlsx")
    $xlsWB.Password = "Password"                                        
    $xlsWB.SaveAs("differentPath\*.xlsx")
    $xls.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xls)
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWB)
    

2 个答案:

答案 0 :(得分:1)

事实证明,可以调用一种方法来更改工作簿的共享状态。这是ExclusiveAccess()。

这是解决问题的工作代码:

$xls = new-object -comObject excel.application 
$xls.Visible = $False
$xls.DisplayAlerts = $False
$xlsWB = $xls.Workbooks.Open("FilePath")
$xlsWB.ExclusiveAccess()
$xlsWB.Password = "AddThisPassword"                                     
$xlsWB.Save()
$xlsWB.Close()
$xls.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xls)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWB)

move "CurrentPath" "NewPath"

一旦我更改了工作簿的共享状态,Password方法就会成功地为工作簿添加密码,解决了OP中描述的第二个问题。我没有使用SaveAs(),而是决定简单地移动文件,这使我无法删除源文件。

谢谢,我希望有人觉得这很有用。

答案 1 :(得分:0)

这是我针对类似问题的尝试。它将删除文件夹结构中文件的MultiUserEditing。

foreach ($file in (Get-ChildItem "C:\path_to_reports\" -File -Filter "*.xls" -recurse))
{
    #The filter seems to also work for *.xlxsx        
    $Excel = New-Object -comobject Excel.Application
    $Excel.Visible = $False
    $Excel.DisplayAlerts = $False

    $ExcelWorkbook = $Excel.workbooks.open($file.fullname)
    If ($ExcelWorkbook.MultiUserEditing -eq "True")
    {
        $ExcelWorkbook.ExclusiveAccess()                                 
        $ExcelWorkbook.Save()
    }
    #close the workbook and not the file
    $ExcelWorkbook.Close()
    #Quit the file
    $Excel.Quit()

    #cleanup
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()

    #more clean up
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelWorkbook) 

    #the most clean up
    Remove-Variable -Name excel
}