You cannot call a method on a null-valued expression. + $submitButton.click() - powershell

I'm running a script that I've used for some time successfully, but I am now getting the following error message:
You cannot call a method on a null-valued expression. At
G:\Backup\2021\DownloadASX300 v1.ps1:14 char:1
$submitButton.click()
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
The script I'm running is as follows:
$OutputFilePath = "c:\_Temp\ASX300html.htm
$url = 'https://www.marketindex.com.au/asx300'
$IE = New-Object -ComObject InternetExplorer.Application
$IE.Navigate($url)
$IE.Visible = $true
while ($IE.Busy -eq $true){Start-Sleep -seconds 5;}
$submitButton=$IE.Document.IHTMLDocument3_getelementsbytagname("a") | Where-Object {$_.innerhtml -like '*SHOW ALL COMPANIES*'}
$submitButton -eq $null
$submitButton.click()
Start-Sleep -s 5
$IE.Document.body.innerHTML | Out-File -FilePath $OutputFilePath
$IE.Quit()
This script basically downloads share prices from a website after opening the full list on that site.
Any help you can offer will be greatly apprreciated.

Related

How to download multiple files via PowerShell script?

I have multiple files to download, as many as 7 at a time, it downloads the first file then peters out.
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:17 char:5
$IE.Navigate2("https://mdf.mydomain.com/SeaNet//DownloadFile ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], COMException
FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
$BinaryID = 7458,7457,7446,7317
# open IE
$IE = New-Object -COMObject "InternetExplorer.Application"
$IE.Visible = $True
$MyUser = ""
$MyCreds = Get-Credential -Credential $MyUser
$MyPass = $Creds.GetNetworkCredential().Password
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/CustomReport.aspx?reportId=692")
While($IE.Busy -eq $true) {Start-Sleep -Seconds 30}
$IE.document.getElementById('UserNameTB').value = "$MyUser"
$IE.document.getElementById('PasswordTB').value = "$MyPass"
$Link = $IE.Document.getElementByID('LoginIBtn')[0].Item().Click()
ForEach ($ID in $BinaryID) {
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/DownloadFile.aspx?binaryid=$ID")
Pause
}

You cannot call a method on a null-valued expression in PowerShell using another credentials

Well, i'm trying to execute a script with another credentials and i got the next error:
You cannot call a method on a null-valued expression.
At C:\Automation\SoftwareInstallation\runas_test\whoami_test.ps1:10 char:1
+ Write-Host $result.StandardOutput.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This is my code:
$username = 'idb\frida_automation_scc'
$pass = Get-Content -Path C:\Automation\SoftwareInstallation\runas_test\settings.txt -Raw
$password = ConvertTo-SecureString $pass -AsPlainText -Force
$MyCredential=New-Object -TypeName PSCredential -ArgumentList $username, $password
$result=Start-Process -NoNewWindow powershell.exe -ArgumentList "-file C:\Automation\SoftwareInstallation\runas_test\whoami_test2.ps1" -Credential $MyCredential -PassThru -RedirectStandardOutput test1.txt
Write-Host $result.StandardOutput.ReadToEnd()
And this is the another command:
$result= whoami
Write-Host $result
return $result
I donĀ“t know why this error happens if the command are well written and the script brought back the value in a .txt file.

Why OpenSubKey() method returns null when I try to access to a registry key in Powershell?

I'm trying to make a script that returns the default printer of a list of remote pc, by reading the registry key Device under the path Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows.
The problem in my code seems to be in the method OpenSubKey which returns null so the method GetValue fails.
The path of the registry key should be correct.
$Workstations=Import-Csv -Path C:\Users\mmarinari\Downloads\pclist2.csv -Header "PcName"
Remove-job *
foreach($workstation in $Workstations) {
Out-File -FilePath $logpath -InputObject $workstation.PcName -Append
Write-Output $workstation.PcName
$Reg=$null
$remotereg=Get-Service -ComputerName $workstation.PcName -Name RemoteRegistry
if($remotereg.Status -ne "Running"){
Get-Service -ComputerName $workstation.PcName -Name RemoteRegistry | Set-Service -StartupType Manual -PassThru| Start-Service
Write-Output "Service Started"
}
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser', $workstation.PcName)
If($Reg -eq $null){
Write-Output "Reg is null"
}
else{
$RegKey= $Reg.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows")
$DefaultPrinter = $RegKey.GetValue("Device")
Write-Output $DefaultPrinter
$RegKey.Dispose()
}
$Reg.Dispose()
}
The error that I get is the following:
You cannot call a method on a null-valued expression.
At C:\Users\mmwa\Documents\ProgrammiVS\find_default_printer.ps1:28 char:13
+ $DefaultPrinter = $RegKey.GetValue("Device")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
EDIT: I've added the Dispose method for Reg and RegKey and the $reg= $null instruction but that don't solve the problem, the error already occurs in the first iteration.

New-Object fails on PowerShell 2 with Constructor not found error

I have the below script running fine on PowerShell 5
$NetworkChange = New-Object System.Net.NetworkInformation.networkchange
Register-ObjectEvent -InputObject $NetworkChange -EventName NetworkAddressChanged -SourceIdentifier "NetworkChanged" -Action {
Write-Host "network switched"
$LanConnected=#(Get-WmiObject win32_networkadapter -filter "netconnectionstatus = 2" | Where-Object {$_.netconnectionid -like "*Local Area Connection*"})
If($LanConnected){
Get-WmiObject win32_networkadapter -filter "netconnectionstatus = 2" | Where-Object {$_.netconnectionid -like "*Wireless Network Connection*"} | ForEach-Object {$_.disable()}
}
Else {
Get-WmiObject win32_networkadapter | Where-Object {$_.netconnectionid -like "*Wireless Network Connection*"} | ForEach-Object {$_.enable()}
}
}
However it fails on PowerShell 2 with the below error related to the New-Object cmdlet
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Net.NetworkInformation.networkchange.
At line:1 char:11
+ New-Object <<<< System.Net.NetworkInformation.networkchange
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
Any idea why it fails? Is there a different syntax for the New-Object cmdlet on PowerShell 2?
Note: Our estate is still on PowerShell 2 hence this struggle.
Thanks in advance
Steve
In PS5 works this code:
$NetworkChange = [System.Net.NetworkInformation.NetworkChange]::new()
PS2 says [System.Net.NetworkInformation.NetworkChange] doesn't contain a method named 'new'. So we can go around it by creating a variable 'classic' way:
New-Variable -Name NetworkChange -Value ([System.Net.NetworkInformation.NetworkChange])
$NetworkChange

ProcessStartInfo and Process in PowerShell - Authentication Error

I have code that uses ProcessStartInfo and Process to invoke another script, and to return the output of that script.
Unfortunately, I am getting errors, and I am unsure how to troubleshoot them.
#script1.ps1
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\script2.ps1", $abc
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "DOMAIN\Username"
$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
# $standardOut should contain the results of "C:\script\script2.ps1"
$standardOut
The errors I get are:
Exception calling "Start" with "0" argument(s): "Logon failure: unknown user name or bad password"
At C:\script\script1.ps1:46 char:15
+ $process.Start <<<< () | Out-Null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At C:\script\script1.ps1:47 char:49
+ $standardOut = $process.StandardOutput.ReadToEnd <<<< ()
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script1.ps1:48 char:21
+ $process.WaitForExit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How can I fix this problem?
It's pretty much spelled out to you, isn't it?:
"Logon failure: unknown user name or bad password"
(first error line).
Note that DOMAIN should be provided in separate property:
$startInfo.Username = "Username"
$startInfo.Domain = "DOMAIN"