Search code examples
batch-filecmdvbscriptautomationgroup-policy

How to get Window title of newly spawned process thro' Batch-Vbscript hybrid script?


I am trying to automate the Group Policy editing process as much as possible.

I have the following script to spawn the gpedit.msc process but it's window goes out of focus as soon as it opens:

FINDSTR /E "'VbsCode" %~f0 > %temp%\~temp.vbs
CSCRIPT //NOLOGO %temp%\~temp.vbs
Sub GPEditOptions 'VbsCode
    On Error Resume Next 'VbsCode
    Set WshShell = WScript.CreateObject("WScript.shell") 'VbsCode
    WshShell.Visible = False 'VbsCode
    WshShell.Run "gpedit.msc",0 'VbsCode
    :: WshShell.AppActivate "Local Group Policy Editor" 'VbsCode
End Sub 'VbsCode
GPEditOptions 'VbsCode
:: WScript.Quit 0 'VbsCode

How can I AppActivate the window that has been opened by the newly spawned gpedit.msc process ? Specifically how to know what's the name/title of that window that has been opened ? "Local Group...Editor" doesn't work.


Solution

  • I think I eventually figured out, how to approach this problem. There are different types of processes.

    In this case, I first need to select the Microsoft Management Console window, since it's the parent process which spawns the actual "Local Group Policy Editor" child process.

    So this code does the job of selecting the first Windows Component starting with letter "W" by sending a ton of keys priorly, and yes you do need Administrator elevation for proper selection of options in the gpedit.msc window:

    @echo off
    net file 1>nul 2>nul
    if not '%errorlevel%' == '0' (
        powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >nul 2>&1
        exit /b
    )
    cd /d %1
    
    FINDSTR /E "'VbsCode" %~f0 > %temp%\~temp.vbs
    CSCRIPT //NOLOGO %temp%\~temp.vbs
    Sub GPEditOptions 'VbsCode
        On Error Resume Next 'VbsCode
        Set WshShell = WScript.CreateObject("WScript.shell") 'VbsCode
        WshShell.Visible = False 'VbsCode
        WshShell.Run "gpedit.msc",0 'VbsCode
        WScript.Sleep 500 : WshShell.AppActivate "Microsoft Management Console" 'VbsCode
        WScript.Sleep 500 : WshShell.AppActivate "Local Group Policy Editor" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "% x{TAB}{ENTER}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{ENTER}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{DOWN}{DOWN}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{DOWN}{DOWN}{ENTER}" 'VbsCode
        WScript.Sleep 500 : WshShell.sendKeys "{TAB}{TAB}{TAB}{TAB}{W}" 'VbsCode
    End Sub 'VbsCode
    GPEditOptions 'VbsCode
    WScript.Quit 0 'VbsCode
    

    Hope this helps anyone facing similar issue.