Меню

Ошибка недопустимый знак vbs

VBS

Сообщение «Ошибка: Недопустимый знак» при запуске скрипта

04.08.2016, 17:16. Показов 8619. Ответов 1


Здравствуйте. С VBS так вплотную не раотаю, по этому если проблема очевидна то не бросайтесь тапками… В общем при запуске vbs выдаёт ошибку : Строка 5, символ 29, недопустимый знак. Вот сам код:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Const EmailFrom = “****@mail.ru”      ‘ от кого будет отправляться e-mail
Const EmailPassword = “123456″          ‘ пароль от e-mail
Const strSmtpServer = “ smtp.mail.ru”  ‘ smtp сервер
Const EmailTo = “****@mail.ru”        ‘ Кому будет отправляться e-mail
Set objEmail = CreateObject(”CDO.Message”)
 
objEmail.From = EmailFrom
objEmail.To = EmailTo
objEmail.Subject = “Здесь должен быть текст заголовка”
objEmail.Textbody = “Текста Вашего письма”
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/sendusing”[/url]) = 2
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/smtpauthenticate”[/url]) = 1
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/sendusername”[/url]) = EmailFrom
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/sendpassword”[/url]) = EmailPassword
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/smtpserver”[/url]) = strSmtpServer
objEmail.Configuration.Fields.Item (”[url]http://schemas.microsoft.com/cdo/configuration/smtpserverport”[/url]) = 25
objEmail.Configuration.Fields.Update
objEmail.Send
WScript.Quit

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Я получаю сообщение об ошибке компиляции, когда пытаюсь запустить следующий код vbs из командной строки в Windows 7.

Option Explicit
Dim objNetwork, strRemotePath1, strRemotePath2, strRemotePath3
Dim strDriveLetter1, strDriveLetter2, strDriveLetter3, strUserName

Set objNetwork = CreateObject("WScript.Network")
strUserName = objNetwork.UserName 

strDriveLetter1 = "H:"
strDriveLetter2 = "P:"
strDriveLetter3 = "S:"
strRemotePath1 = "\testpublicusers" & strUserName & ""
strRemotePath2 = "\testpublicgroups"
strRemotePath3 = "\testscans"


'Section which maps two drives, M: and P: and S:
objNetwork.MapNetworkDrive strDriveLetter1, strRemotePath1
objNetwork.MapNetworkDrive strDriveLetter2, strRemotePath2
objNetwork.MapNetworkDrive strDriveLetter3, strRemotePath3

'Extra code just to add a message box
WScript.Echo "Map drives " & strDriveLetter1 & " & " & strDriveLetter2 & " & " & strDriveLetter3

Wscript.Quit

В нем говорится, что проблема связана с линией 1, символ 1. Есть идеи?

3 ответы

Возможная проблема заключается в том, как был закодирован ваш файл; попробуйте сохранить его как ANSI и запустить снова.

Создан 10 янв.

FYI для тех, у кого такая же проблема в будущем, чтобы исправить это:

  1. Откройте .vbs в блокноте
  2. Перейти к файлу и «сохранить как»
  3. Прямо под полем имени файла вы увидите раскрывающееся меню для кодирования. Выбирать ANSI.

ответ дан 31 окт ’13, 17:10

Убедитесь, что вы не используете расширенный символ, например á é í ó ú ñ в имени переменной

Создан 07 фев.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

vbscript

or задайте свой вопрос.

I get a compilation error when I try to run the following vbs code from a command prompt in Windows 7 Vista. I’ve already Coverted it to ANSI but it still has the same problem

Set wshShell =wscript.CreateObject(“WScript.Shell”)
do
wscript.sleep 100
wshshell.sendkeys “{CAPSLOCK}”
wshshell.sendkeys “{NUMLOCK}”
wshshell.sendkeys “{SCROLLLOCK}”
loop

it says the issue is in Line 1 Char 36… Got Any Ideas?

asked Apr 7, 2015 at 21:42

Dylan Mercedes's user avatar

This should works just give a try :

Because this is diffrent from this « and this diffrent from «

Set wshShell = CreateObject("WScript.Shell")
do
wscript.sleep 100
wshshell.sendkeys "{CAPSLOCK}"
wshshell.sendkeys "{NUMLOCK}"
wshshell.sendkeys "{SCROLLLOCK}"
loop

answered Apr 7, 2015 at 21:56

Hackoo's user avatar

HackooHackoo

18k3 gold badges40 silver badges67 bronze badges

You used Word as an editor, Word uses smart quotes. Autocorrect in Word changes » to opening and closing printers’s quotes (ie 66 and 99).

Press Ctrl + Z to undo the change while typing or change options in Tools — Options — Autocorrect.

answered Apr 7, 2015 at 23:04

Serenity's user avatar

I get a compilation error when I try to run the following vbs code from a command prompt in Windows 7 Vista. I’ve already Coverted it to ANSI but it still has the same problem

Set wshShell =wscript.CreateObject(“WScript.Shell”)
do
wscript.sleep 100
wshshell.sendkeys “{CAPSLOCK}”
wshshell.sendkeys “{NUMLOCK}”
wshshell.sendkeys “{SCROLLLOCK}”
loop

it says the issue is in Line 1 Char 36… Got Any Ideas?

asked Apr 7, 2015 at 21:42

Dylan Mercedes's user avatar

This should works just give a try :

Because this is diffrent from this « and this diffrent from «

Set wshShell = CreateObject("WScript.Shell")
do
wscript.sleep 100
wshshell.sendkeys "{CAPSLOCK}"
wshshell.sendkeys "{NUMLOCK}"
wshshell.sendkeys "{SCROLLLOCK}"
loop

answered Apr 7, 2015 at 21:56

Hackoo's user avatar

HackooHackoo

18k3 gold badges40 silver badges67 bronze badges

You used Word as an editor, Word uses smart quotes. Autocorrect in Word changes » to opening and closing printers’s quotes (ie 66 and 99).

Press Ctrl + Z to undo the change while typing or change options in Tools — Options — Autocorrect.

answered Apr 7, 2015 at 23:04

Serenity's user avatar

Troubleshooting Code 800A0408 – Invalid Character

Introduction to Code 800A0408

This error code, 800A0408 occurs when you execute a VBScript.  A wild guess a problem with an apostrophe, possibly in a ‘REM statement.Code  Error 800A0408 - Invalid Character

The Symptoms You Get

The script does not execute as you had hoped. Instead you get a WSH message box like this picture:

The Cause of error 800A0408

Your VBScript contains an illegal character, often at the beginning of a line.  It can happen if you copy the script from word, then paste into notepad.  For example, to ‘Rem out a line we need the apostrophe, which is ASCII character 39; however if you paste from word you may get ASCII 96 (Grave accent).

Note the clue Source: Microsoft VBScript compilation error, this means a syntax error in your script.

The Solutions

Check the punctuation marks in your VBScript, particularly look out for apostrophes and commas that do not display correctly.  The reference to Line: 1 Char 1, means that the very first symbol that is probably wrong.

  ‡

Example 1 of error code 800A0408 – Invalid Character

Note: The error  Rem VBScript

It should be ‘ Rem VBScript

  Rem VBScript
Set WshShell = WScript.CreateObject(«WScript.Shell»)
Set WshNetwork = WScript.CreateObject(«WScript.Network»)
Set AllDrives = WshNetwork.EnumNetworkDrives()

DriveLetter = «N:» ‘must be capitalized
RemotePath = «alanhome»

AlreadyConnected = False
For i = 0 To AllDrives.Count – 1 Step 2
If AllDrives.Item(i) = DriveLetter Then AlreadyConnected = True
Next

If AlreadyConnected = False then
WShNetwork.MapNetworkDrive DriveLetter, RemotePath
WshShell.PopUp «Drive » & DriveLetter & » connected successfully.»

Else
WShNetwork.RemoveNetworkDrive DriveLetter
WshShell.PopUp «Drive » & DriveLetter & » disconnected.»
End if

»

Example 2 Code 800A0408 – Invalid Character

I include this screen shot just to emphasise that Char: number need not be one.  Thus Char: 20, or what ever your char number is, becomes a big clue in tracing obscure characters that may have sneaked into your script.

Code 800A0408 - Invalid Character

See More Windows Update Error Codes 8004 Series

• Error 800A101A8 Object Required   •Error 800A0046   •Error 800A10AD   •Error 800A000D

• Error 80048820   •Error 800A0401   •Review of SolarWinds Permissions Monitor

• Error 80040E14   • Error 800A03EA   • Error 800A0408   • Error 800A03EE

Solarwinds Free WMI MonitorGuy Recommends: WMI Monitor and It’s Free!

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, SolarWinds have created the WMI Monitor so that you can examine these gems of performance information for free.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor


Do you need additional help?

  • For interpreting the WSH messages check Diagnose 800 errors.
  • For general advice try my 7 Troubleshooting techniques.
  • See master list of 0800 errors.
  • Codes beginning 08004…
  • Codes beginning 08005…
  • Codes beginning 08007…
  • Codes beginning 0800A…

Give something back?

Would you like to help others?  If you have a good example of this error, then please email me, I will publish it with a credit to you:

If you like this page then please share it with your friends


Я
   ПульсЪ

14.10.10 — 16:50

VBS не зна вообще, где то на кком то форуме нашел текст

положим s=CreateObject («WScript.Shell»)

делать

s.SendKeys»{} CAPSLOCK»

типа выполняется нажатие кнопки КапсЛок,

пихаю скрипт в блокнот, сохраняю *.vbs, ругается:

Строка 1

Символ 1

Ошибка недопустимый знак

Код 800A0408

помогите решить задачу

   KnightAlone

1 — 14.10.10 — 16:52

VBS не знаю вообще. Может заменить

положим s=CreateObject («WScript.Shell»)

делать

s.SendKeys»{} CAPSLOCK»

на

s=CreateObject («WScript.Shell»)

s.SendKeys»{} CAPSLOCK»

   NikVars

2 — 14.10.10 — 16:53

Может так?
s.SendKeys»{CAPSLOCK}»

   Salvador Limones

3 — 14.10.10 — 16:54

set s = WScript.CreateObject(«WScript.Shell»)

   el-gamberro

4 — 14.10.10 — 16:57

Set WshShell = CreateObject(«WScript.Shell»)
WshShell.SendKeys «{CAPSLOCK}»

   ПульсЪ

5 — 14.10.10 — 17:00

(4)(3)(2)(1) СПАСИБО!!!!! РАБОТАЕТ!! можно еще вопрос,

делать
Set WshShell = CreateObject(«WScript.Shell»)
WshShell.SendKeys «{CAPSLOCK}»
петля

это как будет*?

   Salvador Limones

6 — 14.10.10 — 17:00

(5) Нельзя вопрос. Сам думай.

   ПульсЪ

7 — 14.10.10 — 17:03

(6) ну плиз, я понимаю что это цикл, тока как он пишется то?

   ПульсЪ

8 — 14.10.10 — 17:05

loop ?

   Salvador Limones

9 — 14.10.10 — 17:05

For I = 1 To 10

Next

   Megas

10 — 14.10.10 — 17:06

(7) Яндекс в помощь… такие простые вопросы то…

   ПульсЪ

11 — 14.10.10 — 17:11

спс я додумался)) пришлось перезагружать комп__))

do
Set WshShell = CreateObject(«WScript.Shell»)
WshShell.SendKeys «{CAPSLOCK}»
loop

   NikVars

12 — 14.10.10 — 17:52

http://muromtsevo.narod.ru/VBS.html

   smaharbA

13 — 14.10.10 — 22:56

вобщето намлук и капслук выставляются без сендкея

   trdm

14 — 14.10.10 — 23:41

http://script-coding.info/filez.html
первая ссылка..

   ПульсЪ

15 — 15.10.10 — 11:26

(13) да это я к примеру ввел, мне другие кнопки нужны были)

   ПульсЪ

16 — 15.10.10 — 11:26

(12) (14) спасибо)

  

Megas

17 — 15.10.10 — 11:29

(15) Шифруется… но мы то знаем что там кнопка «СДЕЛАТЬВСЁ»  … это уже полная автоматизация… Если раньше кнопка «СДЕЛАТЬВСЁ» лежала на стуле менеджера и он садился на неё ж*пой, то теперь это делается программно.

TurboConf — расширение возможностей Конфигуратора 1С

ВНИМАНИЕ! Если вы потеряли окно ввода сообщения, нажмите Ctrl-F5 или Ctrl-R или кнопку «Обновить» в браузере.

Ветка сдана в архив. Добавление сообщений невозможно.
Но вы можете создать новую ветку и вам обязательно ответят!
Каждый час на Волшебном форуме бывает более 2000 человек.

Я получаю ошибку компиляции, когда пытаюсь запустить следующий код vbs из командной строки в Windows 7.

Option Explicit
Dim objNetwork, strRemotePath1, strRemotePath2, strRemotePath3
Dim strDriveLetter1, strDriveLetter2, strDriveLetter3, strUserName

Set objNetwork = CreateObject("WScript.Network")
strUserName = objNetwork.UserName 

strDriveLetter1 = "H:"
strDriveLetter2 = "P:"
strDriveLetter3 = "S:"
strRemotePath1 = "testpublicusers" & strUserName & ""
strRemotePath2 = "testpublicgroups"
strRemotePath3 = "testscans"


'Section which maps two drives, M: and P: and S:
objNetwork.MapNetworkDrive strDriveLetter1, strRemotePath1
objNetwork.MapNetworkDrive strDriveLetter2, strRemotePath2
objNetwork.MapNetworkDrive strDriveLetter3, strRemotePath3

'Extra code just to add a message box
WScript.Echo "Map drives " & strDriveLetter1 & " & " & strDriveLetter2 & " & " & strDriveLetter3

Wscript.Quit

Он говорит, что проблема заключается в строке 1 Char 1. Есть идеи?

3 ответов


возможная проблема заключается в том, как ваш файл был закодирован; попробуйте сохранить его как ANSI и запустить его снова.


FYI для тех, кто с той же проблемой в будущем, чтобы исправить это:

  1. открыть .VBS в блокноте
  2. перейдите в файл и»сохранить как»
  3. справа в поле Имя файла, вы увидите выпадающее меню для кодирования. Выберите в ANSI.

Регистрация вы не используете расширенный характер, как á é í ó ú ñ в имени переменной


check
Best Answer

  • Author Mike Brown

    So I had to go through the whole file and replace invalid characters.  This is rather frustrating.  What I think happened is I edited in Notepad at one point rather than Notepad++.

    I’ll have to change the default editor for vbs files or I’m going to do that again I’m sure of it.


    Was this post helpful?
    thumb_up
    thumb_down

  • View Best Answer in replies below

    5 Replies

    • Author Adam

      In the command line or a batch file try using «type old.vbs > new.vbs» to convert the file(s) to ansi.

      http:/ Opens a new window/www.robvanderwoude.com/type.php#Unicode Opens a new window


      Was this post helpful?
      thumb_up
      thumb_down

    • You need to post a snippet of your code, maybe the line and character referenced in the error?
      We do not have enough information to help with just the error.

      EDIT:
      After searching the error, it does seen to be an encoding issue.
      I have never seen that with NotePad++.


      Was this post helpful?
      thumb_up
      thumb_down

    • Author Mike Brown

      AdamRPL wrote:

      In the command line or a batch file try using «type old.vbs > new.vbs» to convert the file(s) to ansi.

      http:/ Opens a new window/www.robvanderwoude.com/type.php#Unicode Opens a new window

      Tried that and when I run the new file I get the same message.  Notepad++ is showing that it is ANSI.

      attach_file
      Attachment

      2014-01-23_13_34_…ection.png
      41.1 KB


      Was this post helpful?
      thumb_up
      thumb_down

    • Author Mike Brown

      Dave Rossi wrote:

      You need to post a snippet of your code, maybe the line and character referenced in the error?
      We do not have enough information to help with just the error.

      EDIT:
      After searching the error, it does seen to be an encoding issue.
      I have never seen that with NotePad++.

      It’s always line 1 character 1.

      Here is the beginning of the code:

      ‘——————————————————————————–
      ‘declare variables
      ‘——————————————————————————–
      
      Const ForAppending = 8
      
      Const LogFile = “c:tempjavauninstall.txt”
      
      ‘——————————————————————————–
      ‘create log file
      ‘——————————————————————————–
      
      Set objFSO = CreateObject(“Scripting.FileSystemObject”)
      
      Set objLogFile = objFSO.CreateTextFile(LogFile)
      
      sLog = “Started Java Uninstall”
      
      Call WriteLog(sLog)
      

      This script worked just fine until I edited it recently.


      Was this post helpful?
      thumb_up
      thumb_down

    • Author Mike Brown

      So I had to go through the whole file and replace invalid characters.  This is rather frustrating.  What I think happened is I edited in Notepad at one point rather than Notepad++.

      I’ll have to change the default editor for vbs files or I’m going to do that again I’m sure of it.


      Was this post helpful?
      thumb_up
      thumb_down

    This is a simple VBS script. But when I double-click on this, I get Invalid Character 800A0408 on Line 1, Character 1, which I think is the first «Dim». I am new to VBS—can u tell me what I did wrong? FYI, I have an XP OS and IIS6 Manager installed.

    ' This script adds the necessary Windows Presentation Foundation MIME types 
    ' to an IIS Server.
    ' To use this script, just double-click or execute it from a command line.
    ' Running this script multiple times results in multiple entries in the IIS MimeMap.
    
    Dim MimeMapObj
    Dim MimeMapArray
    Dim WshShell
    Dim oExec
    Const ADS_PROPERTY_UPDATE = 2
    
    ' Set the MIME types to be added
    Dim MimeTypesToAddArray = Array(".manifest", "application/manifest", ".xaml", _
        "application/xaml+xml", ".application", "application/x-ms-application", _
        ".deploy", "application/octet-stream", ".xbap", "application/x-ms-xbap", _
        ".xps", "application/vnd.ms-xpsdocument")
    
    ' Get the mimemap object 
    Set MimeMapObj = GetObject("IIS://LocalHost/MimeMap")
    
    ' Call AddMimeType for every pair of extension/MIME type
    For counter = 0 to UBound(MimeTypesToAddArray) Step 2
        AddMimeType MimeTypesToAddArray(counter), MimeTypesToAddArray(counter+1)
    Next
    
    ' Create a Shell object
    Set WshShell = CreateObject("WScript.Shell")
    
    ' Stop and Start the IIS Service
    Set oExec = WshShell.Exec("net stop w3svc")
    Do While oExec.Status = 0
        WScript.Sleep 100
    Loop
    
    Set oExec = WshShell.Exec("net start w3svc")
    Do While oExec.Status = 0
        WScript.Sleep 100
    Loop
    
    Set oExec = Nothing
    
    ' Report status to user
    WScript.Echo "Windows Presentation Foundation MIME types have been registered."
    
    ' AddMimeType Sub
    Sub AddMimeType(ByVal Ext, ByVal MType)
    
        ' Get the mappings from the MimeMap property. 
        MimeMapArray = MimeMapObj.GetEx("MimeMap")
    
        ' Add a new mapping. 
        i = UBound(MimeMapArray) + 1
        ReDim Preserve MimeMapArray(i)
        MimeMapArray(i) = CreateObject("MimeMap")
        MimeMapArray(i).Extension = Ext
        MimeMapArray(i).MimeType = MType
        MimeMapObj.PutEx(ADS_PROPERTY_UPDATE, "MimeMap", MimeMapArray)
        MimeMapObj.SetInfo()
    
    End Sub
    

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка невозможно запустить среду исполнения net не удается найти указанный файл
  • Ошибка недостаточно средств на карте