Тёмный

PowerShell S2E57 (sendkeys) 

Mr Automation
Подписаться 1,5 тыс.
Просмотров 8 тыс.
50% 1

(How to send keyboard input with PowerShell to any open window or application)
In this video I demonstrate a practical use case for using sendkeys in a PowerShell script. You can use sendkeys to automatically click a button, or confirm a prompt for instance.
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
[Microsoft.VisualBasic.Interaction]::AppActivate()
[System.Windows.Forms.SendKeys]::SendWait()
*powershell
*learn powershell
*automation
*learn automation
*windows
*windows powershell
*automatic installations
Code:
Demo1
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "notepad.exe"
start-sleep -Milliseconds 2500
[Microsoft.VisualBasic.Interaction]::AppActivate("Notepad")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("+{h}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{e}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{l}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{l}")
start-sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("{o}")
Demo2
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "notepad.exe"
Start-Sleep -Milliseconds 100
[Microsoft.VisualBasic.Interaction]::AppActivate("Notepad")
$line = "some line to write to notepad" #this can also come from a file or database
foreach ($c in $line.GetEnumerator()){
[System.Windows.Forms.SendKeys]::SendWait("{$c}")
Start-Sleep -Milliseconds 10
}
Demo3
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
Start-Process -FilePath "mmc.exe" -ArgumentList "compmgmt.msc"
start-sleep -Milliseconds 2500
[Microsoft.VisualBasic.Interaction]::AppActivate("Computer Management")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 3}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{RIGHT 2}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 1}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{RIGHT 1}")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{DOWN 2}")
Demo4
add-type -AssemblyName microsoft.VisualBasic
Start-Process powershell.exe -ArgumentList "D:\__DEMOS\powershell-part57\installer-hangs.ps1" -Windowstyle Hidden
start-sleep -Milliseconds 5000
[Microsoft.VisualBasic.Interaction]::AppActivate("Yes or no")
start-sleep -Milliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Installer hangs script
Add-Type -AssemblyName System.Windows.Forms
$useip = [System.Windows.Forms.MessageBox]::Show("Do you want to provide a static IP?","Yes or no",4)
if ($useip -eq "Yes"){
#$ipnumber = Read-Host "enter last octect 1-255 is valid : $network_prefix"
}
Write-Output "and now we are done"

Наука

Опубликовано:

 

7 июл 2021

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 70   
@lpgm3075
@lpgm3075 8 месяцев назад
Finally, the explanation I have been looking for while I am learning powershell! Thank you!
@mrautomation
@mrautomation 8 месяцев назад
I am glad you like it, makes it worth to create these video's. Thanks 🙂
@djust270
@djust270 2 года назад
Very cool. I already knew about WScript.Shell sendkeys method but this is more useful for sure. I will definitely put this to work.
@mrautomation
@mrautomation 2 года назад
Hi A.D.D Gamer, thanks for you comment. This script is doing the same, but in a new style. I am glad you see some value in it ;-) Wscript.Shell is what you use when writing vbs files. (Loooong time ago for me :-P)
@eechaze12
@eechaze12 3 года назад
Thanks for sharing.. Learning alot from your videos.
@mrautomation
@mrautomation 3 года назад
Hi Charles, thank you for your comment and I am very happy to hear that you learned something from my videos :-)
@shalinipandit938
@shalinipandit938 2 года назад
Thank you so much 🙏🙏🙏 your script help me a lot
@mrautomation
@mrautomation 2 года назад
Hi Shalini, I am glad to hear that it helped you 🙂
@justinrodriguez3066
@justinrodriguez3066 2 года назад
Super helpful. Thank you!!
@mrautomation
@mrautomation 2 года назад
Hi Justin. I'm glad you like it
@felipepapim
@felipepapim 3 года назад
Great Script! Thanks for sharing
@mrautomation
@mrautomation 3 года назад
I am very happy to hear that :-) And your welcome.
@redadz9105
@redadz9105 3 года назад
interessting, thanks for the video
@mrautomation
@mrautomation 3 года назад
Hi Reda, thanks for your reply and your welcome.
@ManojSingh-hl9wn
@ManojSingh-hl9wn 2 года назад
Wonderful ,Thanks Man .. :)
@mrautomation
@mrautomation 2 года назад
Hi Manoj, thanks for your message and great that you like it.
@itsupportbyharshit6285
@itsupportbyharshit6285 Год назад
Very helpful video
@mrautomation
@mrautomation Год назад
Thanks. I am glad you like it :-)
@phantomaticscience6846
@phantomaticscience6846 Год назад
you don`t need using delay.. you should check the windows is run and active ..its going to me much faster.Great video - thanks.
@mrautomation
@mrautomation Год назад
I know bro, In one of my videos (I think this one) I also mention that for each time you wish to send a key you first must activate the window, because potentially another window could be active. the sleeps are just for demo purposes so everyone can see what happens. Thanks for you comment though, much appreciated.
@MuhammadBerki
@MuhammadBerki 2 года назад
Wow didn't know powershell could do this 🤯
@mrautomation
@mrautomation 2 года назад
Hi Muhammad, Powershell can do a lot ;-) and thanks for your comment.
@mikeTomas3128
@mikeTomas3128 2 года назад
Nice, subbed
@mrautomation
@mrautomation 2 года назад
Hi Mike. Thanks 👍
@mikeTomas3128
@mikeTomas3128 2 года назад
@@mrautomation i have a request for video if it already hasn't been made. Can you make a vid about creating a script in PowerShell for a problem from absolute beginning (idea) to finish? Doesn't have to be a complicated problem or long (actually prefer it not be). My main concern is seeing your process. How you go about deciding PowerShell will work for this problem, how you explore and find the cmdlets you need, adding them to script, making it reusable for others, etc. Again whatever you have time for or feel like doing, and if there is any vids like that already please direct me to them thanks.
@mrautomation
@mrautomation 2 года назад
​ @Mike Thomas Hi, perhaps this video could help ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fGpsQ-y8Upo.html ..... But I do see your point in your request, it could certainly be interesting. I am quite sure if you browse all my video's you should be able to find some interesting video's where I start with an empty editor. When I find some time I make a video where I start with an empty editor to solve a simple problem. Thanks a lot for the idea, I am certainly going todo something with that.
@mikeTomas3128
@mikeTomas3128 2 года назад
@@mrautomation thanks for the reply. I know it is a lot to ask but thanks for at least considering. I literally found your channel yesterday so I have not had time to thoroughly go through the vids. I'll go through them and see if I can find what I'm looking for. Appreciate the help
@Pavankumar71036
@Pavankumar71036 Год назад
I am not able to do it in poweshell ide could you please explain why you used visual studio instead of powershell ISE
@mrautomation
@mrautomation Год назад
Hi Pavan, I am using visual code because I also write python code and C# (although for C# I often switch to visual studio). I am also using visual code, because the PowerShell IDE/ISE does not support newest version of PowerShell on .NET core. Sendkeys does work in ISE for sure, because I have tried it on ISE as well. ISE is for built-in powershell version which ships with Windows. I have installed powershell 7.2 myself (using /NET core), hence you need to use another editor, the built-in editor (ISE) does not support powershell 7. I hope it makes sense. If you check this link, I am using sendkeys from the ISE itself : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-eeS89X2EMek.html
@manasdash3610
@manasdash3610 13 дней назад
Demo 3: only opening "Computer Management", but not move any arrow keys nor expanding. Seems some error.
@mrautomation
@mrautomation 10 дней назад
Hi Manasdash, on my system it does work. Can't really tell why it wont work at your side. Are you debugging the code or just running it?
@ShayanKhan-tj6le
@ShayanKhan-tj6le 3 месяца назад
The video was simple, easily to follow and very helpful. Is it possible to run this in the background? For example if we want to have multiple things doing at the same time. Having this automation run in the background while playing a video game at the same time.
@ShayanKhan-tj6le
@ShayanKhan-tj6le 3 месяца назад
Is it Start-Job cmdlet?
@mrautomation
@mrautomation 3 месяца назад
Thanks for your message 🙂. You can certainly play a game in the background, but the problem with sendkeys is that it needs to activate a window by title. Which means when you are playing your game and the sendkeys kicks in, it will activate the Window by title and send keys. If you also playing a game this means that the sendkeys could send keystrokes into your game window for instance. Lots of things can be automated in different ways, sendkeys is really your last resort if there is no other mechanism to programmatically instruct what needs to be done. Do you have a specific task you want to run in the background that really needs sendkeys?
@ShayanKhan-tj6le
@ShayanKhan-tj6le 2 месяца назад
@@mrautomation Thank you for the quick response, really appreciate it. I was trying to run 2 different cmd prompts at the same time and was trying to see if it’s possible to run in parallel. But from your comment above, it seems like we can’t do that. Another question besides this, Is there a command that would only send keys when the program asks for the user input? I was thinking not to rely on the start-sleep
@mrautomation
@mrautomation 2 месяца назад
Hi @@ShayanKhan-tj6le, you are welcome. You can actually run several cmd prompts (as long as they have a unique title) and use sendkeys to send keystrokes. It is possible to accept user input, but only if the prompt has a unique title(Like in my example with the messagebox). Start-sleep is only in the code for demo purposes(so you can actually see what is happening). If you don't want to use sleep, just make sure you always activate the correct window by title and send as many keystrokes if you want without sleep. There is a tool called AUTOIT, that has its own scripting language, looks like vbscript. I am not sure if the tool is free(havent used it for at least 13 years), but that tool is really awesome to automate anything that needs user input or conformations. It could be worth checking if you really want to do advanced UI stuff in an automated fashion. I hope this helps? Kind regards Mr Automation
@starbirthcalamity
@starbirthcalamity 2 года назад
Alright, so we have the code for sending the keys... but how does one activate these scripts in the context of automation within the applications we're using them for? So, we wouldn't always open Visual Studio or Powershell while using the apps we want to automate 'cause that would eliminate the whole reason for having them, so if the scripts are made- how do we implement the scripts as we're performing our tasks? Are they triggered, do they have hotkeys to execute them, or...
@mrautomation
@mrautomation 2 года назад
Hi Starbirth, the videos that I create are often examples of functionalities that can be useful in your day to day administration tasks. To give a practical example for the sendkeys. I have used that in the past for application loadtesting. So what I did was like spin up 250 virtual machines, made sure autologin was enabled, and for that specific user that logs on to the system a powershell script launches at login. The application(s) was/were then started from the powershell script and using sendkeys to actually perform the load test for the specific application. Another example. I am also using it myself whenever I start up my own environment, like starting all the tools in need, connecting to the correct sources and such. Most of the things in Windows you can automate using powershell, but whenever it comes to clicking buttons or filling in forms, sendkeys is there to help you. I hope these 2 examples gave you an impression for the applicability of sendkeys. Kind regards Mr Automation.
@starbirthcalamity
@starbirthcalamity 2 года назад
@@mrautomation Forgive me, I didn't mean to suggest that the functions weren't useful or practical. I would absolutely love to use them, as I use software that has a disproportionate amount of confirmation windows, pop-ups, prompts, errors, and hi-fives- and automation, per usual, would save me that much time in workflow. My question intended to ask about tasks that wouldn't necessarily be large batch functions to call when initiating a task. This video definitely helps me batch logins and the like, but I was curious about smaller executables within a software after those batches would be run. An example is that if I have a software that I use on multiple devices, I can call a function to log into them simultaneously with credentials and keys, but if in that software I enter information to update a database throughout the day and the information is accompanied by a number of prompts, and those prompts change slightly depending on the kind of data I've entered, if I'm not in Powershell as I'm entering this information, how could I call or trigger a SendKey function to zip through those prompts much faster without interacting with any of them? Would you program a trigger associated with a particular window where the prompts begin, would you save them to a hot-key- therefore diminishing the fullness in automation, or would I need to find a way to build a Powershell environment from which I can interact with the software indirectly? I've been looking for a way to control my applications internally through Powershell, so if so, where to learn to do that would be appreciated as well. Thank you! (Sorry for the long text )
@mrautomation
@mrautomation 2 года назад
Hi @@starbirthcalamity, no worries :-). For your specific scenarios it seems that you perhaps need a small script or several, which always run. The script just checks if a specific prompt is open (based on title) and then answers that accordingly. Running these scripts in the background should not consume any resources if you properly design your while loops (with sleep). Another option would be to investigate AutoIT. I am not sure if its still free. But that tools is really the best there is if you need to automate UI based stuff. I have seen it being used at many customers who did not had the skills to automate application installations, they used AutoIT to click trough the installers, at least until I teached them you could just run most installers silently ;-) or with sendkeys (vbscript at that time). The tricky part with your specific usecase is that the prompt slighty change every now and then. If you cant handle that logic with code, it will be very hard to find the correct button or option with sendkeys.
@starbirthcalamity
@starbirthcalamity 2 года назад
add-type -AssemblyName microsoft.VisualBasic add-type -AssemblyName System.Windows.Forms start-sleep -Milliseconds 5000 $pic = picture-id $script = $pic.url FUNCTION PICTURE-ID ($GENDER = "MALE"){ $url = new-id | select $_.picture.large; $script = Invoke-Item "url.ps1" | Start-Sleep -milliseconds 1000 [system.Diagnostics.Process]::Start("chrome.exe") } [Microsoft.VisualBasic.Interaction]::AppActivate("Chrome") start-sleep -Milliseconds 5000 [System.Windows.Forms.SendKeys]::SendWait("{$SCRIPT}") start-sleep -Milliseconds 5000 [System.Windows.Forms.SendKeys]::SendWait("{ENTER}") What am I doing wrong? Everything runs normally up until Chrome opens- after which silence from a flashing cursor. I can't get the SendKeys to generate any action.
@itsupportbyharshit6285
@itsupportbyharshit6285 Год назад
Can you please share any url or link to learn more about this. I was trying to install an exe but it works on some systems and i am facing timing issue between sendkey event.
@mrautomation
@mrautomation Год назад
There is not much information avialable. If you have timing issues, those are often hard to fix. I know exactly what you are talking about. But still with some code and a while loop you should be able to work around these kind of problems. Make sure you activate the window first before sending a keystoke, best is to do that with every sendkey.
@quinnvanhest1077
@quinnvanhest1077 Год назад
Do you know why example 4 is not working for me, it wont type Enter but when i tried in in notepad it working?
@mrautomation
@mrautomation Год назад
Hi Quinn, Thanks for your message and sorry for late reply. Please be aware that part 4 depends on the "installer hangs script". This means you first need to run the "installer hangs script" which will open a messagebox asking you to press yes or no. When that script runs, and the messagebox is open, you will run the other piece of code that will actually select that yes/no window (messagebox window) and will simulate an ENTER keystroke which will close the application. I hope this answer helps
@grankenk9121
@grankenk9121 2 года назад
How could I send the keys win + d without using notepad?, thanks in advance!
@mrautomation
@mrautomation 2 года назад
Hi Gran, you cant do that with sendkeys, since send keys only works on a per window activation level. If you want to send a global hotkey, you probably need to import some function from [DllImport("user32.dll")]. The kinds of keystrokes you want to send can be access via native windows functions only. I don' t think there is any native .NET class that support sending global keys to the system. At least not the last time I looked at this. You probably need some C# or C++ code for sending global hotkeys to the Operating system. I hope this helps.
@KnifeEye89
@KnifeEye89 2 года назад
Very nice and educational video. Is it possible to write to a UAC prompt, auto fill user and password?
@mrautomation
@mrautomation 2 года назад
Hi Mikkel, sorry I havent responded before, I totally forgot. I am not sure if you can write to the UAC. If the UAC has a windows with a name it should be possible. I havent got any time to really did into this. When I find some time I will try to investigate the possibilities.
@KnifeEye89
@KnifeEye89 2 года назад
@@mrautomation thanks for replying, and it's super fine. I found another solution, so there's no need, but I thank you for your intentions 🙏
@Pavankumar71036
@Pavankumar71036 Год назад
How to pass control+N in powershell script???
@mrautomation
@mrautomation Год назад
Hi Pavan, you could this: [System.Windows.Forms.SendKeys]::SendWait("^{n}") Please let me know if it works for you. Kind regards Mr Automation. learn.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send?redirectedfrom=MSDN&view=windowsdesktop-7.0#System_Windows_Forms_SendKeys_Send_System_String_
@David1p
@David1p 2 года назад
Is it possible to use this to send keystroke to another computer in my network? Trying to highlight the app I'm trying to start and sending an {Enter} command to press "Start" (Have successfully managed to start the app by sending a "StartScheduledTask" command to it)
@mrautomation
@mrautomation 2 года назад
Hi David1p, thanks for watching the video. It is certainly possible, and the way you want to accomplish this is also possible. When I have some spare time I will create a video on how to send these commands remotely to a system (Scheduled task or run regkey). Its quite tricky because you need to have a usersession available, without a usersession it is not possible to use sendkeys. Thats mainly because non interactive users (like system) have no UI capabilities by default and have no userprofile either. I always use autologon for this purpose, but a scheduled task would do the trick fine as well, taking into account that some usersession needs to exist.
@fatinnabilla3651
@fatinnabilla3651 Год назад
@@mrautomation Hi Mr Automation, just wondering have you created a video regarding this problem? Because I am also facing the same problem as David1p. Thank you in advance :)
@mrautomation
@mrautomation Год назад
Hi @@fatinnabilla3651​I did not create a video on this topic yet, but I could create one, I will put it on the list for todo items. It seems more people now asking for it, so I will create a video for this for sure. Stay tuned.
@fatinnabilla3651
@fatinnabilla3651 Год назад
@@mrautomation Thankyouuu so much Mr Automation. I am facing these problems for quite some time already. I really appreciate your time and effort. Your kind gesture to teach people new things really aspired me. Have a nice day ahead :)
@mrautomation
@mrautomation Год назад
@@fatinnabilla3651 Thanks for your nice words :-) A new video incoming about remote sending keys and the caveats around it.
@user-ti4ij7ec2z
@user-ti4ij7ec2z Год назад
Hi Mr Automation! Thanks for your video. Can we have the script for installer-hangs please ?
@mrautomation
@mrautomation Год назад
Hi User-ti, I have added it to the comments actually, all the way down it is. This is the installer hangs code: ###Installer hangs script Add-Type -AssemblyName System.Windows.Forms $useip = [System.Windows.Forms.MessageBox]::Show("Do you want to provide a static IP?","Yes or no",4) if ($useip -eq "Yes"){ #$ipnumber = Read-Host "enter last octect 1-255 is valid : $network_prefix" } Write-Output "and now we are done"
@user-ti4ij7ec2z
@user-ti4ij7ec2z Год назад
@@mrautomation Hi Mr Automation. Thank you for your feedback. I didn't realize that my question was in the description of the video 😁
@mrautomation
@mrautomation Год назад
@@user-ti4ij7ec2z, Hahha no worries bro, your welcome ;-)
@knowledgeanddocumentationm9074
@knowledgeanddocumentationm9074 2 года назад
i have default powershell, can i do this?
@mrautomation
@mrautomation 2 года назад
Yes you certainly can, I think this is even supported on the first version of PowerShell which came out in 2006 called Monad.
@Slapfrost
@Slapfrost 9 месяцев назад
How would you send a {Space} in this
@mrautomation
@mrautomation 9 месяцев назад
Hi Slapfrost, .sendkeys(" ") just place a literal space in the sendkeys argument. I hope this helps.
@jeremyflowers8908
@jeremyflowers8908 Год назад
@1:20 - typo simulation
@enzym2004
@enzym2004 2 года назад
Lame examples can also be good examples. ;)
@mrautomation
@mrautomation 2 года назад
:-P
Далее
PowerShell S2E58 (Set Permissions)
22:21
Просмотров 758
PowerShell SE02E67 - Sendkeys remote
27:47
Просмотров 1 тыс.
Beautiful sport😍
00:20
Просмотров 134 тыс.
Tom🍓Jerry 😂 #shorts #achayanarmyfamily
00:14
Просмотров 11 млн
How to Measure ANY Cliffs Height with a Rock
00:46
Просмотров 12 млн
PowerShell Remoting
37:12
Просмотров 70 тыс.
PowerShell Windows Forms Tutorial 1 : Hello World
21:01
Microsoft PowerShell - My fav scripts
18:52
Просмотров 16 тыс.
CSV, JSON and XML (Oh My!) by Jeff Hicks
49:03
Просмотров 10 тыс.
How to Send Clicks and Key Strokes to Any Application
33:48