Need Help in PS script(login to a website, search for a string and click)


I am using the bleow script to auto login to a website and then search for a string, click on that string.
Issue: I am able to autologin to the website but after login, the code for : Search for string and click is not working. If the keep the current opened webpage and run the script again then on the second/new page its running fine (i mean searching the string and clicking on it). But first time its not working, please let me know if i miss anything here.

Create an Internet Explorer object

$ie = New-Object -ComObject ‘internetExplorer.Application’
$ie.Visible= $true # Make it visible

Open website


Script to wait till webpage is downloaded into the browsers.

while ($ie.Busy -eq $true){Start-Sleep -seconds 4;}

Feed in your credentials to the input fields on the web page

$usernamefield = $ie.Document.getElementByID(‘j_username’)
$usernamefield.value = ‘usrname’
$passwordfield = $ie.Document.getElementByID(‘j_password’)
$passwordfield.value = ‘psswd’
$submitButton = $ie.document.getElementById(“loginData”).submit()
#{Start-Sleep -seconds 20;}

search for Servers in the opened webpage and click on it — This is not working for the first time, if i keep the first session opened and run the PS1 file again then in the newly opened browser (2nd session) its clicking the servers. But for the first time its not workingv

$link = $ie.Document.getElementsByTagName(‘a’) | where-object {$.innerText -eq ‘Servers’}|ForEach-Object { $.Click() }
{Start-Sleep -seconds 20;}

Please close this, it got fixed now.