Powershell script stops working when starting task scheduler

I am running the script below as a scheduled task with a user logged in to the server. It converts the xls file to csv using the Excel.Application COM object. The conversion works, but eventually breaks down, and I don't know why.

I have a task to run the following command, which should theoretically allow it to work constantly:

powershell.exe -noexit -file "filename.ps1"

Any thoughts on what to try?

 $server = "\\server" $xls = "\path\XLS\" $csv = "\path\CSV\" $folder = $server + $xls $destination = $server + $csv $filter = "*.xls" # <-- set this according to your requirements $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ IncludeSubdirectories = $true # <-- set this according to your requirements NotifyFilter = [IO.NotifyFilters]"FileName, LastWrite" } Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { $path = $Event.SourceEventArgs.FullPath $name = $Event.SourceEventArgs.Name $changeType = $Event.SourceEventArgs.ChangeType $timeStamp = $Event.TimeGenerated $excelFile = $folder + $name $E = New-Object -ComObject Excel.Application $E.Visible = $false $E.DisplayAlerts = $false $wb = $E.Workbooks.Open($excelFile) foreach ($ws in $wb.Worksheets) { $n = "output_" + $name -replace ".XLS" $ws.SaveAs($destination + $n + ".csv", 6) } $E.Quit() } 
+5
source share
1 answer

I did something similar with the word. I could not use only Quit . I think using Quit hides Excel. Try freeing the com object using:

 $E.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($E) Remove-Variable E 

I don't know if you are opening an Excel application, but if you can use

 $wb.close($false) 

Let me know if this works ...

Link: https://technet.microsoft.com/en-us/library/ff730962.aspx?f=255&MSPPError=-2147217396

0
source

Source: https://habr.com/ru/post/1269375/


All Articles