从 Excel 工作簿中删除 "sharing"

Remove "sharing" from Excel workbook

我正在尝试使用密码将工作簿保存到新位置并保持文件名不变。电影名每周更新一次,并附加一个日期,所以它永远不会相同。我遇到了两件事:

  1. 使用SaveAs方法将同名文件保存在不同路径&
  2. 我无法添加密码,因为工作簿是共享的。

我正在 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)

原来,有一个方法可以调用来改变工作簿的共享状态。它是 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"

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

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

这是我对类似问题的尝试。它删除了文件夹结构中文件的多用户编辑。

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
}