我在通过PowerShell打开电子表格,重命名工作表,保存和关闭Excel时遇到问题。问题是第一次$WorkBook
变量为空时运行。如果我第二次运行它脚本工作正常。此外,如果我添加$ExcelDoc.Visible = $true
脚本工作正常。有没有人知道为什么脚本首先以下面的形式运行它失败?
$Path = "C:\ScriptRepository\CQC\DataToLoad\"
$FileName = (Get-ChildItem $Path).FullName
$FileName2 = (Get-ChildItem $Path).Name
Start-Sleep 2
$ExcelDoc = New-Object -ComObject Excel.Application
$WorkBook = $ExcelDoc.Workbooks.Open($FileName)
$WorkSheet = $WorkBook.Worksheets.Item(2)
$WorkSheet.Name = "CQCProviders"
$WorkBook.Save()
$WorkBook.Close()
$ExcelDoc.Quit()
While([System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelDoc)) {}