How to automatically clear application pop-up windows

I came across a situation where one of my applications was throwing a pop-up and expect someone to click ‘OK’ or ‘Cancel’ to proceed. This was impacting some automated functions of the application as the process was getting stopped with the pop-up. It is highly inconvenient for anyone to clear those pop-ups manually. I had to find some Windows native solution to tackle this situation.

I could not find any PowerShell cmdlet for this situation but I found the old Application.SendKeys VBA method still useful. I created a simple PowerShell script and ran this in a regular interval to handle those pop-ups.

Let’s assume MS Excel as the application here and you are running a macro. The macro throws some pop-ups and won’t proceed unless you clear them. Sounds old technique? But I think it still has several use cases.

So, here is a model script that can be used to automatically clear those pop-up windows. You have to notice the title of the popup window as you have to use that in the script. You can also send any key stroke or a combination of Key strokes as per your requirement by following the SendKeys code.

#region: Variables
$date = Get-Date -Format d
$time = Get-Date -Format t
$logPath = 'C:\temp'
$logFile = $logPath + '\popup_cleaner' + $date + '.log'
$popupName = '<put the tile of the popup window>'
#endregion
#region: Clean up old log files
#Clean up log files older than 30 days
$days = "-30"
$currentDate = Get-Date
$deleteTillDate = $currentDate.AddDays($days)
Get-ChildItem $logPath | Where-Object { $_.LastWriteTime -lt $deleteTillDate } | Remove-Item
#endregion
#region: Popup cleanup
$popup = New-Object -ComObject wscript.shell
if ($popup.AppActivate($popupName)) {
Start-Sleep -Seconds 5
$popup.SendKeys('{Enter}')
Write-Output "$time Popup has been cleaned up" >> $logFile
}
else {
Write-Output "$time No popup is found" >> $logFile
}
#endregion

This script is suitable for desktop application as the SendKeys method interacts with the desktop and sends the Key commands. The script must be scheduled by selecting ‘Run only when user is logged on’ option. This technique does not work on a disconnected or locked RDP session because the desktop is not available when session is disconnected or locked. However, there are some tweaks that can help achieve similar solution on a server. As those are not secure approaches, it is not recommended to go to that route.

Thanks for reading, give it a 👏 if you like it. Please leave a comment and let me know if you have any feedback.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store