通过SQL Server作业代理或Windows Scheduler执行涉及VB脚本的Windows shell命令

时间:2018-02-27 23:33:32

标签: sql-server vbscript xlsx sql-server-agent sql-server-job

我遇到了通过SQL Server代理和Windows调度程序执行涉及VB脚本的shell命令的问题(我试图让这些选项中的至少一个起作用)。

从Windows命令提示符手动执行时,该命令运行并完成。下面是实际命令(它包含一个带有两个参数的VB脚本):

XlsxToCsv.vbs DataDictionaries.xlsx DataDictionaries.csv

XlsxToCsv.vbs是一个VB脚本,可以编辑xlsx文件并将其转换为csv格式。

当我安排上述命令通过SQL Server作业代理运行时,它开始运行VB脚本,完成其第一步,但随后排序永不结束或不继续。它应该创建的文件不会被创建。所以工作步骤一直在运行,永远不会结束。

以下是VB脚本中的内容:

'1. Delete the CSV file.
dFile = WScript.Arguments.Item(1)
SET oFso = CREATEOBJECT("Scripting.FileSystemObject")
oFso.DeleteFile dFile

'2. Read the input Excel file, replace , with c1o2m3m4a5 and save the file as csv, using the second parameter as the csv file name.
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
Dim oSheet
Set oSheet = oBook.Worksheets(1)
Dim oRange
Set oRange = oSheet.UsedRange
oRange.Replace ",", "c1o2m3m4a5"
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit

似乎当由SQL Server代理执行时,上面的VB脚本会暂停"暂停"在某个地方,正在等待什么。但是我很困惑,因为它从MS-DOS提示符(或命令提示符,但没有通过power-shell尝试它)运行得很好。

任何人都可以发现VB脚本的问题,或者是否还需要通过SQL Server代理正确执行上述命令?

请帮助:)

1 个答案:

答案 0 :(得分:0)

  1. 由于在执行期间显示警报,脚本未继续。 以下命令关闭警报: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-displayalerts-property-excel
  2. oExcel.DisplayAlerts = False
    
    1. 我还需要确保SQL Server代理用户对该链接中讨论的特殊目录具有完全权限。 http://justgeeks.blogspot.com/2012/10/troubleshooting-microsoft-excel-cannot.html
    2. 最终脚本看起来像这样,并且没有问题就执行了:

      'Define an object to reference MS Excel application.
      Dim oExcel
      Set oExcel = CreateObject("Excel.Application")
      
      'Turn-off alerts and messages for the MS Excel application object.
      oExcel.DisplayAlerts = False
      
      'Define an object to open and hold an Excel file/workbook.
      Dim oBook
      Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
      
      'Define an object to open and hold an Excel worksheet.
      Dim oSheet
      Set oSheet = oBook.Worksheets(1)
      
      'Define an object and read and store the data from an Excel worksheet.
      Dim oRange
      Set oRange = oSheet.UsedRange
      
      'Replace all the commas in the Excel worksheet object with    pattern "c1o2m3m4a5"
      oRange.Replace ",", "c1o2m3m4a5"
      
      'Save the edited Excel worksheet object into the CSV file 
      '(CSV file name must be passed as the 2nd parameter when running this     script).
      oBook.SaveAs WScript.Arguments.Item(1), 6
      
      'Close the Excel file/workbook.
      oBook.Close False
      
      'Quit the MS Excel. End of the script.
      oExcel.Quit