Powershell - Internet Explorer - Get document for a newly opened tab - windows

I am trying to figure out how to login to web-pages in Internet Explorer 9 using PowerShell version 2 on Windows 7 x64. When I run these lines one by one in PowerShell, I get exactly what I want - The page opens and I am able to login.
$internet_explorer = new-object -com "InternetExplorer.Application"
$internet_explorer.visible = $true
$internet_explorer.navigate2("https://abcd.efgh.com/ijkl/Login.jsp")
$this_document = $internet_explorer.document
$username_field = $this_document.getElementByID("usernameField")
$password_field = $this_document.getElementByID("passwordField")
$login_button = $this_document.getElementByID("SubmitButton")
$username_field.value = "username"
$password_field.value = "password"
$login_button.click()
But when I try to open another tab and try to login to the new webpage by executing the below lines one-by-one,
$internet_explorer.navigate2("https://mnop.qrst.com/uvwx/Login.jsp", 0x0800)
$this_document = $internet_explorer.document
$username_field = $this_document.getElementByID("usernameField")
$password_field = $this_document.getElementByID("passwordField")
$login_button = $this_document.getElementByID("SubmitButton")
$username_field.value = "username"
$password_field.value = "password"
$login_button.click()
I get the following errors :
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:17
+ $username_field. <<<< value = "username"
+ CategoryInfo : InvalidOperation: (value:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:17
+ $password_field. <<<< value = "password"
+ CategoryInfo : InvalidOperation: (value:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At line:1 char:20
+ $login_button.click <<<< ()
+ CategoryInfo : InvalidOperation: (click:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
So when I open a new tab, how can I get Document of that newly opened tab? Please help me solve this
EDIT : Alternative methods will do. Please feel free to suggest any other way to login to multiple web pages automatically (like what was attempted above) if they exist

From the documentation for the Navigate method, it would appear that the new tab is not available for automation:
When navOpenInNewWindow or navOpenInNewTab is specified, the caller does not receive a pointer to the IWebBrowser2 interface for the new window, so there is no immediate way to manipulate it.

Related

Powershell Force Maximize / Reopen if close

Working on a Kiosk Windows tablet, was working before I started to optimize. I had used a Windows Debloating tool to remove all the unnecessary items on the tablets. But I believe it removed something I was calling on in the script. Just looking to see if anyone has any idea what I would need to reinstall. Or if I should start over on the Image
Here is the Powershell script
Add-Type -AssemblyName UIAutomationClient
$MyProcess = Get-Process | where { $_.MainWindowTitle -like "Kiosk*" }
while (1 -eq 1) {
if ($null -ne $MyProcess) {
# if Minimized make it Normal
$ae = [System.Windows.Automation.AutomationElement]::FromHandle($MyProcess.MainWindowHandle)
$wp = $ae.GetCurrentPattern([System.Windows.Automation.WindowPatternIdentifiers]::Pattern)
if ($wp.Current.WindowVisualState -eq 'Minimized') {
$wp.SetWindowVisualState('Normal')
}
# execute needed function
}
else {
start-process "C:\Users\Public\Desktop\Welcome.lnk" -WindowStyle Normal
# execute needed function
}
start-sleep -Milliseconds 500
}
And here is the error attempted a copy and paste
Cannot convert argument "hwnd", with value: "System.Object[]", for "FromHandle' to type "System.IntPtr": "Cannot convert the "System.Object[]" value of type "System.Object[]"' to type "System. IntPtr At C:\Scripts\KioskMinimizedcheckscript.ps1:9 char:5 + Sae = [system.windows. Automation.AutomationElement]:: FromHandle($
+
+CategoryInfo
: NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgument Conversion InvalidcastArgument
You cannot call a method on a null-valued expression. At C:\scripts\KioskMinimizedcheckscript.ps1:10 char:5
Swp = Sae.GetCurrentPattern([system.windows. Automation.windowPatt ...
+ CategoryInfo
Invalidoperation; (:) [], RuntimeException
+ FullyQualifiedErrorId: InvokeMethodonNull
Image of Actual Error
Tried running script on default install of windows and works fine. Just need to know what to add back into the stripped down version.

Null-valued expression for script on WSUS?

I am trying to retrieve a list of updates in the scope. My code is as follows:
#Loads Microsoft.UpdateServices.Administration assembly in order to connect to the WSUS server
[reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”) | Out-Null
#Make the initial WSUS connection by using the .NET accelerator [Microsoft.UpdateServices.Administration.AdminProxy] and the static method getUpdateServer(), which requires two values: the WSUS server name and a Boolean value for a secure connection.
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer()
#Creating the Computer Target Scope object
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
#Find all clients using the computer target scope
$wsus.GetComputerTargets($computerscope)
#Gets computer status
$Wsus.GetComputerStatus($computerscope,[Microsoft.UpdateServices.Administration.UpdateSources]::All)
When I try to run the following:
#Provides a summary of whether the clients that are specified in the scope require the update
ForEach($update in $computerscope)
{
$update = $wsus.SearchUpdates($computerscope)
}
$update[0].GetSummary($computerscope)
I receive the following error:
You cannot call a method on a null-valued expression.
At line:6 char:1
+ $update[0].GetSummary($computerscope)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
even though I am passing $computerscope in the GetSummary method.
Any guidance would be appreciated.

Problems querying the Windows search index

I want to write a powershell script which searches the Windows index for files containing names which are provided as a parameter to the script. I searched the internet and came up with the following solution:
function Search-FileInIndex ($firstname, $lastname) {
$sql = "SELECT System.ItemName, System.DateCreated, System.ItemPathDisplay, System.Search.Rank FROM SYSTEMINDEX WHERE CONTAINS('`"$($firstname)`" NEAR `"$($lastname)`"') and SCOPE= 'c:\' and System.Search.Rank > 0 ORDER BY System.ItemPathDisplay"
$provider = "provider=search.collatordso;extended properties=’Application=Windows’;"
$connector = new-object system.data.oledb.oledbdataadapter -argument $sql, $provider
$dataset = new-object system.data.dataset
if ($connector.fill($dataset)) {
$dataset.tables[0] | format-table -autosize *
}
$dataset.Dispose()
$connector.Dispose()
}
Search-FileInIndex john doe
However, I have two problems.
Problem 1
The provided solution works and finds files, but sometimes I get really strange error messages like these ones resulting in an exception instead of a file listing:
Ausnahme beim Aufrufen von "Fill" mit 1 Argument(en): "Fehler E_FAIL(0x80004005) in IErrorInfo.GetDescription."
In C:\Search-FileInIndex.ps1:11 Zeichen:9
+ if ($connector.fill($dataset)) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OleDbException
or
Ausnahme beim Aufrufen von "Fill" mit 1 Argument(en): "Die Pipe wurde beendet."
In C:\Search-FileInIndex.ps1:11 Zeichen:9
+ if ($connector.fill($dataset)) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OleDbException
I read on the internet that especially the first error results from keywords being used but I don't see any reserved keywords in my query and as I already said, it works sometimes. Is this a race condition or memory issue? I'm running this on Windows 10 Enterprise 1703 with 16 GB of RAM.
EDIT:
I got some new insights.
If I run the script for the first time, it usually works. If I run it again, the crashes are likely to occur, but I didn't find a waiting time between these two runs yet.
If it crashes there is an entry in the application log in the Event Viewer that IndexSearcher.exe was faulty.
The problem seems to be the field System.Search.Rank. If I remove it, it runs flawlessy. However, I need the rank because otherwise I cannot filter the wrong results (due to the NEAR-search). Do you know a replacement for the NEAR-search?
Problem 2
Actually, I would like to have hit-highlighting showing me a snippet of the found matches in the file. However, the MSDN states that the API originally used for that is deprecated. I read on stackoverflow that I would have to use an explorer shell interface, but I have no clue how to do this. Can you provide a working example?
Thanks and best regards,
Hans
I can reproduce the error and the troublemaker seems surprisingly the "NEAR" statement in SQL. This solution is working for me:
function Search-FileInIndex($firstname, $lastname) {
$con = New-Object -ComObject ADODB.Connection
$rs = New-Object -ComObject ADODB.Recordset
$sql = "SELECT System.ItemName, System.DateCreated, System.ItemPathDisplay, System.Search.Rank FROM SYSTEMINDEX WHERE CONTAINS(System.Search.Contents, '$($firstname)') and CONTAINS(System.Search.Contents, '$($lastname)') and SCOPE= 'c:\' and System.Search.Rank > 0 ORDER BY System.ItemPathDisplay"
$con.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
$rs.Open($sql, $con)
While(-Not $rs.EOF){
$rs.Fields.Item("System.ItemPathDisplay").Value
$rs.MoveNext()
}
$rs.Close()
$con.Close()
}
Search-FileInIndex john doe

How to test if an EventSubscriber exists in Windows Powershell

Before deleting an EventSubscriber with SourceIdentifier "abc", I want to test if it exists and only then delete it. Otherwise there is no need to.
But every time I access it to test if it exists with:
Get-EventSubscriber -SourceIdentifier "abc"
Powershell responds with an error:
get-eventsubscriber : Event subscription with source identifier 'abc' does not exist.
At line:1 char:8
+ $chk = get-eventsubscriber -SourceIdentifier "abc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-EventSubscriber], Argu
mentException
+ FullyQualifiedErrorId : INVALID_SOURCE_IDENTIFIER,Microsoft.PowerShell.C
ommands.GetEventSubscriberCommand
stating that it does not exist. Is there a way to avoid the error messages and instead set a variable to null or false that can be tested to see if it does not exist?
Something like:
$eventSubscriberExists = Get-EventSubscriber -SourceIdentifier "abc"
if ($eventSubscriberExists) {
Unregeister-Event -SourceIdentifier "abc"
}
In other words instead of sending error messages to the console, set a variable to true or false.

Powershell script works but also gives an error message

The error is as follows:
You cannot call a method on a null-valued expression.
At C:\Across.ps1:6 char:21
+ $result.Handle.Close <<<< ()
+ CategoryInfo : InvalidOperation: (Close:String) [],
RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The script is as follows:
# Load ntuser.dat
reg load HKU\Across C:\users\Default\NTUSER.DAT
# Create a new key, close the handle, and trigger garbage collection
$result = New-Item -Path
'Registry::HKEY_USERS\Across\Software\AcrossStuff'
$result.Handle.Close()
[gc]::Collect()
#Unload ntuser.dat
reg unload HKU\Across
Can you please help me fix this.
Thanks!
Your $result seems to be null, check the place where it is assigned and ensure that this is not null
It is either your script is not properly lined up or path does not exist. You have to check this.
$result = New-Item -Path 'Registry::HKEY_USERS\Across\Software\AcrossStuff'

Resources