我在Powershell中有一个脚本,用于通过与SQL数据库的连接来更新Excel文件。该脚本可以正常工作,但问题是如果一个连接不起作用,脚本将无法继续。有没有办法像超时一样放置东西,这样在哭泣之后还能继续? 这是我拥有的脚本:
$libraryPath = "C:\temp\Excel\"
$excel = new-object -comobject Excel.Application
# Give delay to open
Start-Sleep -s 5
$allExcelfiles = Get-ChildItem $libraryPath -recurse -include “*.xlsx”
foreach ($file in $allExcelfiles)
{
$workbookpath = $file.fullname
Write-Host "Updating " $workbookpath
# Open the Excel file
$excelworkbook = $excel.workbooks.Open($workbookpath)
$connections = $excelworkbook.Connections
foreach ($c in $connections)
{
if ($c.DataFeedConnection -ne $null)
{
$conn = $c.DataFeedConnection.Connection
# Use regex to search and replace part of connection string
$new = $conn -replace 'ProjectName eq ''(.*)''', "ProjectName eq '$title'"
$c.DataFeedConnection.Connection = $new
Write-Host "Connection replaced."
}
}
Start-Sleep -s 5
# This will Refresh All the pivot tables data.
$excelworkbook.RefreshAll()
# The following script lines will Save the file.
Start-Sleep -s 50
$excelworkbook.Save()
$excelworkbook.Close()
}
$excel.quit()
谢谢
答案 0 :(得分:1)
您可以将脚本作为作业运行,如果作业超过给定时间,则将其终止。
view.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
});
将$timeout_in_sec = 10
$excel_update = {
$libraryPath = "C:\temp\Excel\"
$excel = new-object -comobject Excel.Application
# Give delay to open
Start-Sleep -s 5
$allExcelfiles = Get-ChildItem $libraryPath -recurse -include “*.xlsx”
foreach ($file in $allExcelfiles)
{
$workbookpath = $file.fullname
Write-Host "Updating " $workbookpath
# Open the Excel file
$excelworkbook = $excel.workbooks.Open($workbookpath)
$connections = $excelworkbook.Connections
foreach ($c in $connections)
{
if ($c.DataFeedConnection -ne $null)
{
$conn = $c.DataFeedConnection.Connection
# Use regex to search and replace part of connection string
$new = $conn -replace 'ProjectName eq ''(.*)''', "ProjectName eq '$title'"
$c.DataFeedConnection.Connection = $new
Write-Host "Connection replaced."
}
}
Start-Sleep -s 5
# This will Refresh All the pivot tables data.
$excelworkbook.RefreshAll()
# The following script lines will Save the file.
Start-Sleep -s 50
$excelworkbook.Save()
$excelworkbook.Close()
}
$excel.quit()
}
$job = Start-Job -Name 'thing' -ScriptBlock $excel_update
Wait-Job -Timeout $timeout_in_sec -Job $job
if ($job.State -eq 'Running') { Stop-Job -Job $job }
Remove-Job -Job $job
更改为您需要的任何内容。