1

I'm looking to create a hotkey on F10 that will, when pressed, open a text file named Notes. That is the simple part, it is:

C:\Users\Matt\Notes.txt

But I also want another press of the same hotkey to save the file and exit.

I am only interested in the script, I can run powershell through hotkeys.

2
  • What will you be editing the file with? That kind of makes a huge difference here. The script would have to look to see if the file is open, and take action accordingly. Or you could use handle.exe from SysInternals to see what application has the file open, but that will likely be harder to accommodate since you would have to somehow write code to interact with whatever application has the file open and that could vary greatly. So, will you be editing the file with Notepad? Commented Jul 2, 2015 at 1:45
  • Yes, Notepad, or Sublime if possible! Commented Jul 2, 2015 at 12:35

1 Answer 1

1

Firing off an editor from script is as simple as:

$proc = Start-Process -FilePath C:\Bin\Notepad++.exe -arg C:\Users\Matt\Notes.txt -PassThru

The trickier part is figuring out how to save & close the file. If the editor happens to have a COM object model, you could use that but I doubt your editor is Word. :-)

Another general approach is to use WinForms SendKeys functionality. However an even better approach is to use the Windows UI Automation framework to drive the UI of arbitrary apps. There's even a PowerShell module that wraps this API to make it easy to use from PowerShell. It is called UIAutomation. Here is an example of how it is used:

Start-Process calc -PassThru | Get-UIAWindow | 
    Get-UIAButton -Name [1-3] | Invoke-UIAButtonClick;

You would substitute $proc for the Start-Process calc -PassThru bit above.

Sign up to request clarification or add additional context in comments.

2 Comments

For some reason I get a "system cannot find file specified error" with the above line. I removed -arg and used -filepath and it seems to work :) Thank you!
In my example above, notepad++.exe would need to be in your path. So it is probably better to specify the full path to the exe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.