Действия c windows system32 cmd exe с кодом возврата 2147942401

I am trying to schedule a job to run a batch file with Windows 10 Task Scheduler, but it results in return code 2147942401. The batch file is on remote location so I am giving the absolute path "\

I am trying to schedule a job to run a batch file with Windows 10 Task Scheduler, but it results in return code 2147942401.

The batch file is on remote location so I am giving the absolute path
«\server1file transfersdata filesinboundabccsvexcel-to-csv.bat»

If I run the batch script with command prompt then it work fine.
Properties - General
Actions - Edit Action

The batch script is to convert excel to file to csv.

Content of the script is:

FOR /f "delims=" %%i IN ("\server1file transfersData FilesInboundabcCSV*.xlsx" ) DO to-csv.vbs  "\server1file transfersData FilesInboundabc*.xlsx" "%%~ni.csv"

Its calling another VB script which is to-cvs.vbs

If i make changes in Action tab as mention by @Steinspecht(Task scheduler- task completed “successfully” with exit code 0x8007001) then also i am getting the code 2147942401
Not sure whether Add a arguments is written correctenter image description here

asked Jan 19, 2018 at 15:05

S B's user avatar

S BS B

4611 gold badge4 silver badges9 bronze badges

5

The error codes for Task Scheduler are listed as hexadecimal at msdn, and your code 2147942401 converts to hex as 0x80070001 (which is not listed there), but this superuser describes it as an «Illegal Function». He fixed his problem by using «the simplest task scheduler settings and now it works». I note that he only runs his task when the user is logged in, so he doesn’t need «Log on as a batch job».

If you want to run the batch job when you’re not logged in, you need a special privilege called «Log on as a batch job». Note that there is also a «DENY log on as a batch job» privilege, which you wouldn’t want.

From Social Technet, you can assign that privilege with

  • Type in secpol.msc /s
  • Select «Local Policies» in MSC snap in
  • Select «User Rights Assignment«
  • Right click on «Log on as batch job» and select Properties
  • Click «Add User or Group«, and include the relevant user.

Local Security Policy Snap-In

Your task calls a network resource. These powershell scripters recommend bringing those resources to your local machine to eliminate any chance of network/connectivity/permissions issues … but that may not always be appropriate or practical.

answered May 14, 2018 at 22:54

woodvi's user avatar

woodviwoodvi

1,79819 silver badges27 bronze badges

3

This error code can also result from a bug/mistake in the actual Powershell script or Batch (.bat) file, even if all task scheduler settings, permissions, etc. are correct; in my case I was referencing a directory that doesn’t exist.

daveloyall's user avatar

answered Jul 24, 2018 at 13:29

M Herbener's user avatar

M HerbenerM Herbener

4643 silver badges18 bronze badges

An old question I know, but I was getting 2147942401 error on windows 2016 server.

If you look at the scheduled task properties, on the bottom of the General Tab, it was defaulted to Configure for: Windows Vista, Windows Server 2008.

Changed to Windows Server 2016 and the problem was solved.

answered Jul 10, 2019 at 13:16

user3507000's user avatar

3

Throwing another common cause of the error action "powershell.exe" with return code 2147942401 here. If your action arguments are not correct you will also get this error message.
Check that the action argument parameters and parameter values are spaced correctly.

Good example:

-executionpolicy bypass -file "C:ScriptsImportFiles.ps1"

Broken Example (no space between the ‘file’ parameter and it’s value):

-executionpolicy bypass -file"C:ScriptsImportFiles.ps1"

answered Sep 13, 2019 at 17:51

BrianCanFixIT's user avatar

M Herbener’s answer led to me attempting to run the script manually, to see if the script had an error. It did not, but it did highlight what the problem was as I received the error message:

[my script] cannot be loaded because running scripts is disabled on this system.

The solution, of course, was to run Set-ExecutionPolicy to allow Powershell scripts to run.

answered Mar 14, 2019 at 12:33

paulH's user avatar

paulHpaulH

1,08215 silver badges42 bronze badges

For me, the task would sometimes work and sometimes wouldn’t. According to the Scheduled Task History, when failing, it would appear as if it’s been running for about 40 seconds, doing nothing, and completing action "C:windowsSYSTEM32cmd.exe" with return code 2147942401.

  • In this case, there was no point messing with the Group Policy settings because sometimes it would work. But not everytime. Which means it’s a timing problem, not a Policy problem.

  • Recreating, reconfiguring my task (as suggested in this SuperUser Q&A) did not fix the problem.

  • I did also consider butchering my batch file and getting rid of the standard output redirection, thus abandonning the logging capability (and becoming blind). Or simply running an actual «*.exe» process, instead of using a batch file at all. This could potentially have been a solution.

  • I also considered replacing the «At startup» scheduled task by a full-blown Service, but this would have been an expensive experiment for such a trivial problem.

Ultimately, I remembered that services can be delayed: «Automatic» vs. «Automatic (Delayed Start)». So I imitated this by added a delay on the scheduled task, in the Tasks Scheduler. For «At startup» scheduled tasks, it’s the trigger that have individual properties of its own, and that’s where the delay can be configured:

Image depicting solution for delaying an on-startup scheduled task

I believe my scheduled task was sometimes being started a few milliseconds too early and some OS service or functionality was not yet available or allowed. Simply adding a small delay on the trigger fixed the problem.

answered Dec 16, 2020 at 16:08

numdig's user avatar

For me, the issue was file was blocked as it was downloaded from Internet. I was seeing this in task scheduler history

Task Scheduler successfully completed task "task name" , 
instance "{id}" , action "Powershell.exe" with return code 2147942401.

To solve this:

  • Right click .ps1 file and open Properties
  • Click Unblock under Attributes section

answered Apr 21, 2022 at 17:32

Omer Celik's user avatar

Omer CelikOmer Celik

651 silver badge7 bronze badges

Я пытаюсь запланировать задание для запуска пакетного файла с помощью Планировщика задач Windows 10, но это приводит к коду возврата 2147942401.

Пакетный файл находится в удаленном месте, поэтому я указываю абсолютный путь
«\ server1 передача файлов файлы данных входящий abc csv excel-to-csv.bat»

Если я запустил пакетный скрипт из командной строки, он будет работать нормально. Свойства - Общие Действия - Изменить действие

Пакетный сценарий предназначен для преобразования Excel в файл в CSV.

Содержание скрипта:

FOR /f "delims=" %%i IN ("\server1file transfersData FilesInboundabcCSV*.xlsx" ) DO to-csv.vbs  "\server1file transfersData FilesInboundabc*.xlsx" "%%~ni.csv"

Он вызывает другой сценарий VB, который является to-cvs.vbs

Если я внесу изменения на вкладке «Действие», как указано в @Steinspecht (планировщик задач — задача завершена «успешно» с кодом выхода 0x8007001), то я также получаю код 2147942401 Не уверен, правильно ли написано Добавить аргументы  введите описание изображения здесь

7 ответов

Здесь указывается еще одна распространенная причина ошибки — действие "powershell.exe" with return code 2147942401. Если ваши аргументы действия неверны, вы также получите это сообщение об ошибке. Убедитесь, что параметры аргумента действия и значения параметров расположены правильно.

Хороший пример:

-executionpolicy bypass -file "C:ScriptsImportFiles.ps1"

Пример с ошибкой (нет пробела между параметром ‘file’ и его значением):

-executionpolicy bypass -file"C:ScriptsImportFiles.ps1"


4

BrianCanFixIT
13 Сен 2019 в 20:51

Для меня задача иногда работала, а иногда нет. Согласно журналу запланированных задач, в случае сбоя это выглядело бы так, как если бы оно выполнялось в течение примерно 40 секунд, ничего не делая и завершая action "C:windowsSYSTEM32cmd.exe" with return code 2147942401.

  • В этом случае не было смысла возиться с настройками групповой политики, потому что иногда это срабатывало. Но не каждый раз. Это означает, что это проблема времени, а не политики.

  • Воссоздание, перенастройка моей задачи (как предложено в этом Вопросы и ответы суперпользователя) не устранили проблему.

  • Я также рассматривал возможность разделки моего пакетного файла и избавления от стандартного перенаправления вывода, тем самым отказавшись от возможности ведения журнала (и став слепым). Или просто запустить реальный процесс «*.exe» вместо использования пакетного файла. Это потенциально могло быть решением.

  • Я также рассматривал возможность замены запланированной задачи «При запуске» полноценной службой, но это был бы дорогостоящий эксперимент для такой тривиальной проблемы.

В конце концов, я вспомнил, что услуги могут быть отложены: «Автоматически» против «Автоматически (отложенный запуск)». Поэтому я сымитировал это, добавив задержку запланированной задачи в планировщике задач. Для запланированных задач «При запуске» это триггер, который имеет собственные индивидуальные свойства, и именно здесь можно настроить задержку:

Image depicting solution for delaying an on-startup scheduled task

Я считаю, что моя запланированная задача иногда запускалась на несколько миллисекунд раньше, и некоторые службы или функции ОС еще не были доступны или разрешены. Простое добавление небольшой задержки на триггер решило проблему.


2

numdig
24 Мар 2021 в 17:32

Коды ошибок для планировщика заданий перечислены в шестнадцатеричном виде по адресу msdn, и ваш код 2147942401 преобразуется в шестнадцатеричный формат как 0x80070001 (который там не указан), но этот суперпользователь описывает это как» Незаконную функцию «. Он исправил свою проблему с помощью «простейших настроек планировщика задач, и теперь он работает». Я отмечаю, что он выполняет свою задачу только тогда, когда пользователь вошел в систему, поэтому ему не нужно «Входить как пакетное задание».

Если вы хотите запустить пакетное задание, когда вы не вошли в систему, вам потребуется специальная привилегия под названием «Вход в систему как пакетное задание». Обратите внимание, что есть также привилегия «ОТКАЗАТЬ вход в систему как пакетное задание», чего вам не нужно.

Из Social Technet, вы можете назначить это право с помощью

  • Введите secpol.msc / s .
  • Выберите « Локальные политики » в оснастке MSC.
  • Выберите « Назначение прав пользователя ».
  • Щелкните правой кнопкой мыши « Войти как пакетное задание » и выберите «Свойства».
  • Нажмите « Добавить пользователя или группу » и включите соответствующего пользователя.

Local Security Policy Snap-In

Ваша задача вызывает сетевой ресурс. Эти сценарии powershell рекомендуют ресурсы на ваш локальный компьютер, чтобы исключить любые проблемы с сетью/подключением/разрешениями… но это не всегда может быть уместным или практичным.


27

woodvi
2 Авг 2021 в 19:27

Этот код ошибки также может быть результатом ошибки/ошибки в фактическом сценарии Powershell или пакетном (.bat) файле, даже если все настройки планировщика задач, разрешения и т. д. верны; в моем случае я ссылался на несуществующий каталог.


14

daveloyall
8 Мар 2021 в 16:19

Старый вопрос, который я знаю, но я получал ошибку 2147942401 на сервере Windows 2016.

Если вы посмотрите на свойства запланированной задачи, то в нижней части вкладки «Общие» по умолчанию установлено значение «Настроить для: Windows Vista, Windows Server 2008».

Перешел на Windows Server 2016, и проблема была решена.


7

user3507000
10 Июл 2019 в 16:16

Ответ М. Хербенера привел к тому, что я попытался запустить сценарий вручную, чтобы проверить, есть ли в нем ошибка. Этого не произошло, но он подчеркнул, в чем проблема, поскольку я получил сообщение об ошибке:

[мой скрипт] не может быть загружен, потому что в этой системе отключен запуск скриптов.

Решением, конечно же, было запустить Set-ExecutionPolicy, чтобы разрешить выполнение сценариев Powershell.


2

paulH
14 Мар 2019 в 15:33

Для меня проблема заключалась в том, что файл был заблокирован, так как он был загружен из Интернета. Я видел это в истории планировщика задач

Task Scheduler successfully completed task "task name" , 
instance "{id}" , action "Powershell.exe" with return code 2147942401.

Чтобы решить эту проблему:

  • Щелкните правой кнопкой мыши файл .ps1 и откройте «Свойства».
  • Нажмите «Разблокировать» в разделе «Атрибуты».


0

Omer Celik
21 Апр 2022 в 20:32

Содержание

  1. batch file from scheduled task returns code 2147942401
  2. 6 Answers 6
  3. Действия c windows system32 cmd exe с кодом возврата 2147942401
  4. Вопрос
  5. Ответы
  6. Все ответы
  7. Действия c windows system32 cmd exe с кодом возврата 2147942401
  8. Answered by:
  9. Question
  10. Answers
  11. All replies
  12. Коды возврата ошибок (расшифровки ErrorLevel)*
  13. Powershell script gives err 2147942401 in task scheduler:
  14. 14 Replies

batch file from scheduled task returns code 2147942401

I am trying to schedule a job to run a batch file with Windows 10 Task Scheduler, but it results in return code 2147942401.

The batch file is on remote location so I am giving the absolute path
«\server1file transfersdata filesinboundabccsvexcel-to-csv.bat»

If I run the batch script with command prompt then it work fine. gzfTG

The batch script is to convert excel to file to csv.

Content of the script is:

Its calling another VB script which is to-cvs.vbs

If i make changes in Action tab as mention by @Steinspecht(Task scheduler- task completed “successfully” with exit code 0x8007001) then also i am getting the code 2147942401 Not sure whether Add a arguments is written correct8N4vd

6 Answers 6

The error codes for Task Scheduler are listed as hexadecimal at msdn, and your code 2147942401 converts to hex as 0x80070001 (which is not listed there), but this superuser describes it as an «Illegal Function». He fixed his problem by using «the simplest task scheduler settings and now it works». I note that he only runs his task when the user is logged in, so he doesn’t need «Log on as a batch job».

If you want to run the batch job when you’re not logged in, you need a special privilege called «Log on as a batch job». Note that there is also a «DENY log on as a batch job» privilege, which you wouldn’t want.

From Social Technet, you can assign that privilege with

y9vHK

This error code can also result from a bug/mistake in the actual Powershell script or Batch (.bat) file, even if all task scheduler settings, permissions, etc. are correct; in my case I was referencing a directory that doesn’t exist.

An old question I know, but I was getting 2147942401 error on windows 2016 server.

If you look at the scheduled task properties, on the bottom of the General Tab, it was defaulted to Configure for: Windows Vista, Windows Server 2008.

Changed to Windows Server 2016 and the problem was solved.

Throwing another common cause of the error action «powershell.exe» with return code 2147942401 here. If your action arguments are not correct you will also get this error message. Check that the action argument parameters and parameter values are spaced correctly.

Broken Example (no space between the ‘file’ parameter and it’s value):

M Herbener’s answer led to me attempting to run the script manually, to see if the script had an error. It did not, but it did highlight what the problem was as I received the error message:

[my script] cannot be loaded because running scripts is disabled on this system.

The solution, of course, was to run Set-ExecutionPolicy to allow Powershell scripts to run.

In this case, there was no point messing with the Group Policy settings because sometimes it would work. But not everytime. Which means it’s a timing problem, not a Policy problem.

Recreating, reconfiguring my task (as suggested in this SuperUser Q&A) did not fix the problem.

I did also consider butchering my batch file and getting rid of the standard output redirection, thus abandonning the logging capability (and becoming blind). Or simply running an actual «*.exe» process, instead of using a batch file at all. This could potentially have been a solution.

I also considered replacing the «At startup» scheduled task by a full-blown Service, but this would have been an expensive experiment for such a trivial problem.

Ultimately, I remembered that services can be delayed: «Automatic» vs. «Automatic (Delayed Start)». So I imitated this by added a delay on the scheduled task, in the Tasks Scheduler. For «At startup» scheduled tasks, it’s the trigger that have individual properties of its own, and that’s where the delay can be configured:

eU4zy

I believe my scheduled task was sometimes being started a few milliseconds too early and some OS service or functionality was not yet available or allowed. Simply adding a small delay on the trigger fixed the problem.

Источник

Действия c windows system32 cmd exe с кодом возврата 2147942401

trans

Вопрос

trans

trans

Ответы

trans

trans

Thank you and write here again if problem persists.

Regards, Ravikumar P

Все ответы

trans

trans

Please check the link http://www.blogfodder.co.uk/2012/4/20/win-2008-task-scheduler-with-return-code-1-0x1.

Thanks, Swapnil Prajapati

trans

trans

Its not helping me at all.

any other suggestion please.

trans

trans

Thank you and write here again if problem persists.

Regards, Ravikumar P

trans

trans

That does not help at all.

I think Microsoft dropped ball on windows 2008, and just wondering intentionaly or not.

So far windows 2003 is the best server platform created in terms of maintenance. And if someone from Microsoft actually reading postings here can you please roll back security changes implemented in windows 2008 because those changes makes system unstable and basically useless for businesses, meanwhile hackers have a field days with it.

I working with task schedulers since 1996 and so far this is the worse of all. So many permissions issues that we switch our batch server back to 2003 and hopping that windows 2012 will not have that many loose screws.

Источник

Действия c windows system32 cmd exe с кодом возврата 2147942401

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

trans

Answered by:

trans

Question

trans

trans

Answers

trans

trans

Thank you and write here again if problem persists.

Regards, Ravikumar P

trans

trans

Please check the link http://www.blogfodder.co.uk/2012/4/20/win-2008-task-scheduler-with-return-code-1-0x1.

Thanks, Swapnil Prajapati

trans

trans

Its not helping me at all.

any other suggestion please.

trans

trans

Thank you and write here again if problem persists.

Regards, Ravikumar P

trans

trans

That does not help at all.

I think Microsoft dropped ball on windows 2008, and just wondering intentionaly or not.

So far windows 2003 is the best server platform created in terms of maintenance. And if someone from Microsoft actually reading postings here can you please roll back security changes implemented in windows 2008 because those changes makes system unstable and basically useless for businesses, meanwhile hackers have a field days with it.

I working with task schedulers since 1996 and so far this is the worse of all. So many permissions issues that we switch our batch server back to 2003 and hopping that windows 2012 will not have that many loose screws.

Источник

Коды возврата ошибок (расшифровки ErrorLevel)*

Коды возврата ошибок (встроенных команд и других программ)

Порядок получения код возврата
Запускаем приложение, следующей командой проверяем переменную %ErrorLevel%. Есть еще такие варианты написания.
Например,

В языках высокого уровня код возврата можно получить API функцией:

А задать код при выходе из программы с помощью функций:

либо указав число, которое вернет основная функция,
например main в C++:

Перечень ErrorLevel в этой теме:

Параноя возврата ошибок. Стоит ли проверять каждое действие? Когда останавливаться?
Если. если..если.. Партянка будет длинной.. Например, через 10 лет села батарейка-системная.

tickКоды возврата
Код возврата 2. Причина: ошибки работы встроенных средств оболочки. Мой вопрос: какие есть у.

sov44, ну там не так много.

Это наверное больше вопрос ко мне, что надо бы развивать тему, раз предложил =)
Badger, все это время, готового не находил по встроенным командам (ай-да и не искал).
Если что найдете, выкладываем. Пока информации 0. Есть только по другим (внешним) программам, вроде WinRAR.

А для тестирования вручную нужно готовить среду, чтобы испытать команды в разных ситуациях (то ли это нехватка прав, работа с заблокированным объектом) и т.д.

По другой предложенной темы (ключи) инфы довольно много.

Ну что же начнем собирать.

Операция успешно завершена. 1 Предупреждение. Произошли некритические ошибки. 2 Произошла критическая ошибка. 3 Неверная контрольная сумма CRC32. Данные повреждены. 4 Предпринята попытка изменить заблокированный архив. 5 Произошла ошибка записи на диск. 6 Произошла ошибка открытия файла. 7 Ошибка при указании параметра в командной строке. 8 Недостаточно памяти для выполнения операции. 9 Ошибка при создании файла. 10 Нет файлов, удовлетворяющих указанной маске, и параметров. 255 Операция была прервана пользователем.

Ок, Charles Kludge, исправился. Раз некоторые приложения для кода возврата выделяют буфер DWORD,
думаю, будет нелишним опубликовать и такие значения:

Ясно, значит у меня ответ вернуло 2-байтовый. FFFFFFFFC000013A.

P.S. Тестировал через

Видать, индусы поняли, чтобы возвращать DWORD, придётся писать очередной костыль и забили.:jokingly:

Провел небольшой тест.

Один раз получил странную ошибку. Copy скопировала файл, после чего написала, что «я такого имени не знаю. » =)) Error 9009

По итогам +Errorlevel:

Успешное завершение/Program suseccfully completed. 4 Файл не найден/The system cannot find the file specified. 4 Доступ запрещён/Access is denied. Нет прав доступа к ресурсу. 4 Невозможно скопировать файл поверх самого себя/The file cannot be copied onto itself

errorlevel = 0, даже, если пользователь ответил «Не заменять файл».

Также видим, что в случаях с защищенной правами папкой или когда файл не существует
мы получаем Errorlevel 1 (а не ожидаемые дефолтовые 5 и 2 соответственно).

Успешное завершение/Program suseccfully completed. 1 Файл не найден/The system cannot find the file specified. 1 Доступ запрещён/Access is denied. Нет прав доступа к ресурсу. 1 Невозможно скопировать файл поверх самого себя/The file cannot be copied onto itself

errorlevel = 0, даже если пользователь ответил «Не заменять файл»
Чтобы консоль задала этот вопрос:
1) для одиночного файла нужно указать ключ /-y

250 МБ затрачивается на

1,5 сек. больше времени. Не знаю, что именно оно проверяет, но уж файл точно целиком не считывается.

Из предыдущего поста видно, что команда copy возвращает только коды 0, 1,
что есть совсем не айс.

Я написал надстройку, которая согласовывает ошибки согласно таблице, приведенной Charles Kludge.
Естественно, это просто демо, экспериментальный набросок кода.

Robocopy

Hex Decimal Meaning
0×10 16 Serious error. Robocopy did not copy any files.
Either a usage error or an error due to insufficient access privileges
on the source or destination directories.
0×08 8 Some files or directories could not be copied
(copy errors occurred and the retry limit was exceeded).
Check these errors further.
0×04 4 Some Mismatched files or directories were detected.
Examine the output log. Some housekeeping may be needed.
0×02 2 Some Extra files or directories were detected.
Examine the output log for details.
0×01 1 One or more files were copied successfully (that is, new files have arrived).
0×00 No errors occurred, and no copying was done.
The source and destination directory trees are completely synchronized.

Таким Batch-файлом получим короткое описание ошибок.
Нет ошибок 1 Предупреждение (Не фатальная ошибка(и)). Например, один или более файлов были блокированы другим приложением, таким образом, они не были сжаты. 2 Фатальная ошибка 7 Ошибка командной строки 8 Недостаточно памяти для операции 255 Пользователь остановил процесс

Коды ошибок, Коды ошибок для пользователей (не для мастеров)
ОшибкаПричинаE10проблемы подачи воды. Проверьте не закрыт ли кран, не забита ли сеточка, достаточно.

Krups Коды ошибок
Привезли десяток машинок Krups на ремонт, скиньте, пожалуйста, коды ошибок, чтобы не ползать за.

Коды ошибок в BAss
Всем привет. Кто знает как исправить ошибки Error codes list 0 BASS_OK 1 BASS_ERROR_MEM 2.

Коды ошибок Windows
Вам приходилось встречать при работе на компьютере раздражающие всплывающие окна с указанием.

Коды ошибок смартфонов!
После номера ошибки указывается название и описание. Общие ошибки: (-1)Not Found: не удалось.

Источник

Powershell script gives err 2147942401 in task scheduler:

It runs on a 64 bit PC; runs OK in powershell ISE and also in powershell itself.

The error massage is: Launche failure:

Task Scheduler failed to start «zendRecentGPG» task for user «DESKTOP-OVGENM6pinte». Additional Data: Error Value: 2147942402.

My executionpolicy is : unrestricted

Anybody an idea of the cause or how to debug further?

daily challenge 914d5611f763af9a14a3f7a855ef6c652ea086d05b395af20a59cbb5674f8a61

mini magick20150822 31223 1h5c2jm big

Create a bat file and schedule the bat file to run, the bat file should contain your PowerShell as above

mini magick20220324 70 17faoap big

Error Value: 2147942402 means file not found.

maybe also read here

thanks, I added GPEDIT.MSC since I have a home version of W10 and added my account at the «logon as a batch job», if that is what you ment.

It still gives the same error. I presume I do not have to add a env: path since it is fully specified in my arguments.

I ran the task with following checked:

v run hen logged on or not

v do not store psw

v run with highest priviledges.

mini magick20150822 31223 1h5c2jm big

That is not what I meant. I mean bat file, such as script.bat

But as Neally pointed out, the error is file not found

is not a full path, you need to complete this with

or whatever drive letter and location the file actually is.

mini magick20220324 70 17faoap medium

Indeed I must have overwritten the drive letter when I recently added «Bypass». After re-adding D: [path]…. where the script is located, I still have the same error after double checking path and filename.

mini magick20150822 31223 1h5c2jm big

Task Scheduler failed to start «zendRecentGPG»

Is this the task name or something else, why does it have a at the start and should it not be PGP instead of GPG?

I prefer not to use a bat of vbs file, but if it is not possible without it, I ll do that. In that case can I hide the execution of the bath and the PS1 from being displayed.

@rodit: my powershell script : d:DATA-MEDIONsoft_ontwikkelingpowershellzendRecentPGP16.ps1

rodit: and indeed, you are right, the taskname is zendGPG while the correct filename is zendRecentPGP16.PS1, but this isn’t important, only confusing indeed.

rod-it; as for the at the beginning of the «zendRecentGPG» name, I do not know where it comes from.

I found the error. My path to the powershell.exe was incomplete: it should have been

After correction it return code 0

Thanks to all for yr kind help!!

mini magick20220324 70 17faoap big

I found the error. My path to the powershell.exe was incomplete: it should have been

After correction it return code 0

Thanks to all for yr kind help!!

It should work if you just put «powershell.exe», usually no need for the full path

mini magick20190627 23292

For what it’s worth, I was having a lot of trouble getting my scripts to run automatically via task scheduler. I’ve found that creating scheduled jobs via PS directly is far easier. Using the below code to set up the automatic jobs has saved me a bunch of headaches. Plus it can be run with whichever credentials needed, or set up on a remote computer easily.

Источник

  • Remove From My Forums
  • Question

  • Hello,

    I hope someone can help me out with this.  I’ve tried multiple ways of trying to run a batch from task scheduler but no matter what I do it fails.  Now, this has worked perfectly fine in Windows 2008 R2, and prior, but it’s just Windows Server
    2012 R2 that’s now giving me a problem.   If I run this batch from a command line, no problem but from task scheduler it gives me error «2147942667», which is «The directory name is invalid». 

    Task runs as Administrator and the actions are Program/Script: build.bat   Start in: M:WorkSource   I’ve also set the Program/Script to the whole path M:WorkSourcebuild.bat and the Start in to M:WorkSource but it’s the same error.

    There are NO quotes, which I know was a problem for many in Windows 2008.  This «M» drive is a mapped network drive to an NFS share and all permissions are correct.   Like I previously stated, other Windows Servers (2003 and 2008)
    have no problems executing this batch, it’s just Windows 2012 (Std) R2.

    Any help is GREATLY appreciated, otherwise I have an expensive piece of metal here doing nothing.  ;)

    Thanks!
    Drew

  1. HowTo
  2. Batch Howtos
  3. Batch File From Scheduled Task Returns …
  1. Understand the Error
  2. Possible Causes of the Error
  3. Ways to Solve the Error

Batch File From Scheduled Task Returns Code 2147942401

Windows Task Scheduler is an application that automates tasks and launches programs or scripts at specified intervals. It is an easy-to-use application with just a few clicks.

But when you run a Batch file through Windows Task Scheduler, sometimes it may return with errors. The most common error is the return code (0x1).

There are many reasons why this error occurs. When you schedule a task to run a Batch file, it may result in the return code 2147942401.

However, when you manually run the task, it will work fine and run with a return code (0x0).

This tutorial will illustrate different ways to solve the error task successfully completed with the return code 2147942401.

Understand the Error

The error codes for Windows Task Scheduler are listed in hexadecimal numbers. The error here is 2147942401 when converted to hexadecimal, resulting in 0X80070001.

This error is defined as an incorrect function or illegal function. Though this error code is not listed in MSDN, it is a common error many users face when using Task Scheduler to run Batch files.

Possible Causes of the Error

The error code may occur due to many possible reasons.

  1. It may be due to a mistake in your Batch file or while scheduling a task.
  2. A scheduled task will only run when the user who created and scheduled the task is logged on. However, you can change it to run when the user is not logged on by special privilege, Log on as a batch job.
  3. If the user is logged in and it still shows the error, it may be because of not providing enough privileges.
  4. Another possible reason for this error code may be the system path issue.

Ways to Solve the Error

  1. Assigning special privilege

    Type Windows+R to open the Run window and type secpol.msc /s to open the Local Security Policy window.

    open run tab

    Now, navigate to Local Policies > User Rights Assignment > Log on as a batch job. Double-click the Log on as a batch job to open the Properties window.

    log on as a batch job

    Click the Add User or Group button to add the relevant users.

    Properties window-batch job

    Add the username in the text box and click on OK.

    add users

    The scheduled task will run the Batch file even if the user is not logged in.

  2. Provide the highest privileges

    When creating a task, choose Create Task instead of Create Basic Task, especially for servers, as it gives you more options for server type, as shown below.

    create a task

    By default, it is set to Windows Vista, Windows Server 2008. If you are using Windows 10, choose Windows 10 from the configured list.

    To set the task to run with the highest privileges, check the box labeled Run with highest privileges. The user should have the necessary privileges to execute the commands in the Batch file.

    Otherwise, it will show the task as completed successfully with return code 2147942401.

    run task with highest privileges

    Also, the user account should be taken care of if you use it on a server. The Batch should not execute commands under the user account on the local machine.

    While creating a task, click on Change User or Group and add the relevant user even if you’re already logged in with the same user.

    change user or group

  3. Add directory path via the Start in option

    Another way of solving the error code (0x1) is by assigning the directory path. Right-click on the task and click on Properties to open the Properties window.

    action tab-properties window

    Under the Actions tab, double-click on the action Start a program and add the Batch file’s directory in the Start in (optional): textbox.

    add batch file directory

So, we discussed three ways to solve the error task successfully completed with the return code 2147942401. There are several possible reasons why this error appears, so if one method doesn’t work, you should try another method as discussed above.

Related Article — Batch Error

  • Error Handling in Batch ScriptEzoic
  • Понравилась статья? Поделить с друзьями:
  • Действительная цифровая лицензия на windows 10 home скачать
  • Два apache на одном сервере windows
  • Действие при подключении устройства windows 10
  • Даунгрейд windows server 2019 до 2012
  • Действие при закрытии крышки ноутбука windows 10 cmd