I am trying to write a basic powershell script to log into gmail but have some up against a problem. The code is below. I have commented out some bits to narrow things down.
$url = "http://gmail.com"
$username="myusername"
$password= "123456"
$ie = New-Object -com InternetExplorer.Application
$ie.visible = $true;
$ie.navigate($url);
while ($ie.Busy)
{
Start-Sleep -m 10000;
}
$counter = 0
while (($counter -lt 10) -and ($ie.document -eq $null)) {Start-Sleep 1; $counter++}
$ie.document -eq $null
$ie.Document.getElementByID('email').value=$username
#$ie.Document.getElementByID("Password").value=$password
#$ie.Document.getElementById("signin").Click();
When I run the powershell script, I get the following error.
You cannot call a method on a null-valued expression.
At J:\scripts\gmail.ps1:21 char:1
+ $ie.Document.getElementByID('email').value=$username
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The strange thing is, this was working perfectly fine yesterday and today its not working at all. I am using IE9.
Any help much appreciated.
PowerShell IE9 ComObject has all null properties after navigating to webpage gave me the answer to this. Had to run my script as an administrator due to IE protected mode that was stopping the object from being created. Either turn off IE protected mode or run the script as an administrator to get it working.
I think you made a mistake here:
$ie.Document.getElementByID("Password").value=$password
The ID should be passwd, not password. So replace that line by:
$ie.Document.getElementByID("Passwd").value=$password
Works for me.
Related
Courtesy of this post, the following code auto-logs into a URL using MS IE and works great. The first two lines are the most important here. See below for what happens when I change them. I want to make it clear That I am not a professional web developer. I am only a system administrator forced to hack my way along when it comes to coding.
Working code when PowerShell calls IE:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$username="myname"
$RSAPIN="mypin"
$password="mypassword"
$ie.Navigate("https://www.tibia.com/mmorpg/free-multiplayer-online-role-playing-game.php")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('username')
$usernamefield.value = "$username"
$RSAPINfield = $ie.document.getElementByID('password_input')
$RSAPINfield.value = "$RSAPIN"
$passwordfield = $ie.document.getElementByID('secondary_password_input')
$passwordfield.value = "$password"
Non-working code is shown below; If I change the code to call MS Edge instead, I get a raft of errors and I think it's because PowerShell New-Object doesn't support MS Edge?
$msedge = New-Object -ComObject 'internetExplorer.Application'
$msedge.Visible= $true # Make it visible
$username="myname"
$RSAPIN="mypin"
$password="mypassword"
$msedge.Navigate("https://www.tibia.com/mmorpg/free-multiplayer-online-role-playing-game.php")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $msedge.document.getElementByID('username')
$usernamefield.value = "$username"
$RSAPINfield = $msedge.document.getElementByID('password_input')
$RSAPINfield.value = "$RSAPIN"
$passwordfield = $msedge.document.getElementByID('secondary_password_input')
$passwordfield.value = "$password"
Errors seen when calling MS Edge instead of IE:
New-Object : Retrieving the COM class factory for component with CLSID
{00000000-0000-0000-0000-000000000000} failed due to the following
error: 80040154 Class not registered (Exception from HRESULT:
0x80040154 (REGDB_E_CLASSNOTREG)). At
C:\Scripts\msedge.ps1:3
char:11
$msedge = New-Object -ComObject 'msedge.Application'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Visible' cannot be found on this object. Verify that the
property exists and can be set. At
C:\Scripts\msedge.ps1:4
char:1
$msedge.Visible= $true # Make it visible
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\Scripts\msedge.ps1:8
char:1
$msedge.Navigate("myurl")
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\Scripts\msedge.ps1:12
char:1
$usernamefield = $msedge.document.getElementByID('username')
I am at a loss here. According to this post, PowerShell New-Object only supports IE's COM Automation.
You can't automate the Edge Chromium browser like what you do with IE using PowerShell script. The COM automation interface are for IE, so it doesn't work with Edge. Besides, Edge doesn't have such interface.
It's recommended to use Selenium WebDriver to automate Edge. Selenium web driver supports many developing languages, you can choose the desired language.
You can also refer to the official doc of Selenium to learn how to get start with Selenium and refer to the code sample of different languages.
I want to use powershell to automate a web download request. But I got some errors that I can't fix.
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.visible = $true
$ie.Navigate("http://10.8.140.232/KPIReport/Admin/Login.aspx")
$usr_name = $ie.document.getElementById('TextBoxAccount')
$pwd = $ie.document.getElementById('TextBoxPassword')
$login_button = $ie.document.getElementById('ButtonLogin')
the first 3 lines can run successfully.
but from line 4, error occurs.
You cannot call a method on a null-valued expression.
At line:4 char:1
+ $usr_name = $ie.document.getElementById("TextBoxAccount")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And $ie.document return null in command line.
and by the way. all the element id are existed in source html code.
I don't what happens here.
thanks for your help.
As the comment above, the error is caused by the DOM hasn't been fully loaded. I use While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;} after $ie.Navigate. You could try to add it in your code.
I'm practicing using PowerShell, and today I thought I'd write a script that logs me into a website. I have no use for this specific example, but I thought it would be good practice. I created it while referencing this. Here is what I have so far.
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.Visible = $true
$username = "my#email"
$password = "password"
$ie.Navigate("https://squirrel.ws/login")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernameField = $ie.Document.getElementByID('UserEmail')
$usernameField.value = $username
$passwordField = $ie.Document.getElementByID('UserPassword')
$passwordField.value = $password
$link = $ie.Document.getElementByID('$0')
$link.click()
$ie.Quit()
When I run this, an IE window appears, and almost immediately closes with this error:
Method invocation failed because [System.DBNull] does not contain a method named 'click'.
At J:\removingForPrivacy\test.ps1 char:1
+ $link.click()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
So I'm pretty sure it throws an error either when trying to click, or because I labeled the button incorrectly, or both. When trying to create this, I couldn't find an ID for the button so I used what I could find. Otherwise I'm not sure why click() doesn't exist when it's in all the examples I'm seeing. Can anybody help me?
My issue came from the fact that when creating $Link, that I was using the wrong tags. I used all the same code, but swapped out the $Link creating line for:
$Link=$ie.Document.getElementsByTagName("button") | where-object {$_.type -eq "submit"}
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("********Please Select the SOURCE Directory********",0,"Directory Selecter 5000",0x1)
Function Get-Folder($initialDirectory)
{
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
if($foldername.ShowDialog() -eq "OK")
{
$folder += $foldername.SelectedPath
}
return $folder
}
$a = Get-Folder
$wshellb = New-Object -ComObject Wscript.Shell
$wshellb.Popup("********Please Select the DESTINATION Directory********",0,"Directory Selecter 5000",0x1)
Function Get-Folder($initialDirectory)
{
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
if($foldername.ShowDialog() -eq "OK")
{
$folder += $foldername.SelectedPath
}
return $folder
}
$b = Get-Folder
Set-Content -Path "C:\script\scripts\script data.txt" -Value "$a" -Force
Set-Content -Path "C:\script\scripts\script data2.txt" -Value "$b" -Force
So this script works in ISE and if I copy/paste it into a CLI and that's it. If I navigate to the folder in the powershell CLI and run it from there it gives me this error:
New-Object : Cannot find type
[System.Windows.Forms.FolderBrowserDialog]: verify that the assembly
containing this type is loaded. At
C:\script\scripts\pathingworking.ps1:8 char:19
+ $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'rootfolder' cannot be found on this object. Verify that
the property exists and can be set. At
C:\script\scripts\pathingworking.ps1:9 char:5
+ $foldername.rootfolder = "MyComputer"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression. At
C:\script\scripts\pathingworking.ps1:11 char:8
+ if($foldername.ShowDialog() -eq "OK")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This error comes back twice, once for each instance of the folder selection window that is supposed to pop up.
I have tried -STA from run dialogue, shortcuts, and even from the CLI and it always gives me that error. I have verified using [System.Threading.Thread]::CurrentThread.GetApartmentState() that the open instance of powershell is STA. I can open a powershell CLI and navigate to the folder where the script is, invoke the script, it will give me the error, then I can copy\paste it in the same exact CLI and it works without issue. I have also right-clicked the file in Explorer and selected "run with powershell" and it also gives me the error. I have elevated the CLI to see if that helped with no success.
I fear this is some small oversight and hopefully someone can give me a hand.
using v1.0
windows 10
Cannot find type [System.Windows.Forms.FolderBrowserDialog] is due to the assembly not being loaded.
load the assembly with
Add-Type -AssemblyName "System.Windows.Forms"
rerun's answer solves the errors, but doesn't do a whole lot of explaining. Designing a script in the ISE (which is what I do almost exclusively) is convenient because it will automatically load types and modules for you. If you plan on running the script from another CLI (Command Line Interpreter) you should make it a habit of explicitly loading needed modules and assemblies early on in the script, so that when those things are called upon later PowerShell will know what you're asking for.
Unfortunately there's no easy way to tell what you will need to do that for when it comes to what types are going to be inherently available, but a little trial and error usually points it out rather quickly, or if you look at your script and see that you are making a new object with System.Kitchen.Pasta, then you probably need to load the assembly for System.Kitchen first, so that it has the Pasta type available when you want it, so you could just include a call to load that assembly near the top of the script with no harm done.
In your specific case, as has already been pointed out, you will need to load the assembly that contains the FolderBrowserDialog box that you want to display. Adding the following as the first line of your script will resolve the errors that you are seeing:
Add-Type -AssemblyName "System.Windows.Forms"
i have the following code
its to mass enable External Sharing on SPO and OD users
Connect-SPOService -Url https://######-admin.sharepoint.com
$currentSiteCollection = (Get-Content "siteCollectionsEnabled.txt")
$collectionCount = $currentSiteCollection.Count
if ($currentSiteCollection){
foreach ($currentSite in $currentSiteCollection)
{
Clear-Host
Write-Output "Enabling " $currentSite.ToString() $collectionCount.ToString() " sites left"
Set-SPOSite -Identity $currentSite -SharingCapability ExternalUserSharingOnly
Add-Content ODFBSiteSharingEnabled.log $currentSite.ToString()
$collectionCount = $collectionCount - 1
}
}
but when running i get this
8741
sites left
Set-SPOSite : No connection available. Use Connect-SPOService before running this CmdLet.
At C:###\siteCollectionsDisabledEnable\siteEnable.ps1:10 char:9
+ Set-SPOSite -Identity $currentSite -SharingCapability ExternalUserSharin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-SPOSite], InvalidOperationException
some help here?
Are you able to run Connect-SPOService cmdlet on its own? Do you get any error?
If it works fine and you are able to sign in, then remove the first line of your script here and execute the rest of it.