This article is about reading multi line input from command line using PowerShell. We often get requirement to enter multiple lines or paragraphs of text as input to a PowerShell script. The approach discussed in this article will help you with such requirements.
A few days back one of my friend asked me about this. He wants to write a script which takes a disclaimer as input, which is a multi-line. I told him that this is not a best approach. If you want to have such requirement, get the disclaimer in a text file and pass it to the script which is best approach in my opinion but his users are more comfortable with typing it at the console. Well, fine, requirements are always like this. So, I decided to help him with this script.
function Read-MultiLineInput { [CmdletBinding()] param( ) $inputstring = @() $lineinput = $null while($lineinput -ne "qq") { $lineinput = Read-Host if($lineinput -eq "qq") { Continue } else { $inputstring += $lineinput } } return $inputstring } Write-Host "### Enter multi-line input ###" Write-Host "(Type `"qq`" on a new line when finished)" -ForegroundColor Green $multilines = Read-MultiLineInput Write-Host "`n`n`n###Below is the multi line input you entered" $multilines -join "`n"
Save the above code into a file called Read-MultiLineText.ps1 and execute it. As you can see on the console, it takes the input till you type “qq” on a new line. You can enter as many lines as you want. Just type qq on a new line when finished entering your multi line input.
This approach can be used if you want to enter multiple computer names or you want to copy paste computers list directly.
The logic in this script is simple. The Read-MultiLineInput function is repeatedly calling Read-Host till the value entered by the user is “qq”. When “qq” is found it is stopping the loop. I am sure this script will not cover all of the use cases. If you have a similar requirement and the script requires some enhancements, please post in the comments section. I will try comment/update on the best effort basis.
Below are some of the examples.
Example:1:
As you can see below, I have copy pasted first paragraph of this article as is and it accepted that.
Example 2:
I entered one computer name per line and as you can see it read all of them. Ideally you should declare a array of strings parameter and pass the computer names as camas separated. But most of the times our computer list is one computer name per line. To change it to one string with camas separated, we have to use a trick in excel or your favorite editor. We can avoid it using this approach.
Hope this helps.