Opening an Excel document from SharePoint using PowerShell

我是研究僧i 提交于 2019-12-23 04:20:17

问题


I'm trying to open an Excel workbook from SharePoint using PowerShell. I'm not loading the SharePoint snap-in—I do not have it.

When PowerShell tries to launch the workbook, SharePoint prompts for credentials. The problem is that we're trying to schedule the script, and we would like the script to have an SSO-like experience.

Here's the 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

回答1:


First, download the SharePoint file locally, then open, manipulate, etc.

The example below uses the default creds of the user running the script/PowerShell session.

$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



回答2:


I have recently run into the same issue. I solved it without saving it to the local machine.

The COM Excel object's WorkBook property has a method so called CheckIn and CheckOut. You will need to use both.

Also, to directly open a file from Sharepoint, just go for the library on the Sharepoint page, open it in explorer. You will get something like this:

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

You only need to replace the path for an UNC path like this:

\\sitename\sites\TeamSite\FileLibrary\

(With Double backslash at the begininning)

$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()


来源:https://stackoverflow.com/questions/42676858/opening-an-excel-document-from-sharepoint-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!