【发布时间】:2021-01-06 03:29:06
【问题描述】:
我编写了一个简短的 Powershell 脚本来复制一些 Excel 数据。该脚本运行良好,但每次运行它都会打开 Excel,即使可见属性设置为 $false。任何人有任何想法为什么?我已经搜索了答案,但找不到任何解决方案。我还显示了该属性并且设置正确。
打开工作簿时会打开 Excel。
谢谢,
克里斯·J。
代码:
## function to close all com objects
function Release-Ref ($ref{
([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
#Read-Host -Prompt "Press Enter to exit"
#####################################################################
## Load excel com objects attach to file
#####################################################################
$ExcelPath = 'C:\Chris_Test.xls'
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $False
write-host "Visible 1"
write-host $Excel.Visible
$ExcelWorkBook = $Excel.Workbooks.Open($ExcelPath)
$Excel.Visible = $False
write-host "Visible 2"
write-host $Excel.Visible
$ExcelWorkSheet = $Excel.WorkSheets.item("Sheet1")
$Excel.Visible = $False
write-host "Visible 3"
write-host $Excel.Visible
$row = 2
$South_HX_Avg = "This"
$Middle_HX_Avg = " is a "
$North_HX_Avg = "test."
##
## Cells.Item(Row,Column)
#$ExcelWorkSheet.Cells.Item($row,1).Value2 = $South_HX_Avg
#$ExcelWorkSheet.Cells.Item(2,2).Value2 = $Middle_HX_Avg
#$ExcelWorkSheet.Cells.Item(2,3).Value2 = $North_HX_Avg
#####################################################################
# Close connections to Excel
# set interactive to false so no save buttons are shown
#####################################################################
$Excel.DisplayAlerts = $false
$Excel.ScreenUpdating = $false
$Excel.Visible = $False
write-host "Visible 4"
write-host $Excel.Visible
$Excel.Visible = $false
$Excel.Visible = $False
write-host "Visible 5"
write-host $Excel.Visible
$Excel.UserControl = $false
$Excel.Interactive = $false
## save the workbook
$ExcelWorkBook.Save()
## quit the workbook
$Excel.Quit()
## close all object references
Release-Ref($ExcelWorkSheet)
Release-Ref($ExcelWorkBook)
Release-Ref($Excel)
# Move-Item c:\scripts\test.zip c:\test -force
Read-Host -Prompt "Press Enter to exit"
【问题讨论】:
-
您是否尝试过重新启动,只是为了确保您没有卡在内存中的东西导致这样做?该代码看起来应该做你想做的事。
-
Release-Ref 函数解析不正确,我认为您缺少右括号或大括号..
标签: excel powershell com visible