通过任务计划程序运行时,Powershell脚本停止工作

时间:2017-06-30 17:00:12

标签: excel powershell scripting

我正在运行下面的脚本作为计划任务,用户登录服务器。它使用Excel.Application COM对象将xls文件转换为csv。转换有效,但最终会中断,我不知道为什么。

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

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

关于尝试什么的任何想法?

$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 个答案:

答案 0 :(得分:0)

我正在用言语做类似的事情。我不能单独使用Quit。我认为使用Quit会隐藏Excel。尝试使用以下命令释放com对象:

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

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

$wb.close($false)

让我知道它是否有效......

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