- Remove From My Forums
-
Question
-
I’m so close to get my script to work with a user, but I need your help.
I have a Terminal Server 2003 with policy restrictions. My users can’t even see how much megabytes they have in use. So I created the following script. It runs perfectly with an administrator account:—
Dim oFS, oFolder
Dim total
Dim message
set oFS = WScript.CreateObject(«Scripting.FileSystemObject»)
set oFolder1 = oFS.GetFolder(«\servershare$»)
set oFolder2 = oFS.GetFolder(«\servershare1$»)
set oFolder3 = oFS.GetFolder(«\servershare2$»)
Wscript.Sleep 300
total = oFolder1.Size + oFolder2.Size + oFolder3.Size
message=MsgBox («Size: » & vbTab & oFolder1.Size /10241024 & «MB» & vbTab & » Path: » & vbTab & oFolder1.Path & Chr(10) _
& «Size: » & vbTab & oFolder2.Size /10241024 & «MB» & vbTab & » Path: » & vbTab & oFolder2.Path & Chr(10) _
& «Size: » & vbTab & oFolder3.Size /10241024 & «MB» & vbTab & » Path: » & vbTab & oFolder3.Path & Chr(10) _
& «Total: » & vbTab & total /10241024 & «MB»,64,»megabytes in use»)
—The problem I’m facing is that I can’t distribute it to my users because when this script runs as an user I receive this error:
Windows Script Host
Script: pathandname.vbs
Line: 9
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime errorI’ve checked the users permission on the servershare’s and they have Full Control.
Also on the ACL on the script the user has Full Control.What else can I check?
Is there a setting in some GPO that denies users to run a .vbs?Please let me know when you need more information to solve this.
Cheers,
Yuri
Answers
-
Are you sure the users have permissions to ALL files and directories on the shares?
If there is as much as one file or folder to which the user hasn’t got at least «list contents» permission the script will fail with the above message.If you check the properties of the root of the share from explorer, first as an administrator and then as a user. Does it show the same amount of files/folders and the same size?
A difference here would indicate that the user doesn’t have permissions to everything.-
Marked as answer by
Tuesday, September 1, 2009 9:14 AM
-
Marked as answer by
В этой статье представлена ошибка с номером Ошибка 800A0046, известная как Ошибка программы очистки установщика Windows 800A0046, описанная как Ошибка 800A0046: Возникла ошибка в приложении Windows Installer CleanUp Utility. Приложение будет закрыто. Приносим свои извинения за неудобства.
О программе Runtime Ошибка 800A0046
Время выполнения Ошибка 800A0046 происходит, когда Windows Installer CleanUp Utility дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- Установщик — ОБЩАЯ ПОДДЕРЖКА УСТАНОВЩИКА НЕ ВОСПРИНИМАЕТСЯ
- Утилита . Утилита — это системное программное обеспечение, предназначенное для анализа, настройки и оптимизировать или поддерживать компьютер.
- Windows — ОБЩАЯ ПОДДЕРЖКА WINDOWS НЕ В ТЕМЕ.
- Установщик Windows — Установщик Microsoft Windows является услуга установки и настройки, предоставляемая с Windows
Симптомы Ошибка 800A0046 — Ошибка программы очистки установщика Windows 800A0046
Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Только для примера)
Причины Ошибка программы очистки установщика Windows 800A0046 — Ошибка 800A0046
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.
Метод 2 — Обновите / переустановите конфликтующие программы
Использование панели управления
- В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
- В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
- Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
- В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
- Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.
Использование других методов
- В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
- В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
- Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
- Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.
Метод 1 — Закройте конфликтующие программы
Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.
- Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
- Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
- Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
- Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.
Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.
Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.
Метод 4 — Переустановите библиотеки времени выполнения
Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.
- Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
- Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
- Загрузите последний распространяемый пакет от Microsoft и установите его.
Метод 5 — Запустить очистку диска
Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.
- Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
- Вы также можете очистить кеш и перезагрузить компьютер.
- Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C
- Щелкните «Свойства», а затем — «Очистка диска».
Метод 6 — Переустановите графический драйвер
Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:
- Откройте диспетчер устройств и найдите драйвер видеокарты.
- Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.
Метод 7 — Ошибка выполнения, связанная с IE
Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:
- Сбросьте настройки браузера.
- В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
- Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
- Отключить отладку скриптов и уведомления об ошибках.
- В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
- Установите флажок в переключателе.
- Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.
Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.
Другие языки:
How to fix Error 800A0046 (Windows Installer Cleanup Utility Error 800A0046) — Error 800A0046: Windows Installer CleanUp Utility has encountered a problem and needs to close. We are sorry for the inconvenience.
Wie beheben Fehler 800A0046 (Windows Installer Cleanup Utility Fehler 800A0046) — Fehler 800A0046: Das Windows Installer CleanUp-Dienstprogramm hat ein Problem festgestellt und muss geschlossen werden. Wir entschuldigen uns für die Unannehmlichkeiten.
Come fissare Errore 800A0046 (Errore dell’utilità di pulizia di Windows Installer 800A0046) — Errore 800A0046: l’utilità di pulizia di Windows Installer ha riscontrato un problema e deve essere chiusa. Ci scusiamo per l’inconveniente.
Hoe maak je Fout 800A0046 (Windows Installer Cleanup Utility Fout 800A0046) — Fout 800A0046: Windows Installer CleanUp Utility heeft een probleem ondervonden en moet worden afgesloten. Excuses voor het ongemak.
Comment réparer Erreur 800A0046 (Erreur 800A0046 de l’utilitaire de nettoyage Windows Installer) — Erreur 800A0046 : l’utilitaire Windows Installer CleanUp a rencontré un problème et doit se fermer. Nous sommes désolés du dérangement.
어떻게 고치는 지 오류 800A0046 (Windows Installer 정리 유틸리티 오류 800A0046) — 오류 800A0046: Windows Installer CleanUp 유틸리티에 문제가 발생해 닫아야 합니다. 불편을 드려 죄송합니다.
Como corrigir o Erro 800A0046 (Erro 800A0046 do utilitário de limpeza do Windows Installer) — Erro 800A0046: O Windows Installer CleanUp Utility encontrou um problema e precisa fechar. Lamentamos o inconveniente.
Hur man åtgärdar Fel 800A0046 (Windows Installer Cleanup Utility Error 800A0046) — Fel 800A0046: Windows Installer CleanUp Utility har stött på ett problem och måste avslutas. Vi är ledsna för besväret.
Jak naprawić Błąd 800A0046 (Błąd narzędzia do czyszczenia instalatora Windows 800A0046) — Błąd 800A0046: Narzędzie Windows Installer CleanUp napotkało problem i musi zostać zamknięte. Przepraszamy za niedogodności.
Cómo arreglar Error 800A0046 (Error 800A0046 de la utilidad de limpieza del instalador de Windows) — Error 800A0046: La utilidad de limpieza de Windows Installer ha detectado un problema y debe cerrarse. Lamentamos las molestias.
Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.
Следуйте за нами:
Последнее обновление:
10/11/22 05:47 : Пользователь Windows 10 проголосовал за то, что метод восстановления 2 работает для него.
Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.
ШАГ 1:
Нажмите здесь, чтобы скачать и установите средство восстановления Windows.
ШАГ 2:
Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.
ШАГ 3:
Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.
СКАЧАТЬ СЕЙЧАС
Совместимость
Требования
1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.
ID статьи: ACX012844RU
Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000
Совет по увеличению скорости #63
Как удалить лишние панели инструментов:
Удаление дополнительных панелей инструментов с панели задач Windows и интернет-браузера может повысить скорость вашего компьютера. Эти дополнительные панели инструментов часто устанавливаются вместе при установке плагинов и программного обеспечения. И в большинстве случаев они перекрывают уже имеющуюся у вас функцию.
Нажмите здесь, чтобы узнать о другом способе ускорения работы ПК под управлением Windows
Troubleshooting Code 800A0046 – Permission Denied
Code 800A0046 is a straightforward error to solve. The secret is to read the Windows Script Error message carefully, then check the access control list to see who has permission to use the page, or use the device.
- Introduction to Error Code 800A0046
- Example 1: Script to map a printer
- Example 2: Error 800A0046 When You Install Visual Studio
- Permissions Analyzer Free Tool
‡
Introduction to Error 800A0046
Code 800A0046 is runtime error that is more likely to occur with an .ASP file than a .VBS. You could be trying to connect to SQL, IIS or Exchange. However, my example of is taken from printer permission problem sent in by Keith S.
The Symptoms You Get With Error 800A0046
When you get a pop-up message box. Put on your detective hat, and pay close attention to the line number. Error 800A0046 is a runtime error, so the problem is likely to outside your script, there could be something the matter with permissions on an application server.
The Cause of Error 800A0046
In the example above, Line 6: is the source of the error. Char 1: is not always very useful as the error could be anywhere on the line, and WSH still blames char 1.
The cause of error 800A0046 is likely to be read-only permissions on some aspect of your server. The Source: tells us that this is a runtime error, therefore the syntax is probably o.k.
The Solution
If its Exchange, then check the MailRoot and Pickup folder permissions. If its IIS check the permissions to run scripts. If its SQL check the execute permissions on the services.
The solution in the printer problem below would be to change the share permissions on the HP6L printer share.
Example 1: Script to map a printer
In this example, the user does not have permission to install the HP6L printer. Tell the truth, an example script is not that useful with Error 800A0046 as you cannot see the permissions!
‘ VBScript to create a local printer mapped to a network server
‘ Guy Thomas February 2010.
Option Explicit
Dim netPrinter
Set netPrinter = CreateObject(«WScript.Network»)
netPrinter.AddWindowsPrinterConnection «\ServerPrnHP6L»
Guy Recommends: Permissions Analyzer – Free Active Directory Tool
I like thePermissions Monitor because it enables me to see quickly WHO has permissions to do WHAT. When you launch this tool it analyzes a users effective NTFS permissions for a specific file or folder, takes into account network share access, then displays the results in a nifty desktop dashboard!
Think of all the frustration that this free utility saves when you are troubleshooting authorization problems for users access to a resource. Give this permissions monitor a try – it’s free!
Download Permissions Analyser – Free Active Directory Tool
Example 2: Error 800A0046 When You Install Visual Studio 6.0 (Also other Microsoft Products)
When you install Visual Studio you get the following message.
Permission denied: ‘CreateObject’
/Retail/include/global_siteconfig_lib.asp, line 194
Once again it’s a permissions problem on the Windowssystem32 folder. Another idea is to try the useful Free Permissions Analyzer.
Example 3: ASP on IIS (Kindly sent in by a reader)
The way we got error 800A0046 was running ASP on IIS under Server 2003R2. Someone wrote a debug routine that did an OpenTextFile from a FileSystemObject; I think what happened was there were multiple simultaneous attempts to open that file.
Example 4: Constantly Writing to File
Dim FSO
Dim oFS
CONST F_ATTR_RONLY = 1
Set FSO = CreateObject(«Scripting.FileSystemObject»)
Set oFS = FSO.GetFile(«d:testo2test.png»)
IF oFS.Attributes AND F_ATTR_RONLY ‘check if bit 1 is set – read only
THEN
‘do nothing
ELSE
FSO.CopyFile «d:testo1test.png», «d:testo2»
END IF
The problem was: the file is written into the sourcelocation every 10 seconds. This is done by a Closed Source Software i have no way of editing. It seems like i get the error (line 11) every time i try to READ the sourcefile while it is being written/created.
Sadly the only solution i found was to run the script with
c:windowssystem32wscript.exe «c:{path to script}» //B
preventing the errornotice.
I have found no way to check if the file is currently being modified except for try and error.
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
Guy 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
- Remove From My Forums
-
Question
-
User291970639 posted
Hello I am new on the forum.
I have one scrip to search a local Word Template and if the template exist then delete the template.
I have this script:
‘Search MyTemplate.Dot
Dim Path
Set objWord = CreateObject(«Word.Application»)
objWord.Visible = FalseSet Fso = CreateObject(«Scripting.FileSystemObject»)
Set objSelection = objWord.Selection
Set objOptions = objWord.Options
Const wdStartupPath = 8
Path= objOptions.DefaultFilePath(wdStartupPath) & «MyTemplate.Dot»
MsgBox «The route is : » & Path
objWord.QuitSet Fso = CreateObject(«Scripting.FileSystemObject»)
‘If MyTemplate.Dot exist…
If (Fso.FileExists(Path) ) Then
MsgBox «YES
MyTemplate.Dot
EXIST BUT IF I DONT DISPLAY A MSGBOX LIKE THIS ONE THE SCRIPT MAKE ERROR 800A0046″
fso.DeleteFile(Path)
Else
MsgBox «DONT EXIST MyTemplate.Dot«End If
The really strange part is the MsgBox… if I dont make a MsgBox BEFORE fso.DeleteFile I get one error…
What have to do MsgBox with 800A0046 error??
Answers
-
User291970639 posted
I find the solution yesterday, I post the same question on
http://www.visualbasicscript.com/m_74712/tm.htm
And the solution was easy: a delay of time before the fso.DeleteFile(Path)
My original code:
‘If MyTemplate.Dot exist…
If (Fso.FileExists(Path) ) Then
MsgBox «YES MyTemplate.Dot
EXIST BUT IF I DONT DISPLAY A MSGBOX LIKE THIS ONE THE SCRIPT MAKE ERROR 800A0046″
fso.DeleteFile(Path)
Else
MsgBox «DONT EXIST MyTemplate.Dot»End If
The solution:
‘If MyTemplate.Dot exist…
If (Fso.FileExists(Path) ) Then
WScript.Sleep 5000
fso.DeleteFile(Path)
Else
MsgBox «DONT EXIST MyTemplate.Dot»End If
-
Marked as answer by
Tuesday, September 28, 2021 12:00 AM
-
Marked as answer by
<!— /* Font Definitions */ @font-face {font-family:Wingdings; panose-1:5 0 0 0 0 0 0 0 0 0; mso-font-charset:2; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:0 268435456 0 0 -2147483648 0;} /* Style Definitions */ p.MsoNormal,
li.MsoNormal, div.MsoNormal {mso-style-parent:»»; margin:0cm; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:»Times New Roman»; mso-fareast-font-family:»Times New Roman»;} @page Section1 {size:595.3pt
841.9pt; margin:70.85pt 70.85pt 70.85pt 70.85pt; mso-header-margin:35.4pt; mso-footer-margin:35.4pt; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:2068841666; mso-list-type:hybrid; mso-list-template-ids:-2012814198
67895297 67895299 67895301 67895297 67895299 67895301 67895297 67895299 67895301;} @list l0:level1 {mso-level-number-format:bullet; mso-level-text:; mso-level-tab-stop:36.0pt; mso-level-number-position:left; text-indent:-18.0pt; font-family:Symbol;} ol {margin-bottom:0cm;}
ul {margin-bottom:0cm;} —>
Hi everybody !
I hope someone will bring me some help because I really need it.
The facts :
We integrated a couple of Seven-based desktops in our domain two months ago.
We use GPOs to map network drives at logon for each user in our organisation. To ensure the network drives map correctly on XP and Seven, we followed the Microsoft guidelines and introduced a small VBScript called «launchapp.wsf».
This script encapsulates each «net» command in a scheduled task if the Operating System is Vista or higher and executes it directly if the OS is XP. This script works fine on Seven but generate error messages like this one during the logon on XP
:
Script : the path of the script file
Error : Permission denied
Code : 800A0046
Source : Microsoft VBScript runtime error
What we already tried :
- We followed and applied all Microsoft issues about the topic ()
- We thought it was related to the fact the current user wasn’t already logged on as the script executes. So we delayed the execution of the script and then gave all users “Read & Write”, “List folder content”
and “Read” permissions on the script file. - Then we remarked that the problem do not appear on every XP-desktops in the organisation and finally we thing that the problem could be a hardware problem.
I know that this is a known problem and that several people have to face it. So I would be grateful if somebody could give me further explanations about the situation I described.
Here is the VBScript file content :
<job>
<script language="VBScript">
'---------------------------------------------------------
' This sample launches the application as interactive user.
'---------------------------------------------------------
const TriggerTypeRegistration = 7 ' A constant that specifies a registration trigger.
const ActionTypeExecutable = 0 ' A constant that specifies an executable action.
const FlagTaskCreate = 2 ' A constant that specifies the flag in RegisterTaskDefinition.
const LogonTypeInteractive = 3 ' A constant that specifies an executable action.
If WScript.Arguments.Length <> 2 Then
WScript.Echo "Usage: cscript launchapp.wsf <AppPath>"
WScript.Quit
End If
strAppPath = WScript.Arguments(0) ' This is the script to run.
strTaskName = WScript.Arguments(1) ' This is the name of the task to run.
'********************************************************
' Is this Vista or XP?
' Begin the section added by Jarvis
'********************************************************
' This section that determines OS version is a modified version of code
' originally posted at the following web page:
' http://blog.eqinox.net/jed/archive/2006/12/05/1270.aspx
'
Dim vistaClient
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
computer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & computer & "rootcimv2")
Set objOSList = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each os In objOSList
BuildNumber = OS.BuildNumber
If BuildNumber < 6000 Then
NotVistaClient = True
End If
Next
If NotVistaClient = True Then
' Be CAREFULL !!! Sometime, users are not well autheticated ! If you connect to a network share (\ServerShare), be
' sure that the group "Everyone" have read rights on the share !
' Run the script
wshShell.Run(strAppPath), 0, True
' =======================================
' OLD METHOD, NOW WE DONT NEED IT ANYMORE
' =======================================
'Dim runReturn
'runReturn = -1
'Dim numberOfTry
'numberOfTry = 10
'Dim sleepingMillisec
'sleepingMillisec = 5000
'Dim ok
'ok = False
'
' Try many times to run the script. Sometimes, it gets an "Access denied" message. So let's try and sleep
'Do While numberOfTry > 0
'
' runReturn = wshShell.Run(strAppPath, 0, True) ' Run the logon script normally
'
' If runReturn = 0 Then
'
' numberOfTry = 0
' ok = True
'
' Else
'
' numberOfTry = numberOfTry - 1
' WScript.Sleep(sleepingMillisec)
'
' End If
'
'Loop
'
'If ok = False Then
'
' WScript.Echo "launchapp.wsf --> maximum try reached for : " & strAppPath
'
' End If
WScript.Quit
Else ' Run the logon script using launchapp.wsf
'********************************************************
' Create the TaskService object.
'********************************************************
Set service = CreateObject("Schedule.Service")
call service.Connect()
strTaskName = "Launch Logon Script " & strTaskName & " as Interactive User"
'********************************************************
' Get a folder to create a task definition in.
'********************************************************
Dim rootFolder
Set rootFolder = service.GetFolder("")
'Delete the task if already present
On Error Resume Next
call rootFolder.DeleteTask(strTaskName, 0)
Err.Clear
'********************************************************
' Create the new task
'********************************************************
Dim taskDefinition
Set taskDefinition = service.NewTask(0)
'********************************************************
' Create a registration trigger.
'********************************************************
Dim triggers
Set triggers = taskDefinition.Triggers
Dim trigger
Set trigger = triggers.Create(TriggerTypeRegistration)
'********************************************************
' Set the task settings.
'********************************************************
Dim settings
set settings = taskDefinition.Settings
settings.StopIfGoingOnBatteries = false
settings.DisallowStartIfOnBatteries = false
'***********************************************************
' Create the action for the task to execute.
'***********************************************************
' Add an action to the task. The action executes the app.
Dim Action
Set Action = taskDefinition.Actions.Create( ActionTypeExecutable )
Action.Path = strAppPath
'***********************************************************
' Register (create) the task.
'***********************************************************
call rootFolder.RegisterTaskDefinition(strTaskName, taskDefinition, FlagTaskCreate,,, LogonTypeInteractive)
End If
</script>
</job>
Best regards.
—————-
Gilles Rudaz
-
Moved by
Tuesday, September 7, 2010 2:16 PM
(From:Application Compatibility for Windows Development)






Guy Recommends: WMI Monitor and It’s Free!