Reading Data from the Command Line in PowerShell–#SQLNewBlogger

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

In every language I’ve coded in, there is a way to read input from the command line. From INPUT in BASIC, readln in PASCAL, scanf in C, read in LISP, input() in Python, and more, every language can do this.

I knew PowerShell could, and I wanted to find out how to do it. I’m building a CLI tool for SQL Saturday, and I am looking to get user input.

A quick search led me to Read-Host. I probably should have guessed this, but it does what I need. A quick example of where I started. This code gets an event number from a user and then prints if back out, along with a string created from the number:

$EventNumber = Read-Host -Prompt "Event Number:"
$DataFilename = "SQLSat$($EventNumber).yml"
# write the data
write-host("Event: $EventNumber")
write-host("File: $DataFilename")

I can run this, as shown here, and put in a number.  I typed in the first 1022 below:

2021-11-17 17_45_25-● sqlsatcli.ps1 - sqlsatwebsite - Visual Studio Code

I’ll use this to get information from the user and then produce a YAML file that will contain what’s needed to publish, or update, an event.

SQLNewBlogger

This post took me about 10 minutes to assemble. I was already working through this process and stopped to jot down an idea, save some code, and make a screenshot. That was about 2 minutes out of my day, and then I went on with coding. Later, I wrote this.

You could do the same thing. Take a minute out of your daily work, sketch a quick post, and then finish it later.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

1 Response to Reading Data from the Command Line in PowerShell–#SQLNewBlogger

  1. Greg Moore says:

    Funny you mentioned this now. I just had to look this up to remind myself about it for my upcoming PowerShell article. It also supports -AsSecureString which can be useful.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.