Запустить word из powershell

Обновлено: 04.07.2024

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.

This example uses splatting to pass parameters to the cmdlet. For more information, see about_Splatting.

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. The cmdlet joins the array into a single string with each element of the array separated by a single space.

The outer quotes of the PowerShell strings are not included when the ArgumentList values are passed to the new process. If parameters or parameter values contain a space or quotes, they need to be surrounded with escaped double quotes. For more information, see about_Quoting_Rules.

For the best results, use a single ArgumentList value containing all of the arguments and any needed quote characters.

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 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.

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.

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

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

The parameter does not apply for non-Windows systems. When using on non-Windows systems, you never get a new window.

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

By default, Start-Process launches a process asynchronously. Control is instantly returned to PowerShell even if the new process is still running.

  • On the local system, the launched process lives on independent from the calling process.
  • On a remote system, the new process is terminated when the remote session ends, immediately following the Start-Process command. Therefore, you cannot use Start-Process in a remote session expecting the launched process to outlive the session.

If you do need to use Start-Process in a remote session, invoke it with the Wait parameter. Or you could use other methods to create a new process on the remote system.

When using the Wait parameter, Start-Process waits for the process tree (the process and all its descendants) to exit before returning control. This is different than the behavior of the Wait-Process cmdlet, which only waits for the specified processes to exit.

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 .

Иногда приходится создавать с помощью PowerShell различные документы (отчеты по серверам, выборки из логов и пр. подобная информация). Обычно данные сохраняются в виде обычного текстового файла, либо конвертируются в HTML. Но если у вас на компьютере установлен MS Office, то данные можно сохранять в виде документа Word. Итак, предположим, что нам необходимо создать новый документ и добавить в него текст.

Первым делом запускаем Word:

$Word = New-Object -ComObject Word.Application

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

Cоздаем новый документ:

Документ открыт, но перед тем, как приступить к его редактированию, необходимо выделить участок текста или весь документ:

Теперь добавим в документ текст с помощью метода TypeText:

и сохраним документ в файл:

$File = C:\Temp\psword.doc
$Document.SaveAs([ref]$File)

Закрываем документ и выходим из Word:

создание документа

А теперь откроем созданный файл. Для этого опять запускаем Word и делаем его видимым:

$Word = New-Object -ComObject Word.Application
$Word.Visible = $true

$File = ″C:\Temp\psword.doc″
$Document = $Word.Document.Open($File)

открытие документа

И смотрим, что получилось.

открытый документ

Теперь добавим еще пару строк текста. А для того, чтобы разбить текст на строки, используем метод TypeParagraph:

$Selection = $Word.Selection
$Selection.TypeParagraph()
$Selection.TypeText(″Power″)
$Selection.TypeText(″Shell″)
$Selection.TypeParagraph()
$Selection.TypeText(″&″)
$Selection.TypeParagraph()
$Selection.TypeText(″Word″)

редактирование документа

отредактированный документ

Ну и в завершение немного украсим текст. Для этого выберем шрифт:

Сделаем шрифт жирным (Bold) и наклонным (Italic):

$Selection.Font.Bold = $True
$Selection.Font.Italic = $True

Увеличим размер шрифта:

И изменим цвет на зеленый:

изменение шрифтов и цвета

В результате получим такую картину

измененный документ

Посмотреть доступные цвета можно командой:

получение списка цветов

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

Прямой запуск

Set-Location ″C:\Program Files″
.\Hello.exe

Прямой запуск программы из PoSh

Обратите внимание, что даже находясь в нужном каталоге, требуется указывать относительный путь к исполняемому файлу. Исключение составляют файлы из директорий, перечисленных в переменной окружения (path). Например различные встроенные программы и утилиты (notepad, calc, ping и т.п.), находящиеся в директории Windows\System32, можно запускать без указания пути.

запуск встроенных утилит

Оператор &

Если необходимо указать полный путь к исполняемому файлу, то можно воспользоваться оператором & (оператор вызова). Он позволяет выполнить строку текста, указанную в кавычках, как единую команду. Например:

запуск с использованием символа &

Поскольку оператор & не анализирует передаваемую команду, то он не может интерпретировать ее параметры. Поэтому дополнительные параметры\аргументы передаются также в виде текста, в кавычках. Для примера возьмем предыдущую программу и немного изменим ее, так что она принимает нужный текст в виде аргумента:

& ′C:\Program Files\Hello.exe′ ′Hello, world′

При желании можно указать нескольких аргументов через запятую:

& ′C:\Program Files\Hello.exe′ ′Hello,′, ′ world′

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

$exe = ′C:\Program Files\Hello.exe′
$arg1 = ′Hello′
$arg2 = ′world′
& $exe $arg1 $arg2

запуск с аргументами

Ну и если аргументов много, то их можно объединить, воспользовавшись такой конструкцией:

$exe = ′C:\Program Files\Hello.exe′
$allargs = @(′Hello,′,′world′)
& $exe $allargs

варианты передачи аргументов

Invoke-Expression

Invoke-Expression -Command ′C:\Windows\Hello.exe′

Invoke-Expression -Command ′C:\Program Files\Hello.exe′

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

Invoke-Expression -Command ″C:\′Program Files′\Hello.exe″

использование Invoke-Expression для запуска программы

Start-Process

Start-Process -FilePath ′C:\Program Files\Hello.exe′

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

Start-Process -FilePath ′C:\Program Files\Hello.exe′ -NoNewWindow -Wait

Также Start-Process позволяет передать в процесс дополнительные аргументы:

Start-Process -FilePath ′C:\Program Files\Hello.exe′ -ArgumentList ′Hello, world′ -NoNewWindow -Wait

запуск с использованием Start-Process

По умолчанию командлет ничего не возвращает, но с помощью параметра -PassThru можно заставить его вернуть объект процесса. Этот объект очень удобно поместить в переменную:

$process = Start-Process -FilePath ′C:\Program Files\Hello.exe′ -Wait -PassThru

из которой можно затем можно узнать многие полезные вещи, такие как статус:

или код выполнения:

варианты использования Start-Process

использование класса .Net для запуска программы

Такой способ достаточно неудобен и громоздок (на мой взгляд), но чуть более гибок в использовании. Для примера запустим нашу программу в текущем окне, передадим в нее аргументы и заберем результат выполнения:

варианты использования .Net

С помощью WMI можно сделать практически все, в том числе и запустить программу. Для этого вполне подойдет метод Create WMI-класса Win32_Process. Этот метод запускает процесс на локальном или удаленном компьютере через RPC. Например, для выполнения программы на локальном компьютере можно воспользоваться такой командой:

А для выполнения на удаленном компьютере команда будет выглядеть так:

запуск программы через WMI, способ 1

Как вариант, можно воспользоваться командлетом Invoke-WmiMethod:

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList ″C:\Program Files\Hello.exe″

запуск программы через WMI, способ 2

Либо командлетом Invoke-CimMethod:

Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @

использование командлета Invoke-CimMethod

WMI запускает процесс в отдельном окне и возвращает объект, содержащий идентификатор процесса (ProcessID) и результат выполнения (ReturnValue). ReturnValue может принимать следующие значения:

Invoke-Command

Командлет Invoke-Command умеет выполнять команды на локальном или удаленном компьютере, используя WinRM. Например, для запуска нашей программы на локальном компьютере используем команду:

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

Обратите внимание, что Invoke-Command не очень дружит с пробелами, поэтому во избежании ошибок приходится исхитряться с кавычками. Впрочем, подобных проблем можно избежать, например комбинируя использования командлета с оператором &:

запуск программы с помощью Invoke-Command

Invoke-Command -ScriptBlock -ComputerName SRV1,SRV2,SRV3

$scriptblock =
$Computers = @(′SRV1′,′SRV2′,′SRV3′)
Invoke-Command -ScriptBlock $scriptblock -ComputerName $Computers

По умолчанию командлет возвращает результат выполнения программы, а если запустить его в фоновом режиме (параметр -AsJob), то возвращает объект Job:

Invoke-Command -ScriptBlock -ComputerName localhost -AsJob -JobName Hello

запуск Invoke-Command в фоновом режиме

Invoke-Item

Командлет Invoke-Item предназначен для применения к файлу действия по умолчанию. Так запустить исполняемый файл можно командой:

Invoke-Item -Path ″C:\Program Files\Hello.exe″

Однако наиболее удобно использовать Invoke-Item для открытия определенного типа файлов. Например так мы откроем текстовый файл:

Invoke-Item -Path ″C:\Files\test.txt″

А так все текстовые файлы в папке:

Invoke-Item -Path ″C:\Files\*.txt″

использование Invoke-Item

cmd /c ″C:\Program Files\Hello.exe″

запуск программы с помощью cmd

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

Кстати, статья написана по мотивам PowerShell: Deep Dive and Best Practice. Рекомендую почитать, там еще много интересного.

Итак, предположим, у меня есть скрипт start.ps1, который мне необходимо запускать ежедневно в течении 10 дней. Есть два способа решить эту задачу.

Способ 1

Для запуска скрипта воспользуемся оснасткой Task Scheduler, он же планировщик заданий. Найти его можно в разделе Administrative Tools, либо нажав Win+R и введя команду taskschd.msc. Открываем планировщик и в разделе Actions выбираем пункт Create Task.

создаем запланированное задание в Task Scheduler

На вкладке General указываем имя и описание задания, а также (по необходимости) пользователя, от имени которого задание будет запускаться. Для того, чтобы задание выполнялось вне зависимости от того, залогинен ли пользователь в системе, выбираем опцию «Run whether user is logged on or not». Если для выполнения задания требуется повышение привилегий, то отмечаем опцию «Run with highest privileges».

новое задание, вкладка General

Примечание. Если вы хотите запускать задание чаще, чем раз в день, то надо выбрать одноразовое выполнение (One time), а в разделе Advanced settings отметить пункт Repeat task every и указать время повторения, минимум 5 минут, максимум 1 час. Если этого недостаточно, то дополнительно в поле Delay task for up to можно указать временную задержку.

задаем условие для запуска задания

И основное. Переходим на вкладку Action и указываем действие для запланированного задания. Напомню, что в целях безопасности PowerShell скрипты могут выполняться только интерактивно, то есть сначала надо запустить оболочку PowerShell и уже в ней указать путь к скрипту. Поэтому в поле «Action» указываем запуск powershell.exe, а в поле «Add Arguments» параметр -File и путь к нашему скрипту, вот так:

Также в поле аргументы можно указать:

указываем действие для запланированного задания

Заполнив необходимые поля жмем ОК и сохраняем задание. Теперь скрипт будет запускаться по расписанию ежедневно в заданное время в течении 10 дней.

Способ 2

В PowerShell 3.0 появился новый функционал Sheduled Job, дающий возможность создавать запланированные задания прямо из консоли, не пользуясь оснасткой планировщика. Воспользуемся им для планового запуска нашего скрипта.

Сначала создаем расписание запуска (ежедневно в полпятого вечера, в течении 10 дней):

$t = New-JobTrigger -Daily -At 4:30PM -DaysInterval 10

Затем сохраняем в переменной учетные данные:

$cred = Get-Credential contoso\administrator

В качестве опции указываем запуск задания с повышенными привилегиями:

$o = New-ScheduledJobOption -RunElevated

И регистрируем задание с именем Start:

Register-ScheduledJob -Name Start -FilePath C:\Scripts\start.ps1 -Trigger $t -Credential $cred -ScheduledJobOption $o

создание запланированного задания в PowerShell

Чтобы убедится в том, что задание создано, можно открыть планировщик и найти наше задание в разделе Microsoft\Windows\PowerShell\SheduledJobs.

запланированное задание в Task Sheduler

Execution Policy

В заключение напомню об одном немаловажном моменте, а именно о политике выполнения скриптов Execution Policy. Посмотреть текущее значение политики можно командой Get-ExecutionPolicy . Политика выполнения может иметь значения:

Обычно для безпроблемного выполнения скриптов достаточно задать значение RemoteSigned. Изменить текущее значение можно командой Set-ExecutionPolicy , например:

Set-ExecutionPolicy RemoteSigned -force

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

Читайте также: