How to switch to second window of a running app with applescript?

I do not have Microsoft Teams, so I cannot test the example AppleScript code show below, however it works on the other applications I tested it on.

Based on the screenshot in the OP, assuming you want to actuate the menu of a Dock Tile and click a menu item, then here is a way to do it.

Example AppleScript code:

tell application "System Events"
    tell UI element "Microsoft Teams" of list 1 of application process "Dock"
        perform action "AXShowMenu"
        delay 0.1
        click menu item 2 of menu 1
    end tell
end tell

Notes:

The example AppleScript code uses UI Scripting and can be kludgy and is dependent on allowing the script to complete before performing any other actions manually.


Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.


ALTERNATIVE SOLUTION via app menu

Since MS Teams lists the windows in the "Window" menu and it's always the last one in the list as far I know i managed to use the below which is much quicker and doesn't show any menu popups, sweet.

Adding the solution here as initially I didn't ask for a solution specific to the dock menu but rather how to trigger the second window of a running app and this solution is better.

EDIT: Turns out I also need set frontmost to true since the second window was successfully moved forward but the last active app staid still in front and prevented hotkeys to trigger in the second window.

enter image description here

tell application "System Events" to tell application process "Microsoft Teams"
    click (last menu item of menu 1 of menu bar item "Window" of menu bar 1)
    set frontmost to true
end tell