Ошибка vbs требуется объект

I’m getting an «object required» error on line 54, the last line, when I run the following script. What is wrong?

 Option Explicit
Dim cmdString, g_strHostFile, filepath, flexnetpath, importcmd, dtmToday, dtmYesterday, dtmFileDate, param1, param2, param3, i4path, objFSO, objTextStream, g_strComputer, WshShell
'Initialize global constants and variables.
Const FOR_READING = 1
g_strHostFile = "D:dataimportsLUM_servers.txt"
i4path = "C:IFORWINBINi4blt.exe"
filepath = "D:DataImports"
flexnetpath = "C:Program Files (x86)FlexnetManagerAdmin"
importcmd = flexnetpath & "flexnet bulkimport -uadmin -padmin -f" & filepath
dtmToday = Date()
dtmYesterday = Date() - 1
dtmFileDate = Year(Date) & padDate(Month(Date)) & padDate(Day(Date))
param1 = "-r1 -e2,4 -n "
param2 = " -v 'Dassault Systemes' -b "
param3 = " -g "
WScript.Echo "i4Path: " & i4path
WScript.Echo "FilePath: " & filepath
WScript.Echo "flexnetpath: " & flexnetpath
WScript.Echo "importcmd: " & importcmd
WScript.Echo "dtmToday: " & dtmToday
WScript.Echo "dtmYesterday: " & dtmYesterday
WScript.Echo "dtmFileDate: " & dtmFileDate

'Read LUM Server Names from text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(g_strHostFile) Then
  Set objTextStream = objFSO.OpenTextFile(g_strHostFile, FOR_READING)
Else
  WScript.Echo "Input file " & g_strHostFile & " not found."
  WScript.Quit
End If
'Loop through list of computers and perform tasks on each.
Do Until objTextStream.AtEndOfStream
  g_strComputer = objTextStream.ReadLine
WScript.Echo "Processing Server: " & g_strComputer
Set cmdString = i4path & param1 & g_strComputer & param2 & dtmYesterday & param3 & dtmToday & filepath & g_strComputer & "_" & dtmFileDate & "_lum.lrl"
WScript.Echo "Processing Command: " & cmdString
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmdString"
Loop
objTextStream.Close
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "Processing Bulk Import: " & importcmd
WshShell.Run "importcmd"

Function padDate(intNumber)
 if intNumber <= 9 Then
  padDate = "0" & CStr(intNumber)
 Else
  padDate = CStr(intNumber)
 End If
End Function

asked Jul 16, 2010 at 14:49

ChuckO's user avatar

ChuckOChuckO

2,5436 gold badges34 silver badges41 bronze badges

2

Object required is raised when you have a statement like Set x = y where x is not an object type, but is instead an simple type (Integer, Double, Date, etc. ). I think the line

Set cmdString = i4path & param1 & g_strComputer & param2 & ...

is causing the error, and I think all you have to do is remove the Set statement. I think strings do not derive from Object and thus do not need the Set statement.

Wai Ha Lee's user avatar

Wai Ha Lee

8,56381 gold badges57 silver badges92 bronze badges

answered Jul 16, 2010 at 15:08

John Alexiou's user avatar

John AlexiouJohn Alexiou

28.4k11 gold badges76 silver badges133 bronze badges

There are a few problems, I think.

 importcmd = flexnetpath & "flexnet bulkimport -uadmin -padmin -f" & filepath

You probably need some spaces:

 importcmd = flexnetpath & " flexnet bulkimport -uadmin -padmin -f " & filepath

Set is only used with objects, not strings, so it should be removed from this line:

 Set cmdString = i4path & param1 & g_strComputer & param2 & dtmYesterday & param3 & dtmToday & filepath & g_strComputer & "_" & dtmFileDate & "_lum.lrl"

I am fairly sure you either mean

 WshShell.Run importcmd

Or

 WshShell.Run """" & importcmd & """"

answered Jul 16, 2010 at 14:58

Fionnuala's user avatar

FionnualaFionnuala

90.2k7 gold badges113 silver badges152 bronze badges

Could someone tell me why does this line error:

set my_obj = wscript.CreateObject("ObjectTest","pref_")

It gives this error:

Object required: ‘wscript’

If I run this code:

Set WScript = CreateObject("WScript.Shell")
set my_obj = CreateObject("ObjectTest","pref_")

I get this error instead:

Object doesn’t support this property or method: ‘CreateObject’

I’m running the vbscript from within a Delphi app.

Remy Lebeau's user avatar

Remy Lebeau

550k31 gold badges451 silver badges764 bronze badges

asked Feb 3, 2016 at 17:48

Walid's user avatar

1

Object required: ‘wscript’

I’m running the vbscript from within a Delphi app.

This is why your script is failing. The wscript object is only defined when the script is run by wscript.exe. To do what you are attempting, you need to implement your own object and provide it to the script environment for the script code to access when needed.

Assuming you are using IActiveScript to run your script, you can write a COM Automation object that implements the IDispatch interface, and then you can create an instance of that object and give it to the IActiveScript.AddNamedItem() method before then calling IActiveScript.SetScriptState() to start running the script.

For example, write an Automation object that exposes its own CreateObject() method, give it to AddNamedItem() with a name of App, and then the script can call App.CreateObject(). Your CreateObject() implementation can then create the real requested object and hook up event handlers to it as needed. To fire events back into the script, use the IActiveScript.GetScriptDispatch() method to retrieve an IDispatch for the desired procedure defined in the script, and then use IDispatch.Invoke() with DISPID 0 and the DISPATCH_METHOD
flag to execute that procedure with the desired input parameters.

Your object can implement any properties and methods that you want the script to have access to.

answered Feb 4, 2016 at 6:19

Remy Lebeau's user avatar

Remy LebeauRemy Lebeau

550k31 gold badges451 silver badges764 bronze badges

The reason your script is failing is due to a few occurrences.

  1. DO NOT use «WScript» as an object especially while coding in Windows-Based Script Host(or WSH), as the program assumes you are running wscript.exe or calling WScript commands.
  2. Use Dim! If the first rule wasn’t null, this is why. Using command «Option Explicit» in VBScript requires users to Dim any object or calling of an object.

A fixed code would be:

Option Explicit
Dim 1, 2
Set 1 = WScript.CreateObject("WScript.Shell")
Set 2 = WScript.CreateObject("ObjectTest", "pref_")

answered Feb 23, 2021 at 3:05

OhStylerrYT's user avatar

  • Remove From My Forums
  • Question

  • Hello folks, I’ve never used ActiveX jobs before. I put this simple code in the step:

    WScript.Echo «hello world»

    it fails with message:

    Error Source= Microsoft VBScript runtime error  Error Description: Object required: ‘WScript’    Error on Line 0

    I tried to add: Set objShell = CreateObject(«Wscript.Shell»)

    But it fails to save job with this code.

    Can you help me with my confusion please.


    gene

Answers

  • Hi ggolub,

    Per the below reference, the ActiveX Scripting subsystem will be removed from SQL Server Agent in a future version of Microsoft SQL Server, so I would like to suggest
    you try to use CmdExec instead of ActiveX Script, here is a workaround for your issue:

    1.    Save
    the following VB Script to an .txt file and change the suffixes name as .vbs(for example, saved located at G:SQLVB.vbs) :
     

    Dim objShell

    Set objShell = CreateObject(«Wscript.Shell»)

    WScript.Echo «hello world»

    set objShell = nothing

    2.    Create
    an Operation System(CmdExec) step in your job, type the follow command:C:WINDOWSsystem32cscript.exe G:SQLVB.vbs. On the Advanced page, we could specified an output file to record the messages.

    Reference:

    http://msdn.microsoft.com/en-us/library/ms187100.aspx

    Thanks,
    Weilin Qiao


    Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.

    • Proposed as answer by

      Monday, February 7, 2011 3:20 PM

    • Marked as answer by
      WeiLin Qiao
      Monday, February 14, 2011 11:28 AM

  • Active X jobs are deprecated and will be removed in future releases of sql server. Please use Powershell jobs / cmdexec jobs.

    http://msdn.microsoft.com/en-us/library/cc879341(v=sql.110).aspx

    Let us know what you are trying to accomplish. whatever you could do with ActiveX scripting, you can do the same using equivalent powershell statements

    Thanks

    Sethu Srinivasan[MSFT]

    SQL Server

    • Marked as answer by
      WeiLin Qiao
      Monday, February 14, 2011 11:28 AM

  • Remove From My Forums
  • Question

  • Hi,

    I am new to Vbscript. I have got an error :Object required when i tried to unintall the product using the Command line : setup.exe -silent -deinstall -nowait -responseFile»Oracle11g.rsp»

    Below is my code:

    Option Explicit
    Dim SRCDIR, FSO, strRespFile, strCmd, WshShell
    Set SRCDIR = CreateObject(«Scripting.FileSystemObject»).GetFile(WScript.ScriptFullName).ParentFolder
    Set strRespFile = TEMPDIR & «Oracle11g.rsp»
    strCmd = «»»» & SRCDIR & «Installersetup.exe»» -silent -deinstall -nowait » & _
             «-responseFile «»» & strRespFile & «»»»
    WshShell.Run strCmd, 1, True
    If CheckError(SEVERE) Then
     LogMsg «Uninstallation will now abort.», SEVERE
     ExitScript(Err.Number)
    End If

    ‘Wait for the Uninstallation process to complete
    LogEvent «Waiting for process to complete»
    Do While FindProcess(«java.exe»)
     WScript.Sleep(500)
    Loop
    LogMsg «Uninstallation process complete.», INFO

    Please help me.

Answers

  • We must not be seeing all of the VBScript code. And, the error message should have indicated a line number, which you can use to determine the line in the program that raised the error.

    The error might be raised because you are invoking the Run method of the wshShell object, but that object has not been Set. You appear to missing:

    Set wshShell = CreateObject("Wscript.Shell")

    However, we also seem to be missing the code for the methods CheckError, LogMsg, ExitScript, LogEvent, and FindProcess. Are these defined elsewhere?


    Richard Mueller — MVP Directory Services

    • Marked as answer by

      Monday, August 8, 2011 10:05 PM

Перейти к содержимому раздела

Серый форум

разработка скриптов

Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2012-09-16 10:10:04

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Тема: VBScript: WScript — требуется объект

конструкции типа WScript.Echo или WScript.Sleep вызывают ошибку «Требуется объект», даже в чужих работающих примерах. Какие-то компоненты не установлены или в чем может быть причина?

2 Ответ от yuriy2000 2012-09-16 11:48:01

  • yuriy2000
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Скорее всего потому, что Вы примеры используете в скрипте внутри HTML.
Такие конструкции как WScript.Echo или WScript.Sleep  могут быть использованы только если вы используете запуск скрипта через Wscript.exe или Cscript.exe.

3 Ответ от gts 2012-09-16 12:11:05 (изменено: gts, 2012-09-16 12:12:54)

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Спасибо за ответ. Я пытаюсь использовать вышеуказанные конструкции в hta-приложении. Подскажите пожалуйста, как «использовать запуск скрипта через Wscript.exe» на практике (для «чайников»), а если в случае hta-приложения этого сделать нельзя, то как приостановить выполнение скрипта, кроме «вечного цикла».

4 Ответ от yuriy2000 2012-09-16 12:31:57

  • yuriy2000
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

gts пишет:

Подскажите пожалуйста, как «использовать запуск скрипта через Wscript.exe» на практике (для «чайников»), а если в случае hta-приложения этого сделать нельзя, то как приостановить выполнение скрипта, кроме «вечного цикла».

Использовать скрипт очень просто — создайте файл с расширением .VBS  и запускайте его.
Для удобства работы с большим потоком выводимых данных необходимо использовать Cscript, т.к. при запуске через WScript.exe метод WScript.Echo  эквивалентен MsgBox.

Использование: CScript имя_сценария.расширение [параметры…] [аргументы…]

Параметры:
//B            Пакетный режим: подавляются отображение ошибок и запросов сценария
//D            Включение режима Active Debugging
//E:ядро       Использование указанного ядра для выполнения сценария
//H:CScript    Стандартный сервер сценариев заменяется на CScript.exe
//H:WScript    Стандартный сервер сценариев заменяется на WScript.exe (по умолчанию)
//I            Диалоговый режим (по умолчанию, в противоположность //B)
//Job:xxxx     Выполнение указанного задания WSF
//Logo         Отображать сведения о программе (по умолчанию)
//Nologo       Не отображать сведения о программе во время выполнения
//S            Сохранить для данного пользователя текущие параметры командной строки
//T:nn         Интервал ожидания (в секундах):  максимальное время выполнения сценария
//X            Выполнение сценария в отладчике
//U            Использование кодировки Юникод при перенаправлении ввода-вывода с консоли

5 Ответ от gts 2012-09-16 15:06:34

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Спасибо, т.е., если я вынесу часть кода во внешний vbs-файл и запущу WScript или Cscript c ним в качестве сценария из html-страницы или hta-приложения методами ShellExecute или Run, то объект Wscript.Sleep сработает?

6 Ответ от alexii 2012-09-16 15:42:20

  • alexii
  • Разработчик
  • Неактивен

Re: VBScript: WScript — требуется объект

Сработает. Но на HTA это не отразится.

7 Ответ от gts 2012-09-16 16:21:37 (изменено: gts, 2012-09-16 16:23:24)

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Спасибо за участие, очевидно, запуск WScript.exe методами Run и ShellExecute создает отдельный процесс, на который и действует код сценария-параметра. Но есть же какой-то способ приостановить hta-приложение на время загрузки Excel, вызываемого из скрипта в hta, не загружая процессор циклом? Ведь если делать опрос наступления события, а оно не наступит? И какое время ожидания считать приемлемым в зависимости от техники?  Может быть, есть какой либо-метод Shell.Application или WScript.Shell — эти объекты доступны, но я не нашла ничего подходящего. Или можно как-то воспользоваться ответами на тему «CMD/BAT: sleep штатными средствами», но чтобы это воздействовало на заданную работающую в ОС задачу, т.е. что-то на уровне ОС, а не изнутри самой задачи?

8 Ответ от Serge Yolkin 2012-09-16 17:13:05

  • Serge Yolkin
  • Разработчик
  • Неактивен
  • Рейтинг : [1|0]

Re: VBScript: WScript — требуется объект

Способа приостановить скрипт в .hta приложении, в общем-то нет. Есть трансляция WScript в hta, но лучше, по возможности, изменить алгоритм самого скрипта так, чтобы можно было использовать setTimeOut и setInterval.

9 Ответ от gts 2012-09-16 17:45:27

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Спасибо

10 Ответ от alexii 2012-09-16 17:49:44

  • alexii
  • Разработчик
  • Неактивен

Re: VBScript: WScript — требуется объект

11 Ответ от gts 2012-09-16 18:55:00

  • gts
  • Участник
  • Неактивен
  • Рейтинг : [0|0]

Re: VBScript: WScript — требуется объект

Спасибо, буду изучать

Сообщения 11

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

  • Ошибка v71 passat b6
  • Ошибка vbe6ext olb could not be loaded что делать
  • Ошибка v159 passat b6
  • Ошибка vba out of stack space
  • Ошибка v158 пассат б6