Windows script start program

Устраняем ошибку Windows Script Host

Исправляем ошибку Windows Script Host

Сразу стоит сказать о том, что если вы писали свой скрипт и при его запуске получили ошибку, то необходимо искать проблемы в коде, а не в системном компоненте. Например, вот такое диалоговое окно говорит именно об этом:

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

Далее мы поговорим о тех моментах, когда при старте Windows или запуске программ, например, Блокнота или Калькулятора, а также других приложений, использующих системные ресурсы, появляется стандартная ошибка Windows Script Host. Иногда подобных окон может появиться сразу несколько. Случается такое после обновления операционной системы, которое может пройти как в штатном режиме, так и со сбоями.

Причины такого поведения ОС следующие:

  • Неверно выставленное системное время.
  • Сбой в работе службы обновлений.
  • Некорректная установка очередного апдейта.
  • Нелицензионная сборка «винды».

Вариант 1: Системное время

Многие пользователи думают, что системное время, которое показывается в области уведомлений, существует только для удобства. Это не совсем так. Некоторые программы, обращающиеся к серверам разработчиков или к иным ресурсам, могут работать некорректно или вовсе отказаться функционировать по причине расхождений в дате и времени. Это же касается и Windows с ее серверами обновления. В том случае, если будет расхождение в вашем системном времени и времени сервера, то могут наблюдаться неполадки с апдейтами, поэтому на это стоит обратить внимание в первую очередь.

    Нажимаем на часы в правом нижнем углу экрана и переходим по ссылке, указанной на скриншоте.


Далее идем на вкладку «Время по интернету» и жмем на кнопку изменения параметров. Обратите внимание, что ваша учетная запись должна обладать правами администратора.


В окне настроек устанавливаем галку в указанный на изображении чекбокс, затем в выпадающем списке «Сервер» выбираем time.windows.com и нажимаем «Обновить сейчас».


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

Теперь ваше системное время будет регулярно синхронизироваться с сервером времени Майкрософт и расхождения не будет.

Вариант 2: Служба обновлений

Windows – это очень сложная система, с множеством одновременно протекающих процессов, и некоторые из них могут повлиять на работу службы, отвечающей за обновление. Высокое потребление ресурсов, различные сбои и занятость компонентов, помогающих апдейту, «заставляют» службу совершать бесконечные попытки выполнить свою работу. Сам сервис также может сбоить. Выход здесь один: отключить его, а затем перезагрузить компьютер.

    Вызываем строку «Выполнить» сочетанием клавиш Win+R и в поле с названием «Открыть» пишем команду, которая позволит получить доступ к соответствующей оснастке.


В списке находим «Центр обновления», кликаем ПКМ и выбираем пункт «Свойства».


В открывшемся окне жмем кнопку «Остановить», а затем ОК.


После перезагрузки служба должна запуститься автоматически. Стоит проверить, так ли это и, если она все еще остановлена, включить ее тем же способом.

Если после выполненных действий ошибки продолжают появляться, то необходимо поработать с уже установленными обновлениями.

Вариант 3: Некорректно установленные обновления

Данный вариант подразумевает удаление тех обновлений, после установки которых начались сбои в Windows Script Host. Сделать это можно как вручную, так и с помощью утилиты восстановления системы. В обоих случаях необходимо вспомнить, когда «посыпались» ошибки, то есть после какой даты.

    Идем в «Панель управления» и находим апплет с названием «Программы и компоненты».


Далее переходим по ссылке, отвечающей за просмотр обновлений.

Читайте также:  Что делать если нет windows powershell


Сортируем список по дате установки, кликнув по шапке последней колонки с надписью «Установлено».


Выбираем нужное обновление, кликаем ПКМ и выбираем «Удалить». Также поступаем с остальными позициями, помня про дату.

  • Перезагружаем компьютер.
    1. Для перехода к данной утилите кликаем правой кнопкой мыши по значку компьютера на рабочем столе и выбираем пункт «Свойства».


    Далее переходим к «Защите системы».


    Нажимаем кнопку «Восстановление».


    В открывшемся окне утилиты жмем «Далее».


    Ставим галку, отвечающую за показ дополнительных точек восстановления. Необходимые нам поинты будут называться «Автоматически созданная точка», тип – «Система». Из них необходимо выбрать ту, которая соответствует дате последнего обновления (или того, после которого начались сбои).


    Жмем «Далее», ждем, пока система предложит перезагрузиться и выполнит действия по «откату» к предыдущему состоянию.


    Обратите внимание, что в этом случае могут быть удалены и те программы и драйвера, которые были установлены вами после этой даты. Узнать, произойдет ли это, можно нажав кнопку «Поиск затрагиваемых программ».

    Читайте также: Как восстановить систему Windows XP, Windows 8, Windows 10

    Вариант 4: Нелицензионная Windows

    Пиратские сборки «винды» хороши лишь тем, что они совершенно бесплатны. В остальном же такие дистрибутивы могут принести массу проблем, в частности, некорректную работу необходимых компонентов. В этом случае рекомендации, приведенные выше, могут не сработать, так как файлы в скачанном образе уже были сбойными. Здесь можно только посоветовать поискать другой дистрибутив, но лучше воспользоваться лицензионной копией Windows.

    Заключение

    Решения проблемы с Windows Script Host довольно просты, и с ними справится даже начинающий пользователь. Причина здесь ровно одна: некорректная работа инструмента обновления системы. В случае с пиратскими дистрибутивами можно дать следующий совет: пользуйтесь только лицензионными продуктами. И да, правильно пишите ваши скрипты.

    Start-Process

    Starts one or more processes on the local computer.

    Syntax

    Description

    The Start-Process cmdlet starts one or more processes on the local computer. By default, Start-Process creates a new process that inherits all the environment variables that are defined in the current process.

    To specify the program that runs in the process, enter an executable file or script file, or a file that can be opened by using a program on the computer. If you specify a non-executable file, Start-Process starts the program that is associated with the file, similar to the Invoke-Item cmdlet.

    You can use the parameters of Start-Process to specify options, such as loading a user profile, starting the process in a new window, or using alternate credentials.

    Examples

    Example 1: Start a process that uses default values

    This example starts a process that uses the Sort.exe file in the current folder. The command uses all of the default values, including the default window style, working folder, and credentials.

    Example 2: Print a text file

    This example starts a process that prints the C:\PS-Test\MyFile.txt file.

    Example 3: Start a process to sort items to a new file

    This example starts a process that sorts items in the Testsort.txt file and returns the sorted items in the Sorted.txt files. Any errors are written to the SortError.txt file.

    The UseNewEnvironment parameter specifies that the process runs with its own environment variables.

    Example 4: Start a process in a maximized window

    This example starts the Notepad.exe process. It maximizes the window and retains the window until the process completes.

    Example 5: Start PowerShell as an administrator

    This example starts PowerShell by using the Run as administrator option.

    Example 6: Using different verbs to start a process

    This example shows how to find the verbs that can be used when starting a process. The available verbs are determined by the filename extension of the file that runs in the process.

    The example uses New-Object to create a System.Diagnostics.ProcessStartInfo object for PowerShell.exe, the file that runs in the PowerShell process. The Verbs property of the ProcessStartInfo object shows that you can use the Open and RunAs verbs with PowerShell.exe , or with any process that runs a .exe file.

    Example 7: Specifying arguments to the process

    Both commands start the Windows command interpreter, issuing a dir command on the Program Files folder. Because this foldername contains a space, the value needs surrounded with escaped quotes. Note that the first command specifies a string as ArgumentList. The second command is a string array.

    Читайте также:  Система windows 10 iot

    Example 8: Create a detached process on Linux

    On Windows, Start-Process creates an independent process that remains running independently of the launching shell. On non-Windows platforms, the newly started process is attached to the shell that launched. If the launching shell is closed, the child process is terminated.

    To avoid terminating the child process on Unix-like platforms, you can combine Start-Process with nohup . The following example launches a background instance of PowerShell on Linux that stays alive even after you close the launching session. The nohup command collects output in file nohup.out in the current directory.

    In this example, Start-Process is running the Linux nohup command, which launches pwsh as a detached process. For more information, see the man page for nohup.

    Parameters

    Specifies parameters or parameter values to use when this cmdlet starts the process. Arguments can be accepted as a single string with the arguments separated by spaces, or as an array of strings separated by commas.

    If parameters or parameter values contain a space, they need to be surrounded with escaped double quotes. For more information, see about_Quoting_Rules.

    Type: String [ ]
    Aliases: Args
    Position: 1
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Prompts you for confirmation before running the cmdlet.

    Type: SwitchParameter
    Aliases: cf
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies a user account that has permission to perform this action. By default, the cmdlet uses the credentials of the current user.

    Type a user name, such as User01 or Domain01\User01, or enter a PSCredential object generated by the Get-Credential cmdlet. If you type a user name, you’re prompted to enter the password.

    Credentials are stored in a PSCredential object and the password is stored as a SecureString.

    For more information about SecureString data protection, see How secure is SecureString?.

    Type: PSCredential
    Aliases: RunAs
    Position: Named
    Default value: Current user
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies the optional path and filename of the program that runs in the process. Enter the name of an executable file or of a document, such as a .txt or .doc file, that is associated with a program on the computer. This parameter is required.

    If you specify only a filename, use the WorkingDirectory parameter to specify the path.

    Type: String
    Aliases: PSPath, Path
    Position: 0
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Indicates that this cmdlet loads the Windows user profile stored in the HKEY_USERS registry key for the current user. The parameter does not apply for non-Windows systems.

    This parameter does not affect the PowerShell profiles. For more information, see about_Profiles.

    Type: SwitchParameter
    Aliases: Lup
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Start the new process in the current console window. By default on Windows, PowerShell opens a new window. On non-Windows systems, you never get a new terminal window.

    You cannot use the NoNewWindow and WindowStyle parameters in the same command.

    The parameter does not apply for non-Windows systems.

    Type: SwitchParameter
    Aliases: nnw
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.

    Type: SwitchParameter
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies a file. This cmdlet sends any errors generated by the process to a file that you specify. Enter the path and filename. By default, the errors are displayed in the console.

    Type: String
    Aliases: RSE
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False
    Читайте также:  Logo booting windows 10

    Specifies a file. This cmdlet reads input from the specified file. Enter the path and filename of the input file. By default, the process gets its input from the keyboard.

    Type: String
    Aliases: RSI
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies a file. This cmdlet sends the output generated by the process to a file that you specify. Enter the path and filename. By default, the output is displayed in the console.

    Type: String
    Aliases: RSO
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Indicates that this cmdlet uses new environment variables specified for the process. By default, the started process runs with the environment variables inherited from the parent process.

    Type: SwitchParameter
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies a verb to use when this cmdlet starts the process. The verbs that are available are determined by the filename extension of the file that runs in the process.

    The following table shows the verbs for some common process file types.

    File type Verbs
    .cmd Edit, Open, Print, RunAs, RunAsUser
    .exe Open, RunAs, RunAsUser
    .txt Open, Print, PrintTo
    .wav Open, Play

    To find the verbs that can be used with the file that runs in a process, use the New-Object cmdlet to create a System.Diagnostics.ProcessStartInfo object for the file. The available verbs are in the Verbs property of the ProcessStartInfo object. For details, see the examples.

    The parameter does not apply for non-Windows systems.

    Type: String
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish.

    Type: SwitchParameter
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Shows what would happen if the cmdlet runs. The cmdlet is not run.

    This parameter was introduced in PowerShell 6.0.

    Type: SwitchParameter
    Aliases: wi
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies the state of the window that is used for the new process. The acceptable values for this parameter are: Normal, Hidden, Minimized, and Maximized. The default value is Normal.

    You cannot use the WindowStyle and NoNewWindow parameters in the same command.

    The parameter does not apply for non-Windows systems.

    Type: ProcessWindowStyle
    Accepted values: Normal, Hidden, Minimized, Maximized
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies the location that the new process should start in. The default is the location of the executable file or document being started. Wildcards are not supported. The path name must not contain characters that would be interpreted as wildcards.

    Type: String
    Position: Named
    Default value: None
    Accept pipeline input: False
    Accept wildcard characters: False

    Inputs

    None

    You cannot pipe input to this cmdlet.

    Outputs

    None, System.Diagnostics.Process

    This cmdlet generates a System.Diagnostics.Process object, if you specify the PassThru parameter. Otherwise, this cmdlet does not return any output.

    Notes

    This cmdlet is implemented by using the Start method of the System.Diagnostics.Process class. For more information about this method, see Process.Start Method.

    On Windows, when you use UseNewEnvironment, the new process starts only containing the default environment variables defined for the Machine scope. This has the side affect that the $env:USERNAME is set to SYSTEM. None of the variables from the User scope are included.

    On Windows, the most common use case for Start-Process is to use the Wait parameter to block progress until the new process exits. On non-Windows system, this is rarely needed since the default behavior for command-line applications is equivalent to Start-Process -Wait .

    When using Start-Process on non-Windows systems, you never get a new terminal window.

    Оцените статью