从powershell脚本中生成的Excel不会退出

时间:2018-03-30 20:47:59

标签: excel powershell com

我们正在迁移数据库,因此我使用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

1 个答案:

答案 0 :(得分:0)

也许改变:

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

你的工作完成后。