Search Results for 'sendkeys'

Welcome Forums Search Search Results for 'sendkeys'

Viewing 15 results - 16 through 30 (of 45 total)
  • Author
    Search Results
  • #104285
    Participant
    Topics: 5
    Replies: 7
    Points: 0
    Rank: Member

    I am having a very specific issue with scheduling a PowerShell script to run with Task Scheduler in Windows 2012 server. The script works as expected from the PowerShell ISE console. The script is checking the size of C:\ and a particular log folder size and if the log folder size is more than 20 GB then it clears the logs of the folder with the help of application.

    The stop application stops 3 of the particular services and while starting the start application undergoes a interactive session with CMD and if we press y and enter , it will clear the logs and start those 3 services.

    Then it will send the mail the output.

    The issue is, if i start the script from powershell console it complete successfully as expected but if i do the same from task scheduler then only the start application is not executing and the task is getting completed with stop application and sending the mail. The middle part is not happening.

    $cdrive = $NULL
    $percentage = $NULL
    $freespace = $NULL
    $size = $NULL

    $cdrive = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size = [math]::Round($cdrive.Size/1GB,0)
    $freespace = [math]::Round($cdrive.FreeSpace/1GB,0)
    $percentage = [math]::Round($cdrive.FreeSpace/$cdrive.Size * 100,0)

    if($percentage -gt 50)
    {

    exit

    }
    else

    {
    $logsize = $NULL

    $logsize = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB,0)

    if($logsize -lt 10)

    {
    $cdrive1 = $NULL
    $percentage1 = $NULL
    $size1 = $NULL
    $freespace1 = $NULL
    $ID1 = $NULL
    Add-Type -AssemblyName 'System.Windows.Forms'
    $ID1 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Stop Services' -PassThru).Id
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID1)
    Sleep 90
    [System.Windows.Forms.SendKeys]::SendWait("~")

    sleep 20
    this below start function only not executing.
    #*****************************************************************************
    $ID2 = $NULL
    #Add-Type -AssemblyName 'System.Windows.Forms'
    $ID2 = (Start-Process 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Hewlett Packard Enterprise\HPE XP7 Performance Advisor Management Station\Start Services' -PassThru).Id
    sleep 10
    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID2)
    sleep 10
    [System.Windows.Forms.SendKeys]::SendWait("y~")
    sleep 30
    [System.Windows.Forms.SendKeys]::SendWait("~")
    #*********************************************************************************

    $cdrive1 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"
    $size1 = [math]::Round($cdrive1.Size/1GB,0)
    $freespace1 = [math]::Round($cdrive1.FreeSpace/1GB,0)

    $percentage1 = [math]::Round($cdrive1.FreeSpace/$cdrive1.Size * 100,0)

    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "abc@.com"
    $EmailTo ="abc@.com"
    $MyReport = @"

    Script has cleared the HP performance unused logs from the path C:\HPE\HPSS\pa\tomcat\logs and below is the output of C: drive.

    Before log deletion
    **************
    C: Total size in GB = $size
    C: Freespace in GB = $freespace
    C: Freespace in % = $percentage

    After Log Deletion
    **************
    C: Total size in GB = $size1
    C: Freespace in GB = $freespace1
    C: Freespace in % = $percentage1
    "@

    Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV

    }
    else

    {
    $cdrive2 = $NULL
    $percentage2 = $NULL
    $cdrive2 = gwmi win32_logicaldisk -Filter "DeviceId='C:'"

    $percentage2 = [math]::Round($cdrive2.FreeSpace/$cdrive2.Size * 100,0)
    $logsize1 = $NULL

    $logsize1 = [math]::Round((Get-ChildItem C:\HPE\HPSS\pa\tomcat\logs -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB,0)
    $SMTPSRV = "xyz.abc.net"
    $EmailFrom = "xyz.abc.net"
    $EmailTo ="xyz.abc.net"
    $MyReport = @"

    C: drive freespace is < 50% but the HP Performance log folder "C:\HPE\HPSS\pa\tomcat\logs" is not occupied more than 10GB. Current size of the log folder is $logsize1 MB. "@ Send-MailMessage -To $EmailTo -Subject "HP Performance advisor log status" -From $EmailFrom -Body $MyReport -SmtpServer $SMTPSRV } }

    #104105
    Participant
    Topics: 2
    Replies: 1001
    Points: 2,008
    Helping Hand
    Rank: Community Hero

    As for...

    If I run this in Powershell ISE it will pop up to the front of the screen like I would expect.

    It should, because these are two different apps that are being ran. The ISE is of course PowerShell_ise.exe, the console window in the ISE is not a real ConsoleHost. When you run code in the ISE, it actually spawn a PowerShell.exe instance to run it and that is separate from the powershell_ise.exe instance all the while returning the output back to the ISE console. Hence why it can come to the front.

    In VSCode, the code is run as a child process. Hence not coming front. You can see this in Get-Process in both tools.

    When you do this in the ISE, you will see a single powershell_ise.exe process.
    When you run the code in the ISE, and do Get-Process again, you will see a new powershell.exe process.

    When you run VSCode, you will see several powershell.exe processes. One for the start of VSCode (default ConsolHost) and the other for when you start the Editor which triggers the 'PowerShell Integrated Console – Visual Studio Code Host'.

    # VSCode

     
    Get-Process -Name '*powershell*'
    
    Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
    -------  ------    -----      -----     ------     --  -- -----------
        590      28    83808      93452       1.09     32  26 powershell
        728      43   140340     139116       3.86   6840  26 powershell
    

    If you open TaskManager, you'll see only one VSC task, but expand that and you'll see double digit child processes, depending on what you loaded up.

    The VSCode console dropdown will show the number of powershell.exe process are running in the parent process. So, at the start and a blank editor / pane, there will be two. The moment you run this code in the Editor, it will spawn a third powershell.exe instance. If you open TaskManger you will see the VSC process until you expand it and see all the child processes.

     Get-Process -Name '*powershell*'
    
    Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
    -------  ------    -----      -----     ------     --  -- -----------
        584      28    83696      93408       1.19     32  26 powershell
        626      31    85092      95592       1.14   6544  26 powershell
       1246      71   328936     349968      16.95   6840  26 powershell
    

    Also, if you look at the bottom right of the VSC console, you will see the work PowerShell with a spinning icon to the left of it. This means that the parent editor (which itself seems to be model) is running the new PowerShell instance and in a model dialog box thus behind the parent. However, if you go back to TaskManager, you'll see a separate 'Windows PowerShell' task running.

    So, in order for you to bring this to the front, you have to minimize the VSCode window. You can do this in your code. Yet, this just means you have to click the taskbar icon (or ALT+TAB) to bring the VSCode window back up to work on your code again. Otherwise you are going to have to write additional code to try and grab that process and make it active. That is a bit more of a challenge, especially for model dialog boxes. Been there, done that, not successful.

    So, when I do this sort of thing like you are, I just minimize VSC...

        Function Get-FileName($initialDirectory)
        {   
            [system.reflection.assembly]::loadwithpartialname("System.Windows.Forms")
            [System.Windows.Forms.SendKeys]::Sendwait("% {n}")
    
            [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
            Out-Null
    
            $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog 
            $OpenFileDialog.initialDirectory = $initialDirectory
            $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
            $OpenFileDialog.ShowDialog() | Out-Null
            $OpenFileDialog.filename
            $OpenFileDialog.ShowHelp = $true
        } #end function Get-FileName
    
        Get-FileName -initialDirectory D:\Temp
    

    … and work with my dialogs, and ALT+TAB to maximize VSC when done.

    Even using the above, sometimes it will minimize to show the dialog behind, other times it will bring the dialog to the front, depending on what other screens / dialogs I had up at the time. I have a 4 monitor setup with many items up at once.

    Otherwise, I write my code, save the file and shell-out, so as to not have to minimize VSC. Both at not the best experience, but it is what it is. Well, unless someone else tells me I am smoking something, that is causing my in ability to accomplish this. 8^}

    I also spent a good bit of time VSC editor settings and PowerShellEditorServices for a fix, no luck.

    #96584
    js
    Participant
    Topics: 27
    Replies: 739
    Points: 2,015
    Helping Hand
    Rank: Community Hero

    After putting the missing spaces in:

    Function Set-Speaker($Volume){$wshShell=new-object -com wscript.shell;1..50|%{$wshShell.SendKeys([char]174)};
    1..$Volume|%{$wshShell.SendKeys([char]175)}}
    

    This seems to be the way to do it (https://stackoverflow.com/questions/15979445/run-a-local-function-on-a-remote-computer), but it didn't work for me. I even tried installing the script remotely.

    invoke-command comp001 ${function:set-speaker} -ArgumentList 10
    
    #96384
    rubi12
    Participant
    Topics: 1
    Replies: 1

    Hi,

    I would like to run the following power shell script on a remote computer

    FunctionSet-Speaker($Volume){$wshShell=new-object-comwscript.shell;1..50|%{$wshShell.SendKeys([char]174)};1..$Volume|%{$wshShell.SendKeys([char]175)}}

    Set-Speaker – Volume 10

    I have tried to use the Invoke command without success, any suggestions on how to make it work on a remote computer?

    Kevin
    Participant
    Topics: 4
    Replies: 0

    I want to have a script log into Jenkins automatically. Using I.E. I have inspected some elements to create a PowerShell script to do almost everything that I want it to do. My script will launch I.E. and fill out the username and password correctly. How do I get the "Login" button to be clicked? I would rather not use SENDKEYS.

    Here is my script:

    $username = "jdoe";
    $password = "strongpassword";
    $loginUrl = "http://jenkinsserver:8080/"

    $ie = New-Object -com internetexplorer.application;
    $ie.visible = $true;
    $ie.navigate($loginUrl);
    while ($ie.Busy -eq $true) { Start-Sleep -Seconds 1; } #wait for browser idle

    ($ie.document.getElementsByName("j_username") | select -first 1).value = $username;
    ($ie.document.getElementsByName("j_password") | select -first 1).value = $password;
    ($ie.document.getElementsByName("login") | select -first 1).click();

    #88292
    Participant
    Topics: 2
    Replies: 1001
    Points: 2,008
    Helping Hand
    Rank: Community Hero

    This has been possible ever since the VBScript days.
    It's called SendKeys, though it does get panned by many over the years. I've had no real issues in using it.

    In PowerShell, it is just doing this.. Say, some Windows UI

    ### Start PowerUser Menu
    [void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
    [System.Windows.Forms.SendKeys]::SendWait("^{ESC}+X")

    A quick search using your favorite search engine, using the strings

    'VBScript SendKeys'
    'PowerShell SendKeys'

    ... Will provide you a long list of articles to choose from.

    Also take a look at the WASP module, here:
    'wasp.codeplex.com'

    #76647
    Dimitri
    Participant
    Topics: 1
    Replies: 1

    Hello friends, how are you? πŸ™‚
    Please see if you can help me ... I use Posh-ssh to manage Mikrotik routerboards and it works perfectly. However now I want to
    Also automate configuration of switches (in my scenario, they are all
    HP 2530-24G). I can connect normally via posh-ssh (it appears in the
    Log switch as logged), however, any command I try
    Invoking it does not recognize ... I believe it is by the following: – In that
    Swich template, when I log in for the first time, it is necessary to press the
    Enter to be able to fully start the session .... However I do not know how
    Invoking this command by posh / powershell .... do you have any ideas?
    I found something in this sense but I do not know how to use:

    # $ Test = new-object -c wscript.shell
    # $ Test.sendkeys ("{ENTER}")

    Note: I am invoking the commands as follows:

    Invoke-SSHCommand -Command "system-view" -SessionId 0
    #70805
    Del
    Participant
    Topics: 22
    Replies: 19
    Points: 0
    Rank: Member

    You're correct. I tried to invoke the SendKeys didn't work on all of the AD machines.
    Instead I used "InteropServices"; interface "IAudioEndpointVolume" and It works πŸ™‚

    As for Mic. I found some good C# examples ..

    #70735
    Keymaster
    Topics: 13
    Replies: 4872
    Points: 1,896
    Helping HandTeam Member
    Rank: Community Hero

    So, because I know there's no PowerShell command for this, I searched ".NET record microphone". You might try that – there are some good examples. You're going to need to translate from C# or VB, because you're basically going to be coding .NET.

    FWIW, I also searched ".net set volume" and got some good results, which might give you something more reliable than that SendKeys approach you're using. That's almost 20 years old and isn't going to be reliable across a lot of different systems.

    Del
    Participant
    Topics: 22
    Replies: 19

    I'm working on a script, to go and unmute the speaks on a local or remote computer, send a message using [Speech] Class
    I'll show you the code below. But I was wondering if it's possible to use PowerShell to capture a (Record) Microphone input ??

    # Set Speaker function
    Function Set-Speaker($Volume) {
    $wshShell = new-object -com wscript.shell;1..50 | % {$wshShell.SendKeys([char]174)};1..$Volume | %{$wshShell.SendKeys([char]175)}}
    Set-Speaker -Volume 50
    #
    Invoke-Command -ComputerName $PC -scriptblock {

    Add-Type -AssemblyName System.speech
    $talker = New-Object System.Speech.Synthesis.SpeechSynthesizer
    $talker.speak("Hi there .. Your your password expires today. Please change your password now")
    }

    #67303
    Ian Hicks
    Participant
    Topics: 1
    Replies: 0

    I've been working on this script and it works on my PC but I am positive it can be broken if the timing is changed slightly.

    The first problem is I can't figure out how to sendkeys to the program in order to make it start running and simultaneously keep the program from closing via the /w or | out-null commands. When I try to add the out-null lines the script will still close the app before it is done running.

    The 2nd issue is that I have inserted pauses in order to navigate the apps via sendkey commands but obviously this is gonna cause a problem if the app run speed varies even slightly.

    So yeah..... I am sure there are other problems that will arise but these are the two I can see right now. Any advice would be greatly appreciated. Thank you.

    & start "C:\program.lnk"
    sleep 1
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate('C:\program.lnk')
    Sleep 1
    $wshell.SendKeys('{right}')
    Sleep 1
    $wshell.SendKeys('~')
    Sleep 1
    $wshell.SendKeys('{right}')
    Sleep 1
    $wshell.SendKeys('~')
    sleep 5
    get-process program | %{ $_.closemainwindow() }
    & start "C:\program.lnk"
    Sleep 3
    $wshell.SendKeys('~')
    sleep 5
    get-process program | %{ $_.closemainwindow() }
    $wshell.SendKeys('{right}')
    Sleep 3
    $wshell.SendKeys('~')
    & start "C:\program.lnk"
    sleep 3
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.AppActivate('C:\program.lnk')
    sleep 1
    $wshell = New-Object -ComObject wscript.shell;
    $wshell.SendKeys('{tab}')
    sleep 1
    $wshell.SendKeys('{tab}')
    sleep 1
    $wshell.SendKeys('{tab}')
    sleep 1
    $wshell.SendKeys('{tab}')
    sleep 1
    $wshell.SendKeys('~')
    sleep 1
    $wshell.SendKeys('~')
    sleep 200
    get-process program | %{ $_.closemainwindow() }
    sleep 2
    & start "C:\program.lnk"
    $wshell = New-Object -ComObject wscript.shell;
    sleep 10
    $wshell.SendKeys('~')
    sleep 10
    $wshell.SendKeys('~')

    Kevin
    Participant
    Topics: 4
    Replies: 0

    I am using System.Windows.Forms and New-Object to have a pop up GUI from my PowerShell script. The pop up often appears behind the PowerShell ISE window. It is hidden this way. Is there a trick to make it always come to the front? I was thinking of using SendKeys. But I want other users to use it. There is no telling where they might click. I might be able to do something with SendKeys. But I think someone else has encountered this problem before.

    #59148
    Participant
    Topics: 0
    Replies: 61
    Points: -11
    Rank: Member

    Hi

    I'm not any means expert on SendKeys so I don't comment on that, but I would recommend to save and get the password otherwise. Seems that the password is now in plain text in that .txt file.

    Also if you want to "save some time" move the $executable inside the if so it would only be executed when needed. Also I would change all "Outlook" text to $process so when you change $process you don't need to type those into the subject and body etc.

    One approach to this could be also Try Catch Finally, where you could try if it is running then do what you need to do and in Catch you'll do what you'll need to do when it is not running and if needed add Finally where you could always send mail/make log files what has happened. Of course if mail send is only wanted when it is not running then add it to Catch and skip Finally, or make logging there has it been running or not.

    Jake

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

    Alright, well this is to check for a process, if its not running, start it, and in one case, automatically log into the software. I've managed to cobble this together by googling and its my first effort at doing anything at all in PowerShell. On the plus side, it works exactly as I want it, I was just wondering if there are any possible undesirable effects this might have.

    You'll have to forgive the mass of sendkeys, there was no other way of getting it to run the program via a launcher. If I ran the executable directly it would start but be unresponsive to input so I was forced to navigate the launcher and start the software from there.

    $process = "TheProgram"
    $check = Get-Process $process
    
    if(!($check)) {
    
    add-type -AssemblyName System.Windows.Forms
    
    $encrypted = get-content C:\cred.txt
    $user = "UserName"
    $Password = ConvertTo-SecureString -string $encrypted
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $Password
    ConvertFrom-SecureString $Password
    $NonSecure = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
    
    #Unfortunately I didn't know of a way to make powershell interact directly with the software, the provider "doesnt support powershell" and wouldnt help me
    #So the below is a set of keystrokes with as little time as possible between them to allow for windows to load and such
    
    Invoke-Item "C:\Program Files\TheFile\WithTheProgram\LauncherExecutable.exe"
    start-sleep -Seconds 2
    
    [System.Windows.Forms.SendKeys]::SendWait(β€œ{Right}{Right}”)
    Start-Sleep -Seconds 1
    
    [System.Windows.Forms.SendKeys]::SendWait(β€œ(+{F10})”)
    Start-Sleep -Seconds 1
    
    [System.Windows.Forms.SendKeys]::SendWait(β€œ{R}{Enter}”)
    Start-Sleep -Seconds 8
    
    [System.Windows.Forms.SendKeys]::SendWait(β€œ$user{Tab}$NonSecure{Enter}”)
    Start-Sleep -Seconds 10
    
    [System.Windows.Forms.SendKeys]::SendWait(β€œ{Enter}”)
    
    #With an email message to the IT Dept stating that the program needed relaunching
    
    Send-MailMessage -From "The Automated PC" -To "IT Dept" -Subject "TheProgram has been restarted" -Body "TheProgram was not running on MachineName and has been restarted." -SMTP "mail.com"
    }
    
    #Then more of the same with outlook
    #Although the $check variable is identical to above the script broke if it wasn't redefined here for the next section though I have no idea why
    
    $process = "outlook"
    $check = Get-Process $process
    $executable = "C:\Program Files (x86)\Microsoft Office\Office14\outlook.exe"
    
    if(!($check)) {
    Start-Process $executable
    
    Send-MailMessage  -From "The Automated PC" -To "IT Dept" -Subject "Outlook was restarted" -Body "Outlook was not running on MachineName and has been restarted." -SMTP "mail.com"
    }
    #57233
    Participant
    Topics: 2
    Replies: 4
    Points: 0
    Rank: Member

    Ok, I found a work around. The best way for me to paste at the cursor location is to send the CTRL+v keys directly. Here is a MWE. Thank you again for your help!

    # Load System.Windows.Forms to use SendKeys
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    
    # Copy some text to the clipboard
    "Testing again: 1, 2, 3..." | clip.exe
    
    # Delay for 2 seconds while moving the cursor
    Start-Sleep -s 2
    
    # Paste using CTRL+v 3 times just for verification
    [System.Windows.Forms.SendKeys]::SendWait("^{v}") 
    [System.Windows.Forms.SendKeys]::SendWait("^{v}") 
    [System.Windows.Forms.SendKeys]::SendWait("^{v}") 
    
    # Finish up with the command window
    Write-Host "Done!"
    Read-Host "Press enter to close this window..."
    
Viewing 15 results - 16 through 30 (of 45 total)