【问题标题】:Excel spawned from powershell script not quitting [duplicate]从powershell脚本产生的Excel没有退出[重复]
【发布时间】:2018-03-30 20:47:58
【问题描述】:

我们正在迁移数据库,因此我使用 powershell 将数百个引用旧数据库实例的 excel 文件修改为新文件。这一切都很好,可以按预期工作。我遇到的问题是完成后 Excel 应用程序不会退出。该进程将作为后台进程挂起,我需要进入任务管理器来杀死它。没什么大不了的,但很烦人。这是我的脚本。我使用的是 powershell v5 和 Office 2016。

    param(
    [string]$search_root=$(throw "missing search root parameter"),
    [boolean]$test=$true
)
echo $search_root

$NAMEPOSTFIX = '-Updated'
$OLDCONN = 'Data Source=abc;'
$NEWCONN = 'Data Source=xyz;'

$filelist = Get-ChildItem -Path $search_root *.xls* -Recurse -Exclude '*Updated.*'
$Excel = New-Object -Com Excel.Application
$Excel.DisplayAlerts = $False

function update_con_xls{
    param($file)    
    $Workbook = $Excel.Workbooks.Open($file)
    foreach($con in $Workbook.Connections){
        if ($con.OLEDBConnection -ne $null){
            $con.OLEDBConnection.Connection = $con.OLEDBConnection.Connection.Replace($OLDCONN,$NEWCONN)
        }
        if ($con.ODBCConnection -ne $null){
            $con.ODBCConnection.Connection = $con.ODBCConnection.Connection.Replace($OLDCONN,$NEWCONN)
        }
    }
    $Workbook.Save()
    $Workbook.saved = $true
    $Excel.Workbooks.Close()
}

foreach ($file in $filelist) {
    echo $file
    if ($file.Extension -eq '.xls' -or $file.Extension -eq '.xlsx') {
        $newfile = ($file.DirectoryName + '\' + $file.BaseName + $NAMEPOSTFIX + $file.Extension)
        if($test){
            echo $test
            $newfile = ('C:\test\' + $file.Name) #for test run to copy coppy locally 
        }
        Copy-Item $file.FullName -Destination $newfile
        update_con_xls($newfile)
    }
}
$Excel.Quit()
$Excel = $null

【问题讨论】:

标签: excel powershell com


【解决方案1】:

也许会改变:

$Excel.Workbooks.Close()

到:

$Excel= New-Object -ComObject Excel.Application;

$Workbook = $Excel.Workbooks.Open($file);
$Workbook.Save();
$Workbook.Close(); # <--- try

$Excel.Quit();
Remove-Variable -Name Excel;

我在这里看不到任何可以关闭您尝试添加的 ODB 和 OLEDb 连接的内容:

$con.OLEDBConnection.Connection.Close();
$con.ODBCConnection.Connection.Close();

$con.OLEDBConnection.Close();
$con.ODBCConnection.Close();

在你的工作完成之后。

【讨论】:

  • 不,这并没有改变任何东西。连接也永远不会打开。我只是在改变它所指向的属性。我什至可以创建 $Excel 对象,然后立即关闭并删除变量,它仍然保留在运行内存中。
  • 好的,试试 $workbook.SaveAs($outputfile); ,因为 Save() 函数可能会阻塞?
  • 这项工作适合我:$workbook.SaveAs($outputfile); $workbook.Close(); $excel.Quit(); Remove-Variable -Name excel;
  • 另外,你有没有试过把:$Excel.Visible = $false;
  • 从这里stackoverflow.com/questions/27798567/…:文档推荐使用FinalReleaseComObject方法彻底释放COM对象,一劳永逸地关闭Excel进程。
猜你喜欢
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多