使用PowerShell在Office 365上刷新Excel连接

有一个Office 365站点包含几个Excel文档,必须每6小时刷新一次连接。 我希望开发一个简单的PowerShell脚本来:

  1. 结帐并打开一个文件。
  2. 刷新连接。
  3. 保存并签入文件。

我编写了这个简单的PowerShell脚本来刷新作为parameter passing的任何path,并向开发者发送成功/电子邮件通知。 我的计划是使用Task Scheduler来安排这个定期执行,传递我的Excel文件的SSL(WebDav)path。

示例path:

 \\microsoft.sharepoint.com@SSL\DavWWWRoot\teams\project\files\Workbook.xlsx 

PowerShell脚本:

 # Configurables $EmailFrom ="norreply.projectemail@gmail.com" $EmailTo = "myemail@domain.com" $SMTPServer = "smtp.gmail.com" $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) $SMTPClient.EnableSsl = $true $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("USERNAME", "PASSWORD") # Open new instance of Excel $excel = New-Object -ComObject Excel.Application $excel.visible = $true # Give delay to open Start-Sleep -s 5 Foreach ($file In $args) { Write-Host "" $fileName = (Split-Path -Path $file -Leaf) If ((Test-Path $file) -And ($excel.Workbooks.CanCheckOut($file))) { Try { # The following code applies only for excel files in document library, can be skiped for others $excelworkbook = $excel.Workbooks.Open($file) $excelworkbook = $excel.Workbooks.CheckOut($file) $excelworkbook = $excel.Workbooks.Open($file) # Opening a second time after checkout is required # Refresh all data connections. Write-Host "Refreshing: ", $file $excelworkbook.RefreshAll() # Checkin the file Start-Sleep -s 15 $excelworkbook.CheckInWithVersion() SendSuccessEmail $fileName } Catch { SendErrorEmail $fileName $_.Exception.Message } } Else { SendErrorEmail $fileName "Unable to locate or checkout file. Please verify file exists and is checked in." } } # Close Excel instance $excel.quit() 

这个效果很好,但只要我的令牌保持活动状态。 我通过单击SharePoint中的“使用资源pipe理器打开”button来执行此操作。 在这一点上,我可以使用我的SSL WebDavpath来访问这些文件。 当令牌第二天到期时,我必须再次点击“用资源pipe理器打开”button来更新。

是否有任何程序化的方式来更新我的令牌,以便我的脚本继续工作超过一天,或者我正在做这个错误的方式吗?