使用 PowerShell 从 SharePoint 打开 Excel 文档

Opening an Excel document from SharePoint using PowerShell

我正在尝试使用 PowerShell 从 SharePoint 打开 Excel 工作簿。我没有加载 SharePoint 管理单元——我没有。

当 PowerShell 尝试启动工作簿时,SharePoint 会提示输入凭据。问题是我们正在尝试安排脚本,我们希望脚本具有类似 SSO 的体验。

这是 MWE:

$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open(http://site/file.xlsx)
$Worksheet = $Workbook.Sheets.Item($WorksheetName)
$Excel.Visible = $false

# some Excel manipulation

$Workbook.Close($false)
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
Remove-Variable Excel

首先将SharePoint文件下载到本地,然后打开、操作等

下面的示例使用用户 运行 script/PowerShell 会话的默认凭据。

$fromfile = "http://site/file.xlsx"
$tofile   = "c:\somedirectory\file.xlsx"

$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
$webclient.DownloadFile($fromfile, $tofile)

$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open($tofile)
$Worksheet = $Workbook.Sheets.Item($WorksheetName)
$Excel.Visible = $false

# some Excel manipulation

$Workbook.Close($false)
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
Remove-Variable Excel

我最近 运行 遇到了同样的问题。 我没有保存到本地机器就解决了

COM Excel 对象的工作簿 属性 有一个名为 CheckIn 和 CheckOut 的方法。您将需要同时使用两者。

此外,要直接从 Sharepoint 打开文件,只需在 Sharepoint 页面上找到库,在资源管理器中打开它。 你会得到这样的东西:

http://sitename/sites/TeamSite/FileLibrary/

您只需要像这样替换 UNC 路径的路径:

\sitename\sites\TeamSite\FileLibrary\

(开头有双反斜杠)

$ExcelObject = New-Object -ComObject Excel.Application

$ExcelWorkBook = $ExcelObject.Workbooks.Open("\sitename\sites\TeamSite\FileLibrary\test.xlsx")
$ExcelObject.Workbooks.CheckOut("\sitename\sites\TeamSite\FileLibrary\test.xlsx")

$ExcelWorkSheet = $ExcelWorkBook.Sheets.Item(1)

#This part selects the A:1 cell and changes it's value.
$ExcelWorkSheet.Cells.Item(1,1) = "Edited text"

$ExcelWorkBook.Save()
$ExcelWorkBook.CheckIn()