Handling a popup box using powershell

20,654

Solution 1

With Powershell v2 you can use PInvoke to access the normal Win32 API, thus giving you access to FindWindow and SetForegroundWindow. Then use SendKeys to send a Enter key.

Something like this to register the methods:

$pinvokes = @'
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr FindWindow(string className, string windowName);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
'@

Add-Type -AssemblyName System.Windows.Forms
Add-Type -MemberDefinition $pinvokes -Name NativeMethods -Namespace MyUtils

Now you can find the window you need:

$hwnd = [MyUtils.NativeMethods]::FindWindow(null, "Popupboxname")

Give it focus:

[MyUtils.NativeMethods]::SetForegroundWindow($hwnd)

And send the Enter key:

[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

Sources/inspiration:

Solution 2

Try something like this:

$wshell = New-Object -ComObject wscript.shell; 
$wshell.AppActivate('Vector RP1210 API Setup') 
Sleep 1 
$wshell.SendKeys('%C')
$wshell.AppActivate('Vector RP1210 API') 
Sleep 1 
$wshell.SendKeys('{ENTER}')
Share:
20,654
Deepak Narayan
Author by

Deepak Narayan

Updated on September 24, 2020

Comments

  • Deepak Narayan
    Deepak Narayan almost 4 years

    Can anyone please tell me how to click on "ok" or "cancel" on a popup window using powershell? I am trying to automate a website using powershell, but I am new to powershell. I have to click on OK button in a popup box to proceed. I know VBscript, in that I can use

    set obj0 = createobject("wscript.shell")
    count = 0
    do while count = 0
    if obj0.appactivate "Popupboxname" then
    ----perform required action---
    count = 1
    else
    wscript.sleep(2000)
    end if
    loop
    

    Can anyone tell me how to do the same in powershell? If i can somehow access the popup window, atleast i can use sendkeys command to send the enter key. Please let me know how to handle the popup window. Thanks in advance.