1

I'm having a hard time to trying to auto-fill the Read-Host input in PowerShell

I have a script that reads files, extracts lines and store them in a CSV file for fruther changes.

I'd like to be able to change each line on demand from the Powershell window without having to re-type the entire line.

  1. Read the file
  2. Find the next available line
  3. Make the line the Read-Host input
  4. User would then use the arrow keys to move the cursor and make changes to the line
  5. Press Enter to save the line to a new file

"_" in the below example of the desired state of Read-Host is the cursor blinking ready to makechanges*

#> Line to change : server=servername.loc.corporation_

2 Answers 2

3

If you add [System.Windows.Forms.SendKeys]::SendWait("YourText") before Read-Host this should help you. But it work only if console window has focus.

4
  • 1
    I don't even remember asking that
    – JeanneD4RK
    Oct 24, 2018 at 12:19
  • It was for my previous company, we can dump this thread
    – JeanneD4RK
    Oct 24, 2018 at 12:19
  • 2
    @JeanneD4RK on the contrary: SE sites are for problems that are general enough to be helpful in the future. This answer is actually exactly what you wanted to do and what I wanted to do in 2019.
    – Matthieu
    Nov 21, 2019 at 17:03
  • 1
    If you use this, you will probably need to add Add-Type -AssemblyName System.Windows.Forms to the top of your script. Mar 30, 2022 at 10:55
0

Here is a basic approach to get you started. You should really be including the code you're trying and specific examples of where you're getting stuck.

The below will output one line at a time, then ask the user to input whatever they want. This input can be a replication of the original line, or any changes they wish to make.

$sourcefile = gc "file1.txt"
$newfile = "file2.txt"

foreach ($line in $sourcefile) {
     Read-Host "Edit this line -" $line | Out-File -Append $newfile
}
2
  • So people will still have to rewrite the whole line instead of editing pre-filled ? That's my only problem, the rest of the script works well.
    – JeanneD4RK
    Aug 18, 2016 at 4:08
  • 1
    If this doesn't help you get started, then post your code and tell exactly where you're having problems.
    – root
    Aug 18, 2016 at 11:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .