Search Results for 'sendkeys'

Welcome Forums Search Search Results for 'sendkeys'

Viewing 12 results - 31 through 42 (of 42 total)
  • Author
    Search Results
  • Keymaster
    Topics: 13
    Replies: 4872
    Points: 1,870
    Helping HandTeam Member
    Rank: Community Hero

    PowerShell doesn't have an equivalent to SendKeys, and isn't really designed for GUI automation. PowerShell also isn't a web browser; sites that are intended only for interaction with a web browser aren't going to be easy to automate.

    You'll need to learn a bit about HTTP (which is beyond what this forum is about). It's possible that the web page you're attempting to access is sending an HTTP auth request. The browser handles that by displaying the dialog; in PowerShell, you could just send the HTTP auth response instead of using a dialog. But I don't want to imply that this is simple; you're basically re-building part of what a web browser is and does. It's potentially complex, and PowerShell might not be the best language for it.

    #32639
    Participant
    Topics: 1
    Replies: 302
    Points: 145
    Helping Hand
    Rank: Participant

    I was having a think about this and figured that you could probably 'hit' F12 with SendKeys. I had a problem changing the focus of the Window but this stackoverflow post helped there. Does this help at all?

    Add-Type @"
      using System;
      using System.Runtime.InteropServices;
      public class Tricks {
         [DllImport("user32.dll")]
         [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetForegroundWindow(IntPtr hWnd);
      }
    "@
    
    $ie = Start-Process iexplore.exe -PassThru | Get-Process
    
    [void][Tricks]::SetForeGroundWindow($ie.MainWindowHandle)
        
        Start-Sleep -Seconds 2
    
    [System.Windows.Forms.SendKeys]::SendWait("{F12}")
    
    #28650
    Participant
    Topics: 9
    Replies: 1277
    Points: 1,051
    Helping Hand
    Rank: Community Hero

    If you are using SendKeys as a solution, it is most likely the wrong solution. In vbScript forums, I used to continually talk folks out of using it because there is no way to ensure the script is doing what it's supposed to. You're sending commands blindly to the screen and assuming that the Window you expect opened and is active when you are sending commands.

    With that said, there is a programmatic way to manage hiding windows updates. Take a look at this article: http://www.powershellmagazine.com/2014/03/19/how-to-view-and-restore-hidden-windows-updates-with-powershell/

    I used to create the below that hides the annoying Windows 7 language packs in my labs:

    Function Get-WindowsUpdate {
     
        [Cmdletbinding()]
        Param()
     
        Process {
            try {
                Write-Verbose "Getting Windows Update"
                $Session = New-Object -ComObject Microsoft.Update.Session            
                $Searcher = $Session.CreateUpdateSearcher()            
                $Criteria = "IsInstalled=0 and DeploymentAction='Installation' or IsPresent=1 and DeploymentAction='Uninstallation' or IsInstalled=1 and DeploymentAction='Installation' and RebootRequired=1 or IsInstalled=0 and DeploymentAction='Uninstallation' and RebootRequired=1"           
                $SearchResult = $Searcher.Search($Criteria)           
                $SearchResult.Updates
            } catch {
                Write-Warning -Message "Failed to query Windows Update because $($_.Exception.Message)"
            }
        }
    }
     
    Function Show-WindowsUpdate {
        Get-WindowsUpdate |
        Select Title,isHidden,
            @{l='Size (MB)';e={'{0:N2}' -f ($_.MaxDownloadSize/1MB)}},
            @{l='Published';e={$_.LastDeploymentChangeTime}} |
        Sort -Property Published
    }
    
    Function Set-WindowsHiddenUpdate {
     
        [Cmdletbinding()]
     
        Param(
            [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
            [System.__ComObject[]]$Update,
     
            [Parameter(Mandatory=$true)]
            [boolean]$Hide
        )
     
        Process {
            $Update | ForEach-Object -Process {
                if (($_.pstypenames)[0] -eq 'System.__ComObject#{c1c2f21a-d2f4-4902-b5c6-8a081c19a890}') {
                    try {
                        $_.isHidden = $Hide
                        Write-Verbose -Message "Dealing with update $($_.Title)"
                    } catch {
                        Write-Warning -Message "Failed to perform action because $($_.Exception.Message)"
                    }
                } else {
                    Write-Warning -Message "Ignoring object submitted"
                }
            }
        }
    }
    
    $updates = Get-WindowsUpdate
    $updates | Where{$_.Title -like "*language*" -and $_.IsHidden -eq $false} | Set-WindowsHiddenUpdate -Hide $True
    
    #28647
    Nathan Combs
    Participant
    Topics: 1
    Replies: 0

    I am almost finished with my script that gets rid of certain windows updates and hides them but after an unistall it asks if you want to restart I cannot seem to get my

    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate('Windows Update Standalone Installer')
    Sleep 2
    $wshell.SendKeys('~')

    could I put two keys one to tab and one to enter? maybe an IF statement to say if true for unistalling then hit these two keys? I am newer to this so I don't have advanced skills for powershell. Thanks!

    #23079

    In reply to: SendKeys

    Participant
    Topics: 1
    Replies: 1
    Points: 0
    Rank: Member

    Great topic! While I'm out digging on my own, I'm hoping you can point towards the modules/functions that would allow me to write to the console command line.
    (I'm trying to build a facility to allow recall and editing of previous commands. I have a version working with SendKeys, but it is pretty wobbly with almost all shifted keystrokes — '$', for instance.)

    Thanks —

    #22190

    In reply to: Send Key Question

    Participant
    Topics: 4
    Replies: 262
    Points: 61
    Rank: Member

    Hi Vincent,

    It's possible to use send keys for the first two operations you describe. Take a look at the thread on this forum for some examples. https://powershell.org/forums/topic/sendkeys/
    For the third....hmm depending on your operating system, it may also be possible to use your NumberLock keys, but this can be pretty specific. In other circumstances you would probably need to enable the Ease of Access to specifically use the keyboard.
    For fourth, not certain on specific coords, and bear in mind these will always be relative to the screen resolution. As such you'll never be able to ensure you're actually clicking on the right location. You could use SendKeys in combination with some API functions to try and activate the specific window, and then activate the specific control before using SendKeys to simulate the click.

    You can get additional information about SendKeys, take a look at the MSDN article, which describes the keyboard combinations. https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys%28v=vs.110%29.aspx

    Really though, SendKeys should be the last option you choose, you lose control of what's happening and have just got to hope it's going to work.

    What's the intended purpose?

    #21977

    In reply to: SendKeys

    Participant
    Topics: 4
    Replies: 262
    Points: 61
    Rank: Member

    I'm happy to give extra information on the script if you want on it mate,no worries.

    I'm been playing around with SendKeys for the last 15 minutes or so, and experiencing exactly the same situation. It almost seems like ALT is not processed at all. The SendKeys equivalent of ALT+SPACE does not work for example. Also tried it with .NET's [System.Windows.Forms.SendKeys]::Send method and get similar results.

    All I can think of at the moment is that the behavior is different at some level because it is command line based. In vbscript previously for example, you would normally use cscript.exe for running vbs files within a command prompt session, and wscript.exe for form based apps. Thats me just thinking aloud there though, nothing to confirm this is why.

    Will keep digging though, it's an interesting one. 🙂

    #21967

    In reply to: SendKeys

    Inactive
    Topics: 29
    Replies: 32
    Points: 0
    Rank: Member

    Hi Tim Pringle,
    That was a mind blowing job. Honestly I am in vain to understand the code but you given is the perfect solution of my requirement and that worked fine for me.
    But still I am not clear why "$wshShell.SendKeys("% x")" is not working for powershell.exe (but fine for ISE)? any reason?

    #21956

    In reply to: SendKeys

    Participant
    Topics: 4
    Replies: 262
    Points: 61
    Rank: Member

    Hey Vidya,

    SendKeys is really best left as a last resort when all else fails. Mention of it has been known to cause some programmers and scripters to collapse in shock at hearing such bad language. 😉

    It's a bit more involved than using SendKeys, but the Win32API has several funtions we can combine to achieve this. I've put together a couple of cmdlets that can be combined to get what you need. Run them, and you can then use the cmdlet like the example below.

    What it does is get the MainWindowHandle value for the process you specify from Get-Process. This is then fed into the two API functions, which perform the operations required. First, it brings the window to the front, and then maximizes it. You can find out a bit more about these functions on MSDN.

    It will fail for if you specify a process to the cmdlet that has more than one instance open (e.g. notepad running twice), but you can easily add extra validation for this if you want to take that into account.

    Example use :

    Set-WindowMaximized -Name notepad
    
    Function Get-Hwnd
    {
      [CmdletBinding()]
        
      Param
      (
        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string] $ProcessName
      )
        
      Process
      { $ErrorActionPreference = 'Stop'
        Try 
        {
          $hwnd = Get-Process -Name $ProcessName | Select-Object -ExpandProperty MainWindowHandle
        }
        Catch 
        {
          $hwnd = $null
        }
        $hash = @{
          ProcessName = $ProcessName
          Hwnd        = $hwnd
        }
            
        New-Object -TypeName PsObject -Property $hash
      }
    }
    
    function Set-WindowMaximized
    {
      [CmdletBinding()]
        
      Param
      (
        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string] $Name
       
            
      )
        
      Process
      {
        $memberDefinition = @'
        [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll", SetLastError = true)] public static extern bool SetForegroundWindow(IntPtr hWnd);
    
    '@
    
        Add-Type -MemberDefinition $memberDefinition -Name Api -Namespace User32
        $hwnd = Get-Hwnd -ProcessName $Name | Select-Object -ExpandProperty Hwnd
        If ($hwnd) 
        {
          $onTop = New-Object -TypeName System.IntPtr -ArgumentList (0)
          [User32.Api]::SetForegroundWindow($hwnd)
          [User32.Api]::ShowWindow($hwnd, 3)
        }
        Else 
        {
          [string] $hwnd = 'N/A'
        }
    
        $hash = @{
          Process = $Name
          Hwnd    = $hwnd
        }
            
        New-Object -TypeName PsObject -Property $hash
      }
    }
    
    
    #21955

    In reply to: SendKeys

    Member
    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    Using SendKeys is always a pretty fragile operation (since it depends on the correct window having the active focus). If you do need to do some GUI automation of that sort, I'd highly recommend that you check out AutoIT sometime; it has a nice scripting language, a COM interface, and can be written to interact with specific windows and user controls without depending on keystrokes or focus.

    As far as I know, your second usage of SendKeys should be correct, so long as the window that you want to maximize has focus. It worked for me when I pasted it into a file in the ISE and ran it, at any rate (the ISE was maximized.)

    #21954
    Anonymous
    Inactive
    Topics: 29
    Replies: 32

    Hi Team,
    I wan to maximize one window by using send keys in powershell. The below code is not working. Please help me asap pls.
    **
    $wshShell = new-object -com wscript.shell
    $wshShell.SendKeys("%{space}x") #not working...

    $wshShell.SendKeys("% x") #not working... 🙁

    #5388
    Forums Archives
    Member
    Topics: 1562
    Replies: 0

    by karmista at 2013-01-01 05:54:00

    Using the below IE Application object, I am logging into a http website by providing username and password & attempting to download pdf files.
    new-object -com InternetExplorer.Application

    I have over a million files that needs to be downloaded.

    Currently, I get a "Find/ Save/ Cancel" prompt.

    How do I save the pdf file without getting this prompt?
    If the prompt cannot be avoided, there should be some way I can programatically press the save button & provide a name and save the file.
    (Sendkeys method did not work well)

    Attempted Browsers: IE 8 & IE 9

    $wshell = New-Object -ComObject WScript.Shell
    $id = (gps iexplore* | where {$_.MainWindowTitle -match "MyProg"}).id
    Write-host $id
    $wshell.AppActivate($id)
    start-sleep -milliseconds 100;
    $wshell.SendKeys("%{S}");

    by DonJ at 2013-01-01 09:22:06

    Not using PowerShell. Besides the fact that you're going through several layers to get to that COM object, it just isn't what PowerShell's designed for. If you *had* to do this with IE, I'd consider exploring AutoIt, or something else designed for that. PowerShell would want you to go down a more programmatic approach and not use IE at all. You'd create a WebRequest, feed it the URL, get the response back as a binary stream, and then write that binary stream to a file. It's a bit more complicated from a programming perspective, but it's more reliable. IE's goofy.

    http://www.codeguru.com/columns/dotnett ... lasses.htm has the basic methodology, although the code is in C# and you'd need to translate. You can also do some searching for "powershell curl" and "powershell wget" – folks have solved this before in various ways. v3 has Invoke-WebRequest, which may shortcut the process a bit if you're using v3.

    by karmista at 2013-01-02 04:52:34

    Thanks Donj!

    Will explore Invoke-WebRequest

    The C# code looks puzzling as I'm a windows server admin. PowerShell comes in naturally. 🙂

    Using powershell, I had almost got to the point where I get a save prompt. Thought if I can just get that working, it'd be perfect.
    Yes, I can use PowerShell V3 to take the advantage of its workflows as well.

    by karmista at 2013-01-02 05:04:51

    If I had a clear cut download url without any login required, I could have used the below System.Net.WebClient object.

    PS > $source = "http://www.leeholmes.com/favicon.ico"
    PS > $destination = "c:\temp\favicon.ico"
    PS >
    PS > $wc = New-Object System.Net.WebClient
    PS > $wc.DownloadFile($source, $destination)

    Source: http://answers.oreilly.com/topic/2006-h ... owershell/

    However, my scenario is:

    1) Login to a website via providing credentials in the application i.e. within the username/password text box.
    2) Post a url
    EG: http://10.12.1.12/myapp/myfile.aspx?docid=49000
    3) A standard pdf file gets generated i.e. myfile.pdf when I send this request from an authenticated IE browser session.
    4) Save this pdf

    5) Rename it to 49000.pdf [Here, 49000 is the doc id.]
    6) Repeat steps 2 to 5 a million times to download all the docs.

Viewing 12 results - 31 through 42 (of 42 total)