Search Results for 'sendkeys'

Welcome Forums Search Search Results for 'sendkeys'

Viewing 15 results - 1 through 15 (of 52 total)
  • Author
    Search Results
  • #228466
    Participant
    Topics: 12
    Replies: 1645
    Points: 2,674
    Helping Hand
    Rank: Community Hero

    Have you searched for this? I searched “registry set default browser powershell windows 10” and there are a ton of threads. It’s not just setting a key and MS makes it painful to change the browser because they want you to use their browser. Many of the solutions are using a exe and then sendkeys to go thru the interface which is last ditch effort.

    Participant
    Topics: 3
    Replies: 422
    Points: 1,483
    Helping Hand
    Rank: Community Hero

    Thanks for your response i have multiple machines to automate this stuff this banner seems to be hard coded server level which means while deploying images…so am not able to skip this on machine level

    The logon banner can be configured via group policy, so whatever setting the server has can be overridden. Like I said I used vb, C#, and powershell with space, timeout, launching the rdp through each and then using send or sendkeys. Seems only sendwait() was allowed at least in the ISE. None of them worked despite the RDP being front, center, and selected and a simple enter or spacebar dismisses it fine. Again, if the banner is being automatically dismissed, then it really isn’t serving a purpose. For those machines you could consider creating a group policy to remove the banner. I’m not sure your familiarity with GPO. You can set up against an OU, group, specific AD object, or you could simply use WMI filtering to apply only to the machines you want.

    https://www.prajwaldesai.com/how-to-configure-legal-notices-on-domain-computers-using-group-policy/

    If GPO is not an option for whatever reason, it can also be set via registry.

    https://answers.microsoft.com/en-us/windows/forum/windows_7-security/configure-a-logon-banner/4e2fda8d-9522-42bf-a272-3be5d55d7565

    By the way that’s a nice script. Did you write it?

    • This reply was modified 2 months, 3 weeks ago by Doug Maurer.
    Participant
    Topics: 2
    Replies: 2
    Points: -9
    Rank: Member
    $server = “ServerName”
    $Cred1 = New-Object -TypeName pscredential -ArgumentList “UserName”,(ConvertTo-SecureString -String ‘password’ -AsPlainText -Force);
    
    
    Function Connect-Mstsc {
    
    
    [cmdletbinding(SupportsShouldProcess,DefaultParametersetName=’UserPassword’)]
    param (
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true,
    ValueFromPipelineByPropertyName=$true,
    Position=0)]
    [Alias(‘CN’)]
    [string[]] $ComputerName,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=1)]
    [Alias(‘U’)]
    [string] $User,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=2)]
    [Alias(‘P’)]
    [string] $Password,
    [Parameter(ParameterSetName=’Credential’,Mandatory=$true,Position=1)]
    [Alias(‘C’)]
    [PSCredential] $Credential,
    [Alias(‘A’)]
    [switch] $Admin,
    [Alias(‘MM’)]
    [switch] $MultiMon,
    [Alias(‘F’)]
    [switch] $FullScreen,
    [Alias(‘Pu’)]
    [switch] $Public,
    [Alias(‘W’)]
    [int] $Width,
    [Alias(‘H’)]
    [int] $Height,
    [Alias(‘WT’)]
    [switch] $Wait
    )
    
    
    begin {
    [string]$MstscArguments = ”
    switch ($true) {
    {$Admin} {$MstscArguments += ‘/admin ‘}
    {$MultiMon} {$MstscArguments += ‘/multimon ‘}
    {$FullScreen} {$MstscArguments += ‘/f ‘}
    {$Public} {$MstscArguments += ‘/public ‘}
    {$Width} {$MstscArguments += “/w:$Width “}
    {$Height} {$MstscArguments += “/h:$Height “}
    }
    
    
    if ($Credential) {
    $User = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().Password
    }
    }
    process {
    foreach ($Computer in $ComputerName) {
    $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
    $Process = New-Object System.Diagnostics.Process
    
    # Remove the port number for CmdKey otherwise credentials are not entered correctly
    if ($Computer.Contains(‘:’)) {
    $ComputerCmdkey = ($Computer -split ‘:’)[0]
    } else {
    $ComputerCmdkey = $Computer
    }
    
    
    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\cmdkey.exe”
    $ProcessInfo.Arguments = “/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($ComputerCmdkey,’Adding credentials to store’)) {
    [void]$Process.Start()
    }
    
    
    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\mstsc.exe”
    $ProcessInfo.Arguments = “$MstscArguments /v $Computer”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($Computer,’Connecting mstsc’)) {
    [void]$Process.Start()
    if ($Wait) {
    $null = $Process.WaitForExit()
    }
    }
    }
    }
    }
    
    
    connect-mstsc -ComputerName $server -Credential $Cred1 -ErrorAction stop
    
    
    ##below code is used to skip certificate warning###
    
    
    [void][System.Reflection.Assembly]::LoadWithPartialName(‘System.Windows.Forms’)
    # Get the ID of the process
    $WindowsHandle = Get-Process | Where-Object { $_.ProcessName -match ‘mstsc’ } | Select-Object -ExpandProperty Id
    # Activate the window
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate($WindowsHandle) | Out-Null
    
    
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)
    
    
    ##Below code needs to modified to click ok button legal notice banner
    
    
    function Click-MouseButton
    {
    [email protected]’
    [DllImport(“user32.dll”,CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    ‘@
    
    
    $SendMouseClick = Add-Type -memberDefinition $signature -name “Win32MouseEventNew” -namespace Win32Functions -passThru
    
    
    $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    }
    
    
    [system.Reflection.Assembly]::LoadWithPartialName("Remote Desktop Connection") | out-null
    
    
    # Set the exactly position of cursor in some iexplore hyperlink between the (open parenthesis) below:
    [System.Windows.Forms.Cursor]::Position
     = New-Object System.Drawing.Point(790,675)
    Click-MouseButton
    
    • This reply was modified 2 months, 3 weeks ago by Vignesh211726.
    Vignesh172191
    Participant
    Topics: 2
    Replies: 0

    $server = “ServerName”
    $Cred1 = New-Object -TypeName pscredential -ArgumentList “UserName”,(ConvertTo-SecureString -String ‘password’ -AsPlainText -Force);

    Function Connect-Mstsc {

    [cmdletbinding(SupportsShouldProcess,DefaultParametersetName=’UserPassword’)]
    param (
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true,
    ValueFromPipelineByPropertyName=$true,
    Position=0)]
    [Alias(‘CN’)]
    [string[]] $ComputerName,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=1)]
    [Alias(‘U’)]
    [string] $User,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=2)]
    [Alias(‘P’)]
    [string] $Password,
    [Parameter(ParameterSetName=’Credential’,Mandatory=$true,Position=1)]
    [Alias(‘C’)]
    [PSCredential] $Credential,
    [Alias(‘A’)]
    [switch] $Admin,
    [Alias(‘MM’)]
    [switch] $MultiMon,
    [Alias(‘F’)]
    [switch] $FullScreen,
    [Alias(‘Pu’)]
    [switch] $Public,
    [Alias(‘W’)]
    [int] $Width,
    [Alias(‘H’)]
    [int] $Height,
    [Alias(‘WT’)]
    [switch] $Wait
    )

    begin {
    [string]$MstscArguments = ”
    switch ($true) {
    {$Admin} {$MstscArguments += ‘/admin ‘}
    {$MultiMon} {$MstscArguments += ‘/multimon ‘}
    {$FullScreen} {$MstscArguments += ‘/f ‘}
    {$Public} {$MstscArguments += ‘/public ‘}
    {$Width} {$MstscArguments += “/w:$Width “}
    {$Height} {$MstscArguments += “/h:$Height “}
    }

    if ($Credential) {
    $User = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().Password
    }
    }
    process {
    foreach ($Computer in $ComputerName) {
    $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
    $Process = New-Object System.Diagnostics.Process

    # Remove the port number for CmdKey otherwise credentials are not entered correctly
    if ($Computer.Contains(‘:’)) {
    $ComputerCmdkey = ($Computer -split ‘:’)[0]
    } else {
    $ComputerCmdkey = $Computer
    }

    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\cmdkey.exe”
    $ProcessInfo.Arguments = “/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($ComputerCmdkey,’Adding credentials to store’)) {
    [void]$Process.Start()
    }

    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\mstsc.exe”
    $ProcessInfo.Arguments = “$MstscArguments /v $Computer”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($Computer,’Connecting mstsc’)) {
    [void]$Process.Start()
    if ($Wait) {
    $null = $Process.WaitForExit()
    }
    }
    }
    }
    }

    connect-mstsc -ComputerName $server -Credential $Cred1 -ErrorAction stop

    ##below code is used to skip certificate warning###

    [void][System.Reflection.Assembly]::LoadWithPartialName(‘System.Windows.Forms’)
    # Get the ID of the process
    $WindowsHandle = Get-Process | Where-Object { $_.ProcessName -match ‘mstsc’ } | Select-Object -ExpandProperty Id
    # Activate the window
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate($WindowsHandle) | Out-Null

    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)

    ##Below code needs to modified to click ok button legal notice banner

    function Click-MouseButton
    {
    [email protected]
    [DllImport(“user32.dll”,CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    ‘@

    $SendMouseClick = Add-Type -memberDefinition $signature -name “Win32MouseEventNew” -namespace Win32Functions -passThru

    $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    }

    [system.Reflection.Assembly]::LoadWithPartialName(“”) | out-null

    # Set the exactly position of cursor in some iexplore hyperlink between the (open parenthesis) below:
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(790,675)
    Click-MouseButton

     

    Experts someone help me to modify script as the above script bypass legal notice screen during RDP connection but fails to click OK button,Any help much appreciated

     

     

     

    Vignesh172191
    Participant
    Topics: 2
    Replies: 0

    $server = “ServerName”
    $Cred1 = New-Object -TypeName pscredential -ArgumentList “UserName”,(ConvertTo-SecureString -String ‘password’ -AsPlainText -Force);

    Function Connect-Mstsc {

    [cmdletbinding(SupportsShouldProcess,DefaultParametersetName=’UserPassword’)]
    param (
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true,
    ValueFromPipelineByPropertyName=$true,
    Position=0)]
    [Alias(‘CN’)]
    [string[]] $ComputerName,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=1)]
    [Alias(‘U’)]
    [string] $User,
    [Parameter(ParameterSetName=’UserPassword’,Mandatory=$true,Position=2)]
    [Alias(‘P’)]
    [string] $Password,
    [Parameter(ParameterSetName=’Credential’,Mandatory=$true,Position=1)]
    [Alias(‘C’)]
    [PSCredential] $Credential,
    [Alias(‘A’)]
    [switch] $Admin,
    [Alias(‘MM’)]
    [switch] $MultiMon,
    [Alias(‘F’)]
    [switch] $FullScreen,
    [Alias(‘Pu’)]
    [switch] $Public,
    [Alias(‘W’)]
    [int] $Width,
    [Alias(‘H’)]
    [int] $Height,
    [Alias(‘WT’)]
    [switch] $Wait
    )

    begin {
    [string]$MstscArguments = ”
    switch ($true) {
    {$Admin} {$MstscArguments += ‘/admin ‘}
    {$MultiMon} {$MstscArguments += ‘/multimon ‘}
    {$FullScreen} {$MstscArguments += ‘/f ‘}
    {$Public} {$MstscArguments += ‘/public ‘}
    {$Width} {$MstscArguments += “/w:$Width “}
    {$Height} {$MstscArguments += “/h:$Height “}
    }

    if ($Credential) {
    $User = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().Password
    }
    }
    process {
    foreach ($Computer in $ComputerName) {
    $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
    $Process = New-Object System.Diagnostics.Process

    # Remove the port number for CmdKey otherwise credentials are not entered correctly
    if ($Computer.Contains(‘:’)) {
    $ComputerCmdkey = ($Computer -split ‘:’)[0]
    } else {
    $ComputerCmdkey = $Computer
    }

    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\cmdkey.exe”
    $ProcessInfo.Arguments = “/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($ComputerCmdkey,’Adding credentials to store’)) {
    [void]$Process.Start()
    }

    $ProcessInfo.FileName = “$($env:SystemRoot)\system32\mstsc.exe”
    $ProcessInfo.Arguments = “$MstscArguments /v $Computer”
    $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
    $Process.StartInfo = $ProcessInfo
    if ($PSCmdlet.ShouldProcess($Computer,’Connecting mstsc’)) {
    [void]$Process.Start()
    if ($Wait) {
    $null = $Process.WaitForExit()
    }
    }
    }
    }
    }

    connect-mstsc -ComputerName $server -Credential $Cred1 -ErrorAction stop

    ##below code is used to skip certificate warning###

    [void][System.Reflection.Assembly]::LoadWithPartialName(‘System.Windows.Forms’)
    # Get the ID of the process
    $WindowsHandle = Get-Process | Where-Object { $_.ProcessName -match ‘mstsc’ } | Select-Object -ExpandProperty Id
    # Activate the window
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate($WindowsHandle) | Out-Null

    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{TAB}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)

    ##Below code needs to modified to click ok button legal notice banner

    function Click-MouseButton
    {
    [email protected]
    [DllImport(“user32.dll”,CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    ‘@

    $SendMouseClick = Add-Type -memberDefinition $signature -name “Win32MouseEventNew” -namespace Win32Functions -passThru

    $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
    }

    [system.Reflection.Assembly]::LoadWithPartialName(“”) | out-null

    # Set the exactly position of cursor in some iexplore hyperlink between the (open parenthesis) below:
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(790,675)
    Click-MouseButton

    Experts am using the above powershell script to establish RDP connection without any manual intervention as the above code failed to click ok to bypass legal notice screen i have found click-mouse button function to bypass this but not working can someone help to correct the script?? Any help much appreciated.

     

     

    • This topic was modified 2 months, 3 weeks ago by Vignesh172191.
    #200708
    Participant
    Topics: 1
    Replies: 1
    Points: 13
    Rank: Member

    Hi Rob,

    Thanks for getting back to me.  I was able to get the appliction installed correctly with the silent install, but this application has a form to create a workspace on the data drive and I would like to also atuomate that part of the application.  Do you know of anyway that I can sendkeys or is there another command that I can use to fill in the input boxes with text?

    Thanks in advance,

    Cuatejlo34
    Participant
    Topics: 1
    Replies: 1

    Hello,

    I’m  just getting started with coding and was wondering if there was a powershell command that will allow me to enter text and specify the directory into an input box for an apps dialogue box.  I was able to get through the buttons in the first 2 pages with the below command.

    start-process “D:\Application\Install.exe”
    $WindowHandle = Get-Process | Where-Object { $_.MainWindowTitle -Match $WindowTitle } | Select-Object -ExpandProperty MainWindowHandle

    [void][System.Reflection.Assembly]::LoadWithPartialName(‘System.Windows.Forms’)
    [System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)
    [System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)

     

    • This topic was modified 5 months, 1 week ago by Cuatejlo34.
    Participant
    Topics: 1
    Replies: 3
    Points: 21
    Rank: Member
    #region Script Methods
    
    <#
    Description : Create runtime object collection from CSV data
    Input(s) : CSV Object
    Output(s) : Object array
    #>
    Function Import-MacroData([Object[]]$CSVData)
    {
    [Object[]]$OutData = @()
    $CSVData | ForEach-Object {
    [String]$Window = $_.Window
    [String]$Description = $_.Description
    [String]$pausePattern = '\{Pause.*?\}'
    
    if ($_.Macro -notmatch $pausePattern)
    {
    #Add macro that does not contain any pauses
    $OutData += Add-DataObject -Window $Window -RawMacro $_.Macro -Macro (ConvertTo-SendKeyString -InputString $_.Macro) -Description $Description
    }
    else
    {
    [String[]]$sMacro = $_.Macro -split $pausePattern
    [System.Text.RegularExpressions.MatchCollection]$pauses = [RegEx]::Matches($_.Macro, '\{Pause.*?\}')
    if ($_.Macro.Trim() -match '^\{Pause.*?\}$')
    {
    #Add single pause macro
    $OutData += Add-DataObject -Window $Window -RawMacro $_.Macro.Trim() -Macro (Get-PauseDuration -InputString $_.Macro.Trim()) -Description $Description -Pause
    }
    else
    {
    [Int]$count = $count = $sMacro.Count - 1
    for ([Int]$i = 0; $i -le $count; $i++ )
    {
    [String]$macro = $sMacro[$i]
    if (($i -gt 0) -and ($i -lt $sMacro.Count))
    {
    #Add pause macro after first non-pause macro and before preceeding macros
    [String]$pause = $pauses[$i-1].Value
    $OutData += Add-DataObject -Window $Window -RawMacro $pause -Macro (Get-PauseDuration -InputString $pause) -Description $Description -Pause
    $OutData += Add-DataObject -Window $Window -RawMacro $macro -Macro (ConvertTo-SendKeyString -InputString $macro) -Description $Description
    }
    else
    {
    #Add before pause macros and after pause macros
    $OutData += Add-DataObject -Window $Window -RawMacro $macro -Macro (ConvertTo-SendKeyString -InputString $macro) -Description $Description
    }
    }
    }
    
    }
    }
    $OutData
    }
    
    #198629

    In reply to: Autorefresh code

    Participant
    Topics: 12
    Replies: 1645
    Points: 2,674
    Helping Hand
    Rank: Community Hero

    Would not recommend solutions using AppActivate and SendKeys, especially if anyone can interact with the system. Have you considered a browser add-on that is built to refresh at the interval required:

    https://chrome.google.com/webstore/detail/auto-refresh/ifooldnmmcmlbdennkpdnlnbgbmfalko?hl=en
    https://addons.mozilla.org/en-US/firefox/addon/tab-auto-refresh/

    #198620
    joshyland67
    Participant
    Topics: 1
    Replies: 1

    Hi all,
    am trying to create a powershell Script to auto refresh some or all open pages in Google chrome and others in Firefox.
    This one only refresh 1 active page for only 1 Navigateur:

    while(1) { # Loop forever
    sleep -Seconds 3 #1 hour
    $wshell = New-Object -ComObject wscript.shell
    if($wshell.AppActivate('Chrome')) { # Switch to Chrome
    Sleep 1 # Wait for Chrome to "activate"
    $wshell.SendKeys('{F5}') # Send F5 (Refresh)
    } else { break; } # Chrome not open, exit the loop
    }
    

    Thanks for the help

    • This topic was modified 5 months, 3 weeks ago by joshyland67.
    • This topic was modified 5 months, 3 weeks ago by kvprasoon. Reason: code formatting
    Jeremiah Logan
    Participant
    Topics: 28
    Replies: 28
    I have been attempting to automate a web page (help desk form) in PowerShell with the Selenium module. I can get all different types of elements except dropdowns. I have inconsistently been able to get some of them by doing a Find-SEElement and using the -xPath, performing a click() and then doing a Find-SEElement again on the resultant drop down list, but this does not
    always work. The one I am working on at the moment looks like this:
    $User = FindSeElement Driver $chrome Timeout 30 XPath “//span[@id=’control-wrapper-mainForm-GroupBoxDesignerControl4′]//tr[1]//td[2]”
    I can confirm that I do find the element, but if I try to do anything except click on it I get the “element is not interactable” error. I was reading through some other forums, and someone suggested doing something like this:
    $User = FindSeElement Driver $chrome Timeout 30 XPath “//span[@id=’control-wrapper-mainForm-GroupBoxDesignerControl4′]//tr[1]//td[2]”
    $Value
    = ‘Joe Smith’
    $SelectElement
    = [OpenQA.Selenium.Support.UI.SelectElement]::new($User)
    $SelectElement
    .SelectByValue($Value)

    When I run this, however, I get the error “Element should have been select but was td”. Googling this I have seen a number of threads and solutions for other languages such as Python and C#, but nothing specific to PowerShell. I am just looking for a consistent syntax to be able to grab a dropdown menu and select an item from the resultant list.

    Edit: I did realize that the element is a /td, not a select, after posting, based on the XPath. The question remains, however, how to consistently grab the dropdown menu and then select a value. I have done it like this (different element name but shows same issue):

    $taskLink = Find-SeElement -Driver $chrome -Timeout 30 -Wait -XPath "//li[contains(text(),'Add Task')]"
    Invoke-SeClick -Element $taskLink -Driver $chrome
    $taskDropdown = Find-SeElement -Driver $chrome -Timeout 60 -XPath "//div[@id='mainForm-_SupportGroup-Dropdown']//div[4]"
    [System.Windows.Forms.SendKeys]::SendWait('hosting');

    And it works, but not if I were to try and run this as a scheduled task due to the Windows SendKeys call

    #173263
    ofergenat
    Participant
    Topics: 6
    Replies: 15

    Hi all,

    I am rewriting my script that used the com object InternetExplorer.Application to login, navigate, find elements (links) in page source. So now I am using selenium module to work with FireFox driver to do the same.

    I have reached a point where I am able to do the login and navigate, I just can’t find a way to convert the page source (HTML string) into an object that I can filter by tag name and class and select hrefs.

    I found an example at a website that I could create a com object of HTML and write the page source so I would get a DOM object, however it still doesn’t work when I try to look for ‘a’ tags there nothing found, like this data was not added to the object.

    I need your help converting a page source (HTML string) into an object that I can work with.

    Here is the sample code which uses ‘selenium’ module:

    $PSCred = Get-Credential
    $FFDriver = Start-SeFirefox
    $FFDriver.Navigate().GoToURL('https://login.somewebsite.com/')
    $FFDriver.FindElementByName('email').sendkeys($PSCred.Username)
    $FFDriver.FindElementByName('password').sendkeys($PSCred.GetNetworkCredential().password)
    $FFDriver.FindElementByName('password').submit()
    Start-Sleep -Seconds 3
    $FFDriver.Navigate().GoToURL('https://www.somewebsite.com/aaa/bbb/')
    $FFDriver.Title
    $Source = $FFDriver.PageSource
    # Create HTML file Object
    $HTML = New-Object -ComObject "HTMLFile"
    # Write HTML content according to DOM Level2
    $HTML.IHTMLDocument2_write($Source)
    $LinkElements = $HTML.getElementsByTagName('a') | where{$_.href -like "$xxx*"} | where{$_.className -eq 'xxx'}
    
    # cleanup
    Remove-Variable -Name PSCred
    $FFDriver.Close()
    $FFDriver.Quit()
    $FFDriver.Dispose()
    
    
    #168157
    Participant
    Topics: 2
    Replies: 1013
    Points: 2,093
    Helping Hand
    Rank: Community Hero

    What are you asking here?

    8 separate monitors and tiled does not make since. If you have 8 windows open and 8 monitors to use, are you saying, you want each window on one of each monitor?

    Tiled, means you want them on one monitor, then you’d call windows proper to tile / cascade windows feature not use sendkeys stuff.

    For example:

    How Can I Tile the Windows on the Desktop?

     

     

    #167995
    Tony Antony
    Participant
    Topics: 74
    Replies: 167

    I have a script to open 8 windows using VNC viewer (for seeing screens from computer).  This works fine.  After the script runs and I have the 8 windows open, I have to manually snap them to the monitors so they look tiled.  Is there a way to resize a window and move it using powershell?

    This is what I have so far.  This just opens the 8 screens using TightVNC Viewer.

    $laptops = '172.16.2.88', '172.16.1.145', '172.16.2.75', '172.16.2.87',
    '172.16.2.84', '172.16.2.83', '172.16.2.79' , '172.16.2.77'
    
    $wshell = New-Object -ComObject wscript.shell;
    
    foreach ($l in $laptops) {
    Start-Process -FilePath 'C:\Program Files\TightVNC\tvnviewer.exe'
    sleep 2
    $vlc = Get-Process -Name tvnviewer
    sleep 1
    $wshell.SendKeys($l)
    Write-Host "Using VNC for" $l -ForegroundColor Green
    sleep 1
    $wshell.SendKeys('~')
    sleep 1
    $wshell.SendKeys('12345')
    sleep 1
    $wshell.SendKeys('~')
    sleep 1
    }
    #146229
    Participant
    Topics: 2
    Replies: 1013
    Points: 2,093
    Helping Hand
    Rank: Community Hero

    As for …

    How to close currently open particular notepad

    … what does this mean to you?

    All opened or the current one that has focus / in the foreground (which is almost impossible to do BTW – even if you check by StartTime).

    As noted by ‘js’, that is a way to get the isolated instance by that name. Yet, you can do a bit more.
    Use what ‘js’ gave, but you need to know what else you need to pull and there really is not much else useful for what you are after. The most relevant is the below.

    Get-Process -Name Notepad | 
    Select Name, MainWindowTitle, Responding, StartTime
    
    Name    MainWindowTitle        Responding StartTime
    ----    ---------------        ---------- ---------
    notepad Untitled - Notepad           True 3/22/2019 11:02:38 AM
    notepad Untitled - Notepad           True 3/22/2019 11:16:57 AM
    notepad TestFile.txt - Notepad       True 3/22/2019 11:35:21 AM
    

    So, you check for all titles that are either ‘Untitled – Notepad’ or ‘named’.
    Of course, named means the file has been saved at least once.

    However, for those, ‘Untitled – Notepad ones, you may want to check for content before closing it, as the user may not yet have had time to save it. Thus you need to save it for them with some name that you report back to them so that can find it again.

    So, anything with a name, save. Anything else should be checked and saved with say a timestampe and the close. The automation of this as pointed out by Olaf, use AutoIT, or you can use SendKeys. They later is a bit more quirky (timing, etc.), especially if any of these are minimize, and SendKeys chokes until you restore or maximize those windows.

    So here is how I’ve handled such use cases, but again, it can get really quirky. No guarantees at all from system to system you would target with it.

    ### Automating notepad checks
    
    Clear-Host
    
    Function Set-WindowStyle 
    {
        param
        (
            [Parameter()]
            [ValidateSet('FORCEMINIMIZE', 'HIDE', 'MAXIMIZE', 'MINIMIZE', 'RESTORE', 
                         'SHOW', 'SHOWDEFAULT', 'SHOWMAXIMIZED', 'SHOWMINIMIZED', 
                         'SHOWMINNOACTIVE', 'SHOWNA', 'SHOWNOACTIVATE', 'SHOWNORMAL')]
            $Style = 'SHOW',
            [Parameter()]
            $MainWindowHandle = (Get-Process -Id $pid).MainWindowHandle
        )
    
        $WindowStates = @{
            FORCEMINIMIZE   = 11; HIDE            = 0
            MAXIMIZE        = 3;  MINIMIZE        = 6
            RESTORE         = 9;  SHOW            = 5
            SHOWDEFAULT     = 10; SHOWMAXIMIZED   = 3
            SHOWMINIMIZED   = 2;  SHOWMINNOACTIVE = 7
            SHOWNA          = 8;  SHOWNOACTIVATE  = 4
            SHOWNORMAL      = 1
        }
        Write-Verbose ("Set Window Style {1} on handle {0}" -f $MainWindowHandle, $($WindowStates[$style]))
    
        $Win32ShowWindowAsync = Add-Type –memberDefinition @” 
        [DllImport("user32.dll")] 
        public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    “@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru
    
        $Win32ShowWindowAsync::ShowWindowAsync($MainWindowHandle, $WindowStates[$Style]) | Out-Null
    }
    
    
    
    [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms") | Out-Null
    
    
    Get-Process -Name Notepad | 
    ForEach {
        If($PSItem.MainWindowTitle -NotMatch 'Untitled')
        {
            "The process $($PSItem.MainWindowTitle) with start time of $($PSItem.StartTime) has been saved at least once."
            'Saving the file in its current state to the current working directory.'
            Set-WindowStyle RESTORE $PSItem.MainWindowHandle
            [Microsoft.VisualBasic.Interaction]::AppActivate($PSItem.ID)
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%(fs)")
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%{F4}")
            "`n"
        }
        Else
        {
            Write-Warning -Message "
            The process $($PSItem.MainWindowTitle) with start time of $($PSItem.StartTime) is not saved.
            Saving the file using the title and start time to the current working directory."
            Set-WindowStyle RESTORE $PSItem.MainWindowHandle
            [Microsoft.VisualBasic.Interaction]::AppActivate($PSItem.ID)
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("%(fa)")
            Start-Sleep -Seconds 2
            [System.Windows.Forms.SendKeys]::SendWait("$((($PSItem.MainWindowTitle) -split '-')[0])$(($PSItem.StartTime).ToString('[email protected]'))")
            Start-Sleep -Seconds 3
            [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
            [System.Windows.Forms.SendKeys]::SendWait("%{F4}")
            "`n"
        }
    }
    
Viewing 15 results - 1 through 15 (of 52 total)