Windows start process with name

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.

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.

Читайте также:  Пинг по маку windows

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.

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.

Как работать с процессами в Powershell используя Get и Start-Proccess

26 сентября 2019

Процессы — это один из основных компонентов Windows и чаще всего мы работаем с ними через Task Manager (диспетчер задач), но эта возможность становится весомее если мы используем команды по управлению процессами в Powershell. Основные команды по управлению запущенными задачами можно увидеть так:

Мы получим следующий вывод:

  • Debug-Process — возможность мониторинга и отладки процессов. Для его работы нужно загрузить дополнительное ПО.
  • Get-Process — получение в Powershell списка процессов.
  • Start-Process — запуск процессов.
  • Stop-Process — убивает (завершает) процесс.
  • Wait-Process — ожидание окончания процесса.

Таких команд и вариантов их использования очень много. Например мы можем работать с процессами через WMI или использовать их в связке с мониторингом сетевых подключений через Get-NetTCPConnection.

Получив список процессов в Powershell можно увидеть что значения отображаются в Кб:

Изменить это можно через выражения:

В скрипте выше будут выводиться 5 свойств, но их намного больше. Посмотреть возможные свойства можно так:

Каждое это свойство можно вызвать так:

Можно вызвать все свойства всех процессов или по одному выбранному:

Кроме свойств есть еще методы .NET, которые выводятся без дополнительных ключей или с указанием:

Методы полезны тем, что ими можно воспользоваться не прибегая к дополнительным командам. Для примера так мы можем остановить процесс notepad (блокнот) тремя разными способами:

Методы .NET не всегда так очевидны, как командлеты поэтому к ним нужно прибегать с осторожностью.

При получении списка процессов есть параметр, который выводит путь откуда запущен процесс и версию файла:

В варианте выше у нас будет много не критичных ошибок:

  • Get-Process : Не удалось перечислить информацию о версиях файла для процесса «svchost».
  • Get-Process : Cannot enumerate the file version information of the «csrss» process.

Связано это с тем, что не все процессы в Powershell имеют версии и выполняется запрос несуществующего свойства. Этого можно избежать двумя путями, первый — это указать параметр, который будет игнорировать эти ошибки:

Или запросить информацию о конкретном процессе:

Ключ FileVersionInfo это три свойства: Product, FileVersion и Path каждый из которых можно вывести отдельно. Получим процессы в Powershell со свойством времени запуска и отсортируем их:

Если нужно выяснить когда и кто запустил процесс нужно добавить параметр IncludeUserName. В моем примере это два процесса:

Эти же команды можно выполнять удаленно. Во всех командах Powershell, где есть ключ ComputerName можно указать минимум один удаленный компьютер:

Выполняя удаленную команду вы можете получить две ошибки. Первую, если у вас не настроена возможность удаленного управления в Powershell. И вторая, если вы укажете ключ -IncludeUserName, почему-то он не работает совместно с ComputerName:

  • Get-Process : Parameter set cannot be resolved using the specified named parameters.

Запуск процессов с Powershell Start-Process

На примере запуска блокнота команда выполняется так:

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

Если в программа может принимать аргументы их так же можно добавить:

По умолчанию окно процесса разворачивается. Если хотите запустить свернутым, то добавьте ключ WindowStyle:

Ключ WindowStyle принимает 4 значения:

  • minimized — свернутый вариант.
  • hidden — скрытый режим.
  • normal — обычный.
  • maximized — полностью развернутый.

Добавив ключ NoNewWindow, в случае с tracert, команда выполнится в текущем окне:

Если мы запускаем процесс, который подразумевает вывод, но не хотим открывать окно программы, то нам понадобится перенаправить вывод команд. Для этого есть два ключа:

  • RedirectStandardOutput — перенаправляет вывод
  • RedirectStandardError — перенаправляет ошибки
  • RedirectStandardInput — перенаправляет ввод

Воспользоваться этими ключами можно так:

Если нужно открыть файл в определенной программе, то это делается так:

Отмечу, что ни одна команда PS не позволяет запускать процессы в интерактивном сеансе пользователя (например открыть пользователю Excel). Если вы хотите использовать такой метод, то вам нужно использовать psexec от SysInternals либо помещать задачи в планировщик и выполнять оттуда.

Пример по работе с процессами в Powershell

Директории, откуда работает основная часть программ относятся к Windows и Program Files. Работа программ из Application Data, например, всегда подозрительна. Мы можем мониторить запуск процессов из этой директории. Нам нужно объявить переменные с путями, которые не будут вызывать подозрений и проверять путь процессов на вхождение:

Второй пример выполнения — это запуск всех файлов из папки. Обычно скрипты применяются через групповые политики в момент входа пользователя. Если таких скриптов 10, то мы можем поместить их в определенную папку и запускать из планировщика задач указывая только директорию и расширение запускаемого файла и перенаправлять ошибки в индивидуальный файл:

Обратите внимание, что все файлы с ошибками будут сохраняться с именем компьютеров на котором запущен скрипт. В каждом из скриптов я так же ставил знак *, это связано не с точным вхождением. Например в первом случае после пути C:\Users* мы ожидаем еще символы и установив звездочку мы это указали. В случае Get-ChildItem ситуация похожая, но более подробно мы обсуждали в статье поиск файлов в Powershell.

Мы можем использовать поиск процессов не относящихся к производителям ПО, которые мы устанавливали на ПК пользователей. Для этого есть свойство Company. Не все объекты имеют имя компании, они связаны с задачами операционной системы:

По умолчанию мы получаем данные по CPU в секундах, но следующий скрипт вернет процент использования:

Далее эту функцию можно запускать на удаленных компьютерах:

Читайте также:  Find windows installer folder
Оцените статью