Powershell / Chrome Selenium - Forcing update of default download directory - powershell

I have been trying out some automation using Powershell and Selenium + Chrome, however I am struggling to be able to have the default download folder actually apply when Chrome is launched.
I have used this as a guide to set the default download directory in Powershell, and while it does boot launch Chrome with the directory set in "chrome://settings/?search=download", it isn't actually applied (unless you manually press the 'Change' button in settings, which defeats the point of automating it!) and still download to the default user downloads folder:
Chrome settings after PS launch
#WebDriver.dll - C# 4.10 - .NET 4.8
#ChromeDriver - 97.0.4692.71
$WorkingPath = 'C:\PSChromeSelenium'
[System.Reflection.Assembly]::LoadFrom("$($workingPath)\WebDriver.dll")
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$SavePath="C:\Temp"
$HashTable = #{}
$HashTable.Add("prompt_for_download", $true)
$HashTable.Add("default_directory", $SavePath)
$ChromeOptions.AddUserProfilePreference("download", $HashTable)
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
Downloading using 'Save / Save As' still opens to the default folder.
Any help would be appreciated! Thanks in advance.

Related

Powershell with Selenium 4.x: Chrome options

I am able to successfully execute a Powershell script with Selenium 4.x although i need to run chrome under a user profile (which will persist). The objective is to save the cookies. For that I believe I will need to add options as defined in Saving chrome cookies Selenium. I do see something similar here although I need it for Powershell.
So how do I implement options that can be used by this command. (This command is primarily for selenium 4.x).
$browser = Start-SeDriver -Browser Chrome
This is all I could get, but I am unsure how to add it all up:
$ChromeOptions.addArguments("c:/users/PsUser");
With Module https://github.com/adamdriscoll/selenium-powershell v4:
$browser = Start-SeDriver -Browser Chrome -Arguments "--user-data-dir=C:\Users\$($env:username)\AppData\Local\Google\Chrome\User Data"
Without Module:
When you instantiate the ChromeDriver object you can pass a ChromeOptions argument.
So basically:
# Your working directory
$workingPath = 'C:\selenium'
# Add the working directory to the environment path.
# This is required for the ChromeDriver to work.
if (($env:Path -split ';') -notcontains $workingPath) {
$env:Path += ";$workingPath"
}
# OPTION 1: Import Selenium to PowerShell using the Add-Type cmdlet.
Add-Type -Path "$($workingPath)\WebDriver.dll"
# Create a new ChromeDriver Object instance.
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.AddArgument("--user-data-dir=C:\Users\$($env:username)\AppData\Local\Google\Chrome\User Data")
$chrome = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
# Launch a browser and go to URL
$ChromeDriver.Navigate().GoToURL('https://google.com')
# Cleanup
$ChromeDriver.Close()
$ChromeDriver.Quit()

Open User Profile In Chrome using PowerShell and Selenium

So I have found little to no info on this topic, basically I'm just trying to use selenium to open up a chrome profile so that the settings are saved to be used in each run of the script. Please help as I am new to coding and have never used PowerShell.
So far the only semi successful attempt with no errors is as follows but still does not work..
$WebDriverPath = Resolve-Path "C:\selenium\WebDriver.dll"
Unblock-File $WebDriverPath
Add-Type -Path $WebDriverPath
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$CD = $ChromeDriver.AddArgument("--user-data-dir=C:\Users\jshaw\AppData\Local\Google\Chrome\User Data\Profile 2")
$CD = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$CD.Navigate().GoToURL('https://www.google.com')
So i figured out how to do this! This loads your default profile; however, there is an issue when you do this. If you have Chrome open already it throws an error. when Chrome is closed all good! Now I know why people use customized profiles.
$ChromeOptions.AddArgument(
"--user-data-dir=C:\Users\TweakAir\AppData\Local\Google\Chrome\User Data"
)
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
$ChromeDriver.Navigate().GoToURL($YourURL)```

Powershell Startup Script GPO Not Applying

Pretty basic script used to create a web shortcut on the PC's desktop, but it's not applying for some reason. I have it set in the gpo under
Computer Configuration->Policies-> Windows Settings-> Scripts-> Startup->
Added the powershell script-> And set it to run the powershell script first.
I also know the script works because I have tried running it manually on the machine without admin privileges or anything and it appears just fine.
$DesktopPath = [Environment]::GetFolderPath("Desktop") + "\Prophet21.url"
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DesktopPath)
$Shortcut.TargetPath = "https://p21.gallagherseals.com/prophet21/#/login" $Shortcut.Save()
You're running the code in the wrong context, to run as a user and affect a user, you need to deploy this as a User Configuration.
When you run a Startup Script for a Computer, this happens when the PC is Domain Joined and will process shortly after displaying the initial login screen silently in the background.
But because there is no user logged in yet, some items aren't available.
To fix this, just deploy it as a User Configuration, the full path to the setting would be:
User Configuration -> Policies -> Windows Settings -> Scripts (Logon / Logoff);
The better approach
However, GPO also natively supports creating Desktop Icons with a nice and easy to use wizard. Just follow this short guide by Praj Dasai. I used to manage GPO and I would always prefer a native solution to running a script.

Selenium, InternetExplorerDriver, ForceCreateProcessApi, timeout or no browser launch?

We've been using Selenium to automate some browser testing in Internet Explorer. On Windows 7 32-bit it works fine. However we're testing it on Windows 10 64-bit and it fails miserably.
Sometimes the browser doesn't even launch
If i change the driver versions, i can get the browser to launch but it hangs on the first page
The issue is only present when I use ForceCreateProcessApi. However I need to use ForceCreateProcessApi in order to use BrowserCommandLineArguments!
The exception is: The HTTP request to the remote WebDriver server for URL http://localhost:16639/session timed out after 60 seconds.
Here is the PowerShell code i use:
$seleniumOptions = New-Object OpenQA.Selenium.IE.InternetExplorerOptions
$seleniumOptions.InitialBrowserUrl = $SiteUrl
$seleniumOptions.ForceCreateProcessApi = $true
$seleniumOptions.BrowserCommandLineArguments = "-k"
$seleniumOptions.IgnoreZoomLevel = $true
New-Variable -Name IEDS -Value ([OpenQA.Selenium.IE.InternetExplorerDriverService]) -Force
$defaultservice = $IEDS::CreateDefaultService()
$seleniumDriver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver -ArgumentList #($defaultservice, $seleniumOptions)
I've tried the following versions (x86 and x64 versions), and none of them work:
2.25.3
3.141
3.9.0
Can anybody advise on how to make this work? I've made sure that TabProcGrowth etc is set according to the documentation.
Thanks.
Try to use a 3.150.1 32-bit driver.
I'm not sure how it looks on PS - but I'm able to run IE with this driver config.
ie: { version: "3.150.1", arch: "ia32" }
Also I have a key for iexplore.exe here:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE
from this config link

Download file from website using SendKeys in Powershell

I'm trying to download an file from a particular website by clicking on the file icon. Website login works but i'm hoping to use keystroke "TAB" to navigate to the excel file and finally key "Enter" to download. Ran the code but resulted in the Powershell text of "FALSE". Any advice is appreciated! Thanks.
Reference: Table screenshot
$url = "https://abcdefg.com"
$username="test#gmail.com"
$password="TestPW"
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($url);
while ($ie.Busy -eq $true)
{
Start-Sleep -Milliseconds 1000;
}
$ie.Document.getElementById("txtEmail").value = $username
$ie.Document.getElementByID("txtPassword").value=$password
$ie.Document.getElementById("Login").Click();
Start-Sleep -Milliseconds 10000
$obj = new-object -com WScript.Shell
$obj.AppActivate('Internet Explorer')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{Enter}')
Why are you doing that vs using web scraping to find the link you are trying to hit, and use the link URL directly?
Your post is really a duplicate of this Q&A.
Use PowerShell to automate website login and file download
SendKeys could work, but they are very hinky and on different systems may not function as you'd expect. There are better tools dedicated to do this, AutoIT, Selenium, WASP
--- That WASP tool still works, but has not been updated in a long while.
Using PowerShell 2.0 With Selenium to Automate Internet Explorer, Firefox, and Chrome
Internet Explorer
Next you want to obtain the Internet Explorer driver from this site. I
recommend version 2.41 because “as of 15 April 2014, IE 6 is no longer
supported”. This must reside in your current PATH so in your script
you may want to modify your PATH to ensure the executable
(IEDriverServer.exe) can be found there. If you’re wondering whether
to get the 32-bit or the 64-bit version, start with the 32-bit even if
you’ve got a 64-bit Windows.
At this point you’ll want to quickly instantiate Internet Explorer and
navigate somewhere. Great. Let’s do it.
# Load the Selenium .Net library
Add-Type -Path "C:\selenium\WebDriver.dll" # put your DLL on a local hard drive!
# Set the PATH to ensure IEDriverServer.exe can found
$env:PATH += ";N:\selenium"
# Instantiate Internet Explorer
$ie_object = New-Object "OpenQA.Selenium.IE.InternetExplorerDriver"
# Great! Now we have an Internet Explorer window appear. We can navigate to a new URL:
$ie_object.Navigate().GoToURL( "http://www.bbc.co.uk/languages" )
# This worked! The call won’t return until the page download is complete.
# Next let’s click on a link from the link text:
$link = $ie_object.FindElementByLinkText( "Spanish" )
$link.Click()
# display current URL
$ie_object.Url
Selenium Tutorial: All You Need To Know About Selenium WebDriver
Update for the OP
As for...
However the file does not have a redirected URL
Then you need to look deeper at the site, to find the anchor to the file that you can force click on.
Example:
# Scrape a web page with PowerShell
$w = Invoke-WebRequest -Uri 'https://www.reddit.com/r/PowerShell'
$w | Get-Member
$w.AllElements
$w.AllElements.Count
$w.Links.Count
$w.Links
$w.Forms
$w.Forms.Fields
$w.Forms[0]
$w.Forms[0].Fields
$w.RawContent
$w.ParsedHtml
once you find tag names, or the like, you need to parse that to get stuff out of it.
$w.AllElements | Where-Object -Property 'TagName' -EQ 'P' | Select-Object -Property 'InnerText'
For tables you have to dig more.
Extracting Tables from PowerShell’s Invoke-WebRequest