powershell - 如何在不停止进程的情况下正确关闭记事本++窗口?
问题描述
我想正确关闭记事本++的窗口,但它不起作用。请问有什么解决方案?
这是我的代码:
$pathcoalaclient="C:\Program Files\Notepad++\notepad++.exe"
$process=Start-Process -FilePath $pathcoalaclient -Verb RunAs -PassThru
Start-Sleep -s 5
$process.CloseMainWindow()
这是我的输出:
True
解决方案
不幸的是,返回的事实并不能保证窗口实际关闭并且目标进程退出- 它只是告诉您
.CloseMainWindow()
$true
请求关闭的 Windows 消息是否已成功发送。实际上,在您的情况下,窗口不会关闭,因为您已
Notpad++.exe
在提升的会话()中启动。看起来,大概与权限有关,然后是无效的。Start-Process
-Verb RunAs
.CloseMainWindow()
- 但是,如果可以接受,考虑到数据丢失的风险- 您可以回退到以
Stop-Process
终止(强制终止)该过程。
- 但是,如果可以接受,考虑到数据丢失的风险- 您可以回退到以
一个工作示例:
# Note: I'm using Notepad.exe for simplicity here.
$pathcoalaclient = "Notepad.exe"
$process = Start-Process -FilePath $pathcoalaclient -Verb RunAs -PassThru
Start-Sleep -Seconds 5
# Call .CloseMainWindow() but note that return value $true
# isn't a reliable indicator for whether the window actually closed.
# NOTE: If you KNOW that the process was created WITH ELEVATION
# - as in this case - you can skip this call altogether.
$requestSuccessfullySent = $process.CloseMainWindow()
if ($requestSuccessfullySent) {
# The process may or may not exit.
# Wait a reasonable amount of time to see if it does.
# Note: If the request to close couldn't even be sent - this could be
# due to application hanging, currently showing a *modal* dialog,
# or being in the process of / already having exited -
# there is no strict need to wait, although you still may choose to,
# in order to minimize the risk of data loss.
$process | Wait-Process -Timeout 3 -ErrorAction Ignore
}
# Take additional action, if the process did *not* exit.
if (-not $process.HasExited) {
Write-Warning "The $($process.Name) process did not exit on its own within the timeout period."
# !! IF it is acceptable,
# !! you can *kill* the process now, but note that this can
# !! result in *data loss*
Write-Warning "Killing the $($process.Name) process..."
$process | Stop-Process -Force
}
请注意,无条件终止,即它总是强制终止进程,有数据丢失的风险。至少在未来(PowerShell 7.2 后)可能提供优雅终止是GitHub 问题 #13664的主题。Stop-Process
推荐阅读
- reactjs - withFormik如何在handleSubmit中访问包装表单的道具
- javascript - 当父元素是 contentEditable 时,是否可以防止子元素被删除?
- python - 第二次调用一个函数,只有轻微的变化
- python - Python Tkinter filedialog 保存和打开问题(不打开,不让选择名称保存)
- javascript - 如何以递归方式获取树路径?
- firebase - 如何在 Firebase 中创建没有电子邮件的用户?
- php - Shell 响应中的字符串搜索
- android - android从gson获取内部列表参数时遇到问题
- javascript - 如何理解错误“TypeError:无法读取未定义的属性'id'”?
- javascript - mongodb findOneAndUpdate 只获取更新的字段