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

标签 powershell

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

这是我已经拥有的。

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/

相关文章:

系统管理员的 Powershell URI 构建器

azure - 如何使用powershell获取所有Azure订阅和资源的列表(以特定格式)

javascript - 使用 Windows PowerShell 传递 Node.js 环境变量

powershell - 如何将参数类型转换为不同的对象类型

azure - 启动 Azure VM 指定时间

powershell - 通过PowerShell安装exe时可以替代时间延迟吗?

powershell - Powershell-输出目录递归到控制台和文件

powershell - 有没有办法让 Powershell 5 的 Get-Help 解析当前脚本?

powershell - 下载txt文件中的每个对象

powershell - 使用公钥对密码字符串进行加密和编码