Попытка запустить исполняемую команду без заголовка через Powershell, которая работает в строке cmd - PullRequest
0 голосов
/ 09 июля 2020

Я пытаюсь запустить исполняемый файл через PowerShell для работы без головы, чтобы установить программу на машину VM / LocalHost. Я могу заставить мастера открыться, но по какой-то причине я не могу заставить его работать без головы. Вот строка cmd, которую я запускаю, которая работает:

start /WAIT setup.exe /clone_wait /S /v" /qn"

Это мои попытки в PowerShell

Start-Process .\setup.exe /S -Wait -PassThru
Start-Process .\setup.exe /S /v /qn -Wait -PassThru
Start-Process setup.exe -ArgumentList '/clone_wait /S /v /qn' -Wait

В экземпляре строки cmd приложение устанавливается без проблем - в экземпляре PowerShell открывается мастер, и появляется первое приглашение «Далее». Приветствуется любая помощь!

Я также попытался добавить дополнительные параметры «/ v» и «/ qn», которые возвращают ошибку: Start-Process: не может быть найден позиционный параметр, который принимает аргумент '/ v'

Нижняя попытка выполняется, но не дожидается завершения установки

Ответы [ 3 ]

2 голосов
/ 09 июля 2020

Возможно, вы слишком много думаете об этом. Помните, что PowerShell - это оболочка . Одна из целей оболочки - запускать команды, которые вы вводите.

Таким образом: Start-Process вам не требуется. Просто введите команду для запуска и нажмите Enter.

PS C:\> .\setup.exe /clone_wait /S /v /qn

Теперь, если исполняемый файл (или сценарий), который вы хотите запустить, содержит пробелы в пути или имени, используйте оператор вызова / вызова (&) и укажите кавычки; например:

PS C:\> & "\package files\setup.exe" /clone_wait /S /v /qn

(Это поведение одинаково независимо от того, находитесь ли вы в командной строке PowerShell или помещаете команду в сценарий.)

1 голос
/ 10 июля 2020

В продолжение всего, что вам было дано до сих пор. Запуск исполняемых файлов через PowerShell - хорошо задокументированный вариант использования.

Итак, первая ссылка дает больше подтверждения того, что вам дано.

5. The Call Operator &

Why: Used to treat a string as a SINGLE command. Useful for dealing with spaces.

In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another command that starts with a number, you have to use the command invocation operator &.

The PowerShell V3.0 parser do it now smarter, in this case you don’t need the & anymore.

Details: Runs a command, script, or script block. The call operator, also known as the "invocation operator," lets you run commands that are stored in variables and represented by strings. Because the call operator does not parse the command, it cannot interpret command parameters

Example:

& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters or there are spaces in the arguments or paths!

With spaces you have to nest Quotation marks and the result it is not always clear! 

In this case it is better to separate everything like so:

$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
 
& $CMD $arg1 $arg2 $arg3 $arg4
 
# or same like that:
 
$AllArgs = @('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
 
& 'SuperApp.exe' $AllArgs
 

 

6. cmd /c - Using the old cmd shell
** This method should no longer be used with V3

Why: Bypasses PowerShell and runs the command from a cmd shell. Often times used with a DIR which runs faster in the cmd shell than in PowerShell (NOTE: This was an issue with PowerShell v2 and its use of .Net 2.0, this is not an issue with V3).

Details: Opens a CMD prompt from within powershell and then executes the command and returns the text of that command. The /c tells CMD that it should terminate after the command has completed. There is little to no reason to use this with V3.

Example:

#runs DIR from a cmd shell, DIR in PowerShell is an alias to GCI. This will return the directory listing as a string but returns much faster than a GCI
cmd /c dir c:\windows




7. Start-Process  (start/saps)


Why: Starts a process and returns the .Net process object Jump if -PassThru is provided. It also allows you to control the environment in which the process is started (user profile, output redirection etc). You can also use the Verb parameter (right click on a file, that list of actions) so that you can, for example, play a wav file.

Details: Executes a program returning the process object of the application. Allows you to control the action on a file (verb mentioned above) and control the environment in which the app is run. You also have the ability to wait on the process to end. You can also subscribe to the processes Exited event.

Example:
 
#starts a process, waits for it to finish and then checks the exit code.
$p = Start-Process ping -ArgumentList "invalidhost" -wait -NoNewWindow -PassThru
$p.HasExited
$p.ExitCode


#to find available Verbs use the following code.
$startExe = new-object System.Diagnostics.ProcessStartInfo -args PowerShell.exe
$startExe.verbs
1 голос
/ 09 июля 2020

Это сработало для меня. Вам нужно процитировать весь список аргументов, а также вставить двойные кавычки, чтобы передать то, что вы хотите, в /v.

start-process -wait SetupStata16.exe -ArgumentList '/s /v"/qb ADDLOCAL=core,StataMP64"'

Выполнение команды в обычном режиме, а затем использование процесса ожидания после может быть более простой альтернативой, если вы ' убедитесь, что есть только один процесс с таким именем:

notepad
wait-process notepad
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...