【问题标题】:.NET - Can you change a process's parameters after process start?.NET - 你可以在进程启动后更改进程的参数吗?
【发布时间】:2017-06-05 19:08:15
【问题描述】:

最终目标是更改 PowerShell.exe 的进程参数,将 EnableRaisingEvents 设置为 $true,以便在脚本终止时捕获退出事件。

我能找到的所有示例都是先在新进程对象上设置属性,然后使用 start 方法编程生成它,但我想知道是否可以修改现有进程来完成此操作? ...像内联更新?

如果在 .NET 中可行,那很简单,但如果我需要使用 p/invoke 下拉到 WinAPI,如果有人知道库/函数,我也可以弄清楚。谢谢。

【问题讨论】:

  • 答案为您的问题提供了解决方案,而不是您的问题的答案。这主要是因为您没有询问您需要什么,而是询问您提出的解决方案。这是对问题投反对票的正当理由。

标签: .net powershell winapi


【解决方案1】:

EnableRaisingEventsSystem.Diagnostics.Process实例的属性,不是实际的底层操作系统进程,不管底层进程是否已经运行,你都可以轻松修改:

$process = Start-Process notepad -PassThru

# Change EnableRaisingEvents flag after process start
$process.EnableRaisingEvents = $true

# Now the Process instance can raise the Exited event
Register-ObjectEvent -InputObject $process -EventName Exited -SourceIdentifier notepadExited -Action {
    Write-Host "Notepad exited" -ForegroundColor Red
}
$process.Kill()

如果你需要监控一个已经运行但不是你自己启动的进程,你可以使用Win32_ProcessStopTraceWMI事件类:

# Using Start-Process for this example, but could be any existing process
$process = Start-Process notepad -PassThru

# Use the query to filter events raised based on process ID
$eventQuery = "SELECT ProcessName,ExitStatus FROM Win32_ProcessStopTrace WHERE ProcessId = $($process.Id)"

# Register WMI Event listener
Register-WmiEvent -Query $eventQuery -Action {
    $traceEvent = $Event.SourceEventArgs.NewEvent
    Write-Host "$($traceEvent.ProcessName) exited with status code: $($traceEvent.ExitStatus)"
} -SourceIdentifier notepadExited
$process.Kill()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2015-09-20
    相关资源
    最近更新 更多