如何在 PowerShell 中重新启动批处理文件?

问题描述 投票:0回答:1

这是我尝试过的:

Get-Process | Where-Object {$_.Path -eq "C:\path\stream1.bat"} | Stop-Process -Force

Start-Sleep -Seconds 5

Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"C:\path\stream1.bat`""

Start-Process
命令运行良好,但是
Stop-Process
命令没有执行任何操作。

windows powershell cmd server scripting
1个回答
0
投票

当前代码的一个问题是

.Path
(实际上这个属性是
.MainModule.FileName
将是
cmd.exe
的路径而不是
.bat
文件本身。在这种情况下,您可以做的是查询
Win32_Process
并按
CommandLine
属性
进行过滤,其中包含您的
.bat
的路径。这解决了问题之一。

下一个问题是找到

.bat
文件可能启动的所有子进程,这些子进程需要先终止,然后再终止
cmd.exe
本身。为此,您可以再次查询
Win32_Process
以查找
ParentProcessId
等于您的
cmd.exe
进程的进程 ID 的所有进程。

$bat = 'C:\path\stream1.bat'
# WQL requires escaping of `\`
$cmdline = $bat.Replace('\', '\\')
# Find the cmd process having ending with the specific cmdline
$proc = Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe' AND CommandLine LIKE '%$cmdline%'"
$getCimInstanceSplat = @{
    Filter    = "ParentProcessId = '$($proc.ProcessId)' OR ProcessId = '$($proc.ProcessId)'"
    ClassName = 'Win32_Process'
}

# Find all processes started by that bat file as well as the cmd process itself
Get-CimInstance @getCimInstanceSplat |
    # and terminate all of them
    Invoke-CimMethod -MethodName Terminate
© www.soinside.com 2019 - 2024. All rights reserved.