问题
Related: Powershell: Download or Save source code for whole ie page
The input fields I need to programmatically drive do not have an ID, so I'm trying to set them with the form name instead.
In the IE F12 developer console, this command works:
document.forms["loginForm"].elements["_ssoUser"].value = "someone's username"
But in PowerShell, this command fails:
$ie.document.forms["loginForm"].elements["_ssoUser"].value = "$username"
The error is "cannot index into a null array".

回答1:
You may be over complicating this. Last couple times I've needed to login to a web site with a script I didn't bother with the document.forms, I just got the document elements. Try this instead:
$Doc = $IE.Document
$UserNameField = $Doc.getElementById('_ssoUser')
$UserNameField.value = "$username"
$PassField = $Doc.getElementById('_ssoPassword')
$PassField.value = "$Password"
$LoginButton = $Doc.getElementById('LoginBtn')
$LoginButton.setActive()
$LoginButton.click()
Yeah, it's probably a bit longer than needed, but it's easy to follow and edit as needed, and it's always worked for me in the past. You will need to edit some element names probably (I guessed names for the password field element, and the login button element, so please check them).
回答2:
It can happen that you don't find the ID but you can use the tag name instead. I used the MIT website to show you an example of how can this be done.
# setup
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$ie.navigate("http://web.mit.edu/")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$termsField = $ie.document.getElementsByName("terms")
@($termsField)[0].value ="powershell"
$submitButton = $ie.document.getElementsByTagName("input")
Foreach($element in $submitButton )
{
#look for this field by value this is the field(look for screenshot below)
if($element.value -eq "Search"){
Write-Host $element.click()
}
}
Start-Sleep 10

回答3:
Most likely a form in an IFRAME so get the IFRAME by id then the form by ID then select the child object by the name like: (sim. for password field and login button).
($ie.document.getElementbyID("content").contentWindow.document.getElementbyID('loginForm') | Where-Object {$_.name -eq "_ssoUser"}).value = "username"
来源:https://stackoverflow.com/questions/28816216/powershell-programmatically-set-input-field-by-name-in-ie