我正在尝试创建一个弹出窗口,该窗口在脚本完成之前一直保持打开状态。
我有以下代码来创建一个弹出框
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Operation Completed",0,"Done",0x1)
$wshell.quit
我认为 $wshell.quit 会关闭窗口,但事实并非如此。有没有办法在没有用户交互的情况下从脚本中关闭此对话框?
最佳答案
$wsheel.quit
的使用在这里不起作用,因为在 PowerShell 中,当您执行 $wshell.Popup(..)
时, session 将等到表单已关闭。
在窗口关闭之前,您将无法运行任何其他命令。
你可以做的是在不同的 session 中创建弹出窗口,这样你就可以运行你的代码,当你的代码完成时,搜索作业并将其终止。
解决方案#1:
function killJobAndItChilds($jobPid){
$childs = Get-WmiObject win32_process | where {$_.ParentProcessId -eq $jobPid}
foreach($child in $childs){
kill $child.ProcessId
}
}
function Kill-PopUp($parentPid){
killJobAndItChilds $parentPid
Get-Job | Stop-Job
Get-Job | Remove-Job
}
function Execute-PopUp(){
$popupTitle = "Done"
$popupScriptBlock = {
param([string]$title)
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Operation Completed",0,$title,0x1)
}
$job = Start-Job -ScriptBlock $popupScriptBlock -ArgumentList $popupTitle
# Waiting till the popup will be up.
# Can cause bugs if you have other window with the same title, so beaware for the title to be unique
Do{
$windowsTitle = Get-Process | where {$_.mainWindowTitle -eq $popupTitle }
}while($windowsTitle -eq $null)
}
Execute-PopUp
#[YOUR SCRIPT STARTS HERE]
Write-Host "Your code"
Start-Sleep 3
#[YOUR SCRIPT ENDs HERE]
Kill-PopUp $pid
它会创建你的弹出窗口,只有当窗口打开时(通过标题验证。请注意,如果有另一个进程具有相同的窗口标题,它可能会导致冲突)你的代码才会开始运行。
当您的代码完成时,它将终止工作。
请注意,我没有使用 Stop-Job 来停止作业。
我猜是因为当作业创建弹出窗口时,它无法接收任何命令,直到弹出窗口关闭。
为了克服它,我终止了工作的进程。
解决方案#2(使用事件):
function Kill-PopUp(){
kill (Get-Event -SourceIdentifier ChildPID).Messagedata
Get-Job | Stop-Job
Get-Job | Remove-Job
}
function Execute-PopUp(){
$popupTitle = "Done"
$popupScriptBlock = {
param([string]$title)
Register-EngineEvent -SourceIdentifier ChildPID -Forward
New-Event -SourceIdentifier ChildPID -MessageData $pid > $null
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Operation Completed",0,$title,0x1)
}
$job = Start-Job -ScriptBlock $popupScriptBlock -ArgumentList $popupTitle
# Waiting till the popup will be up.
# Can cause bugs if you have other window with the same title, so beaware for the title to be unique
Do{
$windowsTitle = Get-Process | where {$_.mainWindowTitle -eq $popupTitle }
}while($windowsTitle -eq $null)
}
Execute-PopUp
#[YOUR SCRIPT STARTS HERE]
Write-Host "Your code"
Start-Sleep 3
#[YOUR SCRIPT ENDs HERE]
Kill-PopUp
关于Powershell关闭弹框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46370513/