Windows start system process

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.

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.

Читайте также:  Как исправить ошибку 0x81000203 защита системы windows 10

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

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.

Читайте также:  Что такое windows post install wizard
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.

Запуск командной строки/ программы от имени SYSTEM в Windows

В Windows для выполнения некоторых действий недостаточно иметь права администратора. Например, вы не сможете заменить или удалить системные файлы, некоторые ветки реестра, остановить системные службы или выполнить другие потенциально небезопасные действия, которые могут нарушить стабильность системы. Системному администратору в таких случая приходится назначать себе владельцем таких объектов или выполнять действия от имени системы. В этой статье мы рассмотрим, как запустить программу или командную строку в Windows от имени привилегированного аккаунта SYSTEM (Local System).

Запуск командной строки от Local System в старых версиях Windows (до Vista)

В снятых с поддержки Windows XP и Windows Server 2003 была интересная возможность, позволяющая запустить программу или же интерактивную командную строку (cmd) с правами системы через планировщик. Достаточно войти с правами администратора, открыть командную строку и набрать в ней:

at 12:23 /interactive cmd.exe

, где 12:23 – текущее время + одна минута (в 24 часовом формате).

После наступления указанного времени перед вами открывается окно командной строки, запущенное с правами Local System. Если вы выполнили эту команду в терминальном (rdp) сессии Windows Server 2003/XP, имейте в виду, что командная строка с правами System отображается только в консольной сессии (как подключиться к rdp консоли).

В Windows 10 запуск интерактивной строки с помощью команды at не поддерживается. Вместо него рекомендуется использовать schtasks.exe .

Запуск программ от имени системы с помощью PSExec в Windows 10

Начиная с Windows 7 трюк с запуском интерактивной командной строки от имени системы через планировщик не работает. Для запуска команд от имени NT Authority\ System можно использовать утилиту PSExec.exe от Sysinternals.

Утилита PSExec не требует установки. Откройте командную строку с правами администратора (“Run as administrator”) перейдите в каталог, в котором находится исполняемый файл PSexec.exe и наберите:

psexec -i -s cmd.exe

параметр -i запускает приложение в интерактивном режиме (пользователь может взаимодействовать с программой на рабочем столе, если это параметр не указывать, процесс запускается в консольной сесии), —s означает что командную строку нужно запустить из-под системы

После выполнения команды появится новое окно с командной строкой, запущенной из-под учетной записи NT Authority\System. Проверьте это, выполнив команду:

В открывшемся окне командной строки вы можете выполнять любые команды в контексте SYSTEM. Теперь вы сможете изменить, переименовать или удалить системные файлы/ветки реестра, владельцем которых является TrustedInstaller или SYSTEM. Все программы или процессы, которые вы запустите их этого окна также будут запущены с повышенными привилегиями LocalSystem. Например, можно остановить системную службу, или закрыть дескриптор занятого системой файла.

psexec -s \\msk-PCBuh2 cmd.exe

При появлении ошибки couldn’t install PSEXESVC service , убедитесь, что:

  • командная строка запущена от имени администратора;
  • проверьте, возможно служба PSEXESVC уже запущена.

Есть еще ряд сторонних утилит для запуска программ от имени System (AdvancedRun , RunAsSystem, PowerRun), но я не вижу смысла использовать их смысла. Т.к. во-первых это сторонние утилиты, и вы не можете гарантировать что в их коде нет вредоносных закладок, и во-вторых официальная утилита PsExec от Microsoft отлично справляется с задачей.

Читайте также:  Windows 10 esent ошибка 455
Оцените статью