Powershell脚本在运行任务调度程序时停止工作

时间:2022-06-01 19:14:24

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

我将运行下面的脚本作为一个预定任务,用户已登录到服务器上。它使用Excel将xls文件转换为csv。应用COM对象。这种转变是有效的,但最终还是失败了,我不知道为什么。

I have the task run the following command which should in theory allow it to run constantly:

我让任务运行以下命令,理论上应该允许它持续运行:

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

powershell。exe - file”filename.ps1 noexit

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()     
}

1 个解决方案

#1


0  

I was doing something similar with word. I couldnt use Quit alone. I think using Quit hides Excel. Try releasing the com object by using:

我在做类似的事情。我不能一个人戒烟。我认为使用Quit隐藏了Excel。尝试释放com对象,使用:

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

i dont know if you are opening the Excel application but if you are you can maybe use

我不知道你是否正在打开Excel应用程序,但如果是的话,你可以使用

$wb.close($false)

Let me know if it works...

如果有用,请告诉我……

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

裁判:https://technet.microsoft.com/en - us/library/ff730962.aspx?f=255&mspperror= 2147217396

#1


0  

I was doing something similar with word. I couldnt use Quit alone. I think using Quit hides Excel. Try releasing the com object by using:

我在做类似的事情。我不能一个人戒烟。我认为使用Quit隐藏了Excel。尝试释放com对象,使用:

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

i dont know if you are opening the Excel application but if you are you can maybe use

我不知道你是否正在打开Excel应用程序,但如果是的话,你可以使用

$wb.close($false)

Let me know if it works...

如果有用,请告诉我……

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

裁判:https://technet.microsoft.com/en - us/library/ff730962.aspx?f=255&mspperror= 2147217396