How do you define firefox exe path in selenium with Powershell? - powershell

I'm trying to use selenium Firefox with powershell and I need to specify the firefox's executable (portable firefox). I can make my script work with chrome and I have found how to specify chrome's path but I had no luck with Firefox.
Here's all I got so far:
# Website and credential variables
$YourURL = "http://192.168.0.1/" # Website we'll access
# Invoke Selenium into our script!
# Geckodriver.exe
$env:PATH += ";D:\Powershell\webdriver"
Add-Type -Path "D:\Powershell\webdriver\WebDriver.dll"
Add-Type -Path "D:\Powershell\webdriver\WebDriver.Support.dll"
$ff_object = New-Object "OpenQA.Selenium.Firefox.FirefoxDriver"

Thanks a lot JimEvans! Here is my powershell working code:
$YourURL = "http://192.168.0.1/" # Website we'll access
$env:PATH += "C:\Users\Carl\Desktop\webdriver\" # Adds the path for ChromeDriver.exe to the environmental variable
Add-Type -Path "C:\Users\Carl\Desktop\webdriver\WebDriver.dll" # Adding Selenium's .NET assembly (dll) to access it's classes in this PowerShell session
$FirefoxOptions = New-Object OpenQA.Selenium.Firefox.FirefoxOptions
$FirefoxOptions.BrowserExecutableLocation = "D:\PortableApps\FirefoxPortable\App\Firefox64\firefox.exe"
$FirefoxDriver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver($FirefoxOptions)
# Make use of Selenium's class methods to manage our browser at will
$FirefoxDriver.Navigate().GoToUrl($YourURL) # Browse to the specified website

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()

Making a .lnk that opens in a new window with powershell

Good Day everyone!
I am looking to make PowerShell script that creates a .lnk shortcut on the desktop. Which isn't too big a deal, but when I make one manually with chrome, 3 dots>more tools>create shortcut I get this option. Notice how it has the "Open in a new window" option. That is what I'm looking to accomplish. How would I go about making a .lnk file on the desktop that opens in a new window?
make an .lnk shortcut on desktop save it to desktop
.lnk file opens in new window
-preferably grabs an icon from the browser like when you make one with chrome so I don't have to point to one.
$Shell = New-Object -ComObject ("WScript.Shell")
$Favorite = $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Google.lnk")
$Favorite.TargetPath = "http://google.com";
$Favorite.IconLocation = "Picturelocation"
$Favorite.Arguments
$Favorite.Save()
Thanks for your time!
Notice the Icon and Open in a New window button
Use the following to create a shortcut file (.lnk) that launches Chrome with a given URL in a new window:
# Define the target URL
$url = 'https://google.com'
# Derive a friendly site name from it, to serve as the name
# of the shortcut file and the downloaded favicon.
# Adjust as needed, e.g. $friendlySiteName = 'Google'
$friendlySiteName = $url -replace '^https?://(?:www\.)?'
# Determine the full path of the shortcut file; adjust as needed.
# Note the required ".lnk" extension
$shortcutPath = "$HOME\Desktop\$friendlySiteName.lnk"
# Determine the full path of the chrome.exe executable, via the registry.
# Note: This is only necessary because chrome.exe is *not* in one
# of the directories listed in $env:PATH.
$chromeExePath = Get-ItemPropertyValue -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' '(default)'
# Download the favicon:
# Create a designated local directory for storing favicons...
$targetDir = New-Item -Type Directory -Force "$HOME\favicons"
# ... and download the target site's favicon into it.
$favIconPath = Join-Path $targetDir.FullName ($friendlySiteName + '.ico')
& {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -OutFile $favIconPath "$url/favicon.ico"
}
# Create the shortcut file, set its properties, and save it.
$shell = New-Object -ComObject WScript.Shell
$favorite = $shell.CreateShortcut($shortcutPath)
# Tell the shortcut to launch Chrome...
$favorite.TargetPath = $chromeExePath
# ... with the following arguments; -new-window ensures that the
# specified URL is opened in a new window.
$favorite.Arguments = "-new-window $url"
# ... and assign the icon.
$favorite.IconLocation = $favIconPath
$favorite.Save()
Note: The above downloads and assigns the target site's specific favicon as the shortcut file's icon, you can omit the relevant code above, which will make the shortcut file show Chrome's icon.
For the sake of completeness: Creating a URL shortcut file (.url) with the target site's favicon:
Note that such URL shortcut files invariably:
use the default web browser on invocation, and default to that browser's own icon.
typically create a new tab in an existing browser window rather than opening a new window.
As explained in this answer, assigning a custom icon programmatically isn't directly supported via the WScript.Shell COM object, but can be achieved via plain-text processing to modify the .url file after the fact, as shown below.
# Define the target URL.
$url = 'https://google.com'
# Derive a friendly representation from it, to serve as the name of the shortcut file
# and the downloaded favicon.
# Adjust as needed; e.g. $friendlySiteName = 'Google'
$friendlySiteName = $url -replace '^https?://(?:www\.)?'
# Determine the full path of the shortcut file; adjust as needed.
# Note the required ".url" extension.
$urlShortcutPath = "$HOME\Desktop\$friendlySiteName.url"
# Download the favicon:
# Create a designated local directory for storing favicons...
$targetDir = New-Item -Type Directory -Force "$HOME\favicons"
# ... and download the target site's favicon into it.
$favIconPath = Join-Path $targetDir.FullName ($friendlySiteName + '.ico')
& {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -OutFile $favIconPath "$url/favicon.ico"
}
# Create the URL shortcut file, set its properties, and save it.
$shell = New-Object -ComObject WScript.Shell
$urlShortcut = $shell.CreateShortcut($urlShortcutPath)
# Tell the URL shortcut what URL to launch.
# !! No other properties are directly supported for URL shortcut files.
# !! Plain-text processing below compensates for that.
$urlShortcut.TargetPath = $url
$urlShortcut.Save()
# Now use plain-text processing to add the icon location.
Add-Content -LiteralPath $urlShortcut.FullName -Value #"
IconIndex=0
HotKey=0
IconFile=$favIconPath
"#

Selenium and Chromedriver - element not interactable

I've been working with Selenium for a few weeks now. This script was working fine until the website owner recently updated the code, and now my logging into the website will no longer work.
Chrome Drivers and Selenium have been updated, it's an element that I can't seem to get to become intractable.
I've tried adding:
$seleniumDriver.Manage().Timeouts().ImplicitlyWait((New-TimeSpan -Seconds 5))
That didn't work.
I've also tried changing the code from
$ChromeDriver.FindElementXPath("//*[#id='email']").Click
to
$ChromeDriver.FindElement("email_username"").Click
That also didn't work.
Also, adding a Start-Sleep -seconds 15 also didn't help.
There must be another way to get this username and password box clickable. Would appreciate any help. This is what I have so far.
$workingPath = 'C:\selenium'
if (($env:Path -split ';') -notcontains $workingPath) {
$env:Path += ";$workingPath"
}
Add-Type -Path "$($workingPath)\WebDriver.dll"
Add-Type -Path "$($workingPath)\WebDriver.Support.dll"
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
# Launch a browser and go to URL
$ChromeDriver.Navigate().GoToURL("https://fund.traderscentral.com/overview")
# Enter the username in the Username box
$ChromeDriver.FindElementXPath("//*[#id='email']").Click
$ChromeDriver.FindElementByXPath('//*[#id="email"]').SendKeys('b0rken#gmail.com')
# Enter the password in the Password box
$ChromeDriver.FindElementByXPath('//input[#name="password"]').SendKeys('12345678')
# Click on the Login button
$ChromeDriver.FindElementByXPath("//button[#type='submit']").Click();
# Cleanup
$ChromeDriver.Close()
$ChromeDriver.Quit()
i am afraid that some bugs in selenium doesnt bring the solution at your problem:
it seems that the input field was not seen inside a div...
i have found a solution in c# by using Actions, i am not expert in powershell but i suppose Actions exist in powershell, C# and powershell could use same library:
this is my solution in C#: i just send keys with Actions, the first tab goes to the email field and i dont know why but i have to write all sendkeys in one line, hope that could help you:
Actions actions = new Actions(driver);
actions.SendKeys(Keys.Tab).SendKeys("b0rken#gmail.com").SendKeys(Keys.Tab).SendKeys("12345678").Perform();
Actions belongs to OpenQA.Selenium.Interactions
in powershell (not tested)
workingPath = 'C:\selenium'
if (($env:Path -split ';') -notcontains $workingPath) {
$env:Path += ";$workingPath"
}
Add-Type -Path "$($workingPath)\WebDriver.dll"
Add-Type -Path "$($workingPath)\WebDriver.Support.dll"
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
# Launch a browser and go to URL
$ChromeDriver.Navigate().GoToURL("https://fund.traderscentral.com/overview")
#modif
# here 10sec adjust your wait time
[OpenQA.Selenium.Support.UI.WebDriverWait]$wait = New-Object OpenQA.Selenium.Support.UI.WebDriverWait ($ChromeDriver,[System.TimeSpan]::FromSeconds(10))
$wait.PollingInterval = 100
[void]$wait.Until([OpenQA.Selenium.Support.UI.ExpectedConditions]::ElementExists([OpenQA.Selenium.By]::Id('email')))
[OpenQA.Selenium.Interactions.Actions]$actions = New-Object OpenQA.Selenium.Interactions.Actions ($ChromeDriver)
$actions.SendKeys([OpenQA.Selenium.Keys]::Tab).SendKeys("b0rken#gmail.com").SendKeys([OpenQA.Selenium.Keys]::Tab).SendKeys("12345678").Perform()
i have seen some adding build(), dunno the difference but you could test:
$actions.SendKeys([OpenQA.Selenium.Keys]::Tab).SendKeys("b0rken#gmail.com").SendKeys([OpenQA.Selenium.Keys]::Tab).SendKeys("12345678").Build().Perform()

Reference WinSCP.exe from PowerShell script executed from SSIS

I am trying to execute a PowerShell script from within SSIS. My script starts with the Add-Type -Path "WinSCPnet.dll" and it is erroring out because it cannot find the WinSCP.exe in the folder that houses my PowerShell script. Come to find out the server admin did NOT install WinSCP into the GAC. Is this creating my problem?
If so, how and where can I reference the WinSCP.exe in my script using $session.ExecutablePath? Any help/direction would be appreciated. Thanks.
Here is my script below:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Declare variables
$date = Get-Date
$dateStr = $date.ToString("yyyyMMdd")
#$fileDirectory = "\\abicfs2\apps\CoverageVerifier\"
#$filePath = "\\abicfs2\apps\CoverageVerifier\cvgver." + $dateStr + ".0101"
$filePath = "\\empqaapp1\coverageverifier_scripts\CoverageVerifier\cvgver.20190121.0101"
# Write-Output $filePath
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "secureftp.iso.com"
UserName = "account"
Password = "password"
SshHostKeyFingerprint = "ssh-rsa 2048 8C1lwAjxCNRF6B4kbPIeW52/GB+98FmLMt0AJNf/Sf4="
}
#$sessionOptions.AddRawSettings("FSProtocol", "2")
$session = New-Object WinSCP.Session
# $session.SessionLogPath = "\\share\apps\CoverageVerifier\UploadLog.log"
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.PutFiles($filePath,"/").Check()
}
finally
{
$session.Dispose()
}
I am trying to execute a Powershell script from within SSIS
It seems you believe you need to have WinSCP .NET assembly in GAC, so that you can execute it from a PowerShell script executed from SSIS. I do not think it's true. You need an assembly in GAC, only if you directly use it from an SSIS code. What is not your case.
You can simply store the WinSCPnet.dll and WinSCP.exe to your PowerShell script directory.
Anyway to answer your question:
If so, how and where can I reference the WinSCP.exe in my script using $session.ExecutablePath?
$session = New-Object WinSCP.Session
$session.ExecutablePath = "C:\path\WinSCP.exe"
(but as per above, I do not think you need it)
Come to find out the server admin did NOT install WinSCP into the GAC.
You cannot install .exe file to GAC.
Excerpt from WinSCP assembly installation instruction (https://winscp.net/eng/docs/library_install):
The package includes the assembly itself (winscpnet.dll) and a
required dependency, WinSCP executable winscp.exe.
The binaries interact with each other and must be kept in the same
folder for the assembly to work. In rare situations this is not
possible (e.g. when installing the assembly to GAC), make use of the
Session.ExecutablePath property to force the assembly to look for the
winscp.exe in a different location.

webget in Powershell

Is there any command equivalent to webget in WindOS's PowerShell?
I am trying to create a script to download all publicly available files from the website. I am making the custom script because I need to store the files in specific directory structure (depending on name, type and size).
In PowerShell v2, use a WebClient:
(New-Object System.Net.WebClient).DownloadFile($url, $localFileName)
In v3, the Invoke-WebResquest cmdlet:
Invoke-WebRequest -Uri $url -OutFile $localFileName
Another option is with the Start-BitsTransfer cmdlet:
Start-BitsTransfer -Source $source -Destination $destination
In PowerShell V3, you can use the new cmdlet Invoke-WebRequest to send an http or https request to a web site/service e.g.:
$r = Invoke-WebRequest -URI http://www.bing.com?q=how+many+feet+in+a+mile
However to specifically download a file it is probably easiest to use the .NET API WebClient.DownloadFile() e.g.:
$remoteUri = "http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"
$fileName = "$pwd\logo.png"
$webClient = new-object System.Net.WebClient
$webClient.DownloadFile($remoteUri, $fileName)
you can use the .NET class WebClient to download files.
PS > $source = "http://www.unsite.fr/untruc.zip"
PS > $destination = "c:\temp\untruc.zip"
PS >
PS >$wc = New-Object System.Net.WebClient
PS >$wc.DownloadFile($source, $destination)
If you prefer a "native" PowerShell cmdlet that works in PowerShell V2 or V3, I recommend Get-HttpResource from the PowerShell Community Extensions (PSCX). While PSCX surprisingly does not have the API available online (you have to install the extensions then you can use the normal PowerShell help to explore each command), I managed to find the API for Get-HttpResource here. Using the cmdlet can be as simple as this:
$myPage = Get-HttpResource http://blogs.msdn.com/powershell
However, there are a variety of parameters to the cmdlet that let you specify media type, credentials, encoding, proxy, user agent, and more.