gpt4 book ai didi

powershell - 在powershell中停止然后启动一个进程

转载 作者:行者123 更新时间:2023-11-30 23:52:53 25 4
gpt4 key购买 nike

我想停止/终止某个进程,然后在完成我必须做的事情后重新启动它。

这是我已经拥有的。

Clear-host
$processes = Get-Process devenv
$processes.Count
if($processes.Count -gt 1)
{
$i = 0
Write-host "There are multiple processes for devenv."
foreach($process in $processes)
{
$i++
$i.ToString() + '. ' + $process.MainWindowTitle
}
$in = Read-host "Give a number of the process to kill: "
write-host
write-host "killing and restarting: " + $processes[$in-1].MainWindowTitle
$processes[$in-1].Kill()
$processes[$in-1].WaitForExit()
$processes[$in-1].Start()

}
else
{
write-host "something else"
}

但是 Start 需要一些我认为可以从过程中获得的参数。但我不确定我知道该给它什么。

最佳答案

$processes[$in-1].Start()不管用。您需要捕获要杀死的进程信息并再次启动同一个应用程序。您可以使用 Win32_Process WMI 类获取进程二进制文件和命令行信息。

例如,

Clear-host
$processes = Get-Process notepad
$processes.Count
if($processes.Count -gt 1)
{
$i = 0
Write-host "There are multiple processes for notepad."
foreach($process in $processes)
{
$i++
$i.ToString() + '. ' + $process.MainWindowTitle
}
$in = Read-host "Give a number of the process to kill: "
write-host
write-host "killing and restarting: " + $processes[$in-1].MainWindowTitle

#Get the process details
$procID = $processes[$in-1].Id
$cmdline = (Get-WMIObject Win32_Process -Filter "Handle=$procID").CommandLine
$processes[$in-1].Kill()
$processes[$in-1].WaitForExit()
}

在上面的示例中,我使用 WMI 来获取所选进程的命令行信息。如果这是一个带有一些打开文本文件的记事本进程,该进程的命令行看起来像 "C:\WINDOWS\system32\NOTEPAD.EXE" C:\Users\ravikanth_chaganti\Desktop\debug.log
现在,您需要做的就是:以某种方式调用该命令行(这部分在我编写的示例中不存在)。一个非常直率的方法是:
Start-Process -FilePath $cmdline.Split(' ')[0] -ArgumentList $cmdline.Split(' ')[1]

但是,就您而言,可能没有任何参数列表。

希望这能给你一个想法。其他 PowerShell 专家可能有不同且有效的方法。这只是一个快速的黑客。

关于powershell - 在powershell中停止然后启动一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com