I write some data to an excel file and when I run my code again I want to delete the file and create the file again
Issue is that it says PowerShell is locking the file .
<I get the $email object here, $email>
$outputFile = "d:testfile.xlsx"
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Add()
$sheet = $workbook.Worksheets.Item(1)
$row = 1
$sheet.Cells.Item($row, 1) = "Subject"
$sheet.Cells.Item($row, 2) = "Body"
$row++
$sheet.Cells.Item($row, 1) = $email.Subject
$sheet.Cells.Item($row, 2) = ($email.Body.Content[0..1999] -join '')
and then run the following
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Remove-Variable workbook, excel
When I run this code again it says that the file is being used by another process ie PowerShell
How can I delete the file everytime before I start ?
I have tried deleting from the start but it says the file is locked . Its as if PowerShell hasn’t released it