Converting the Windows Script Host Read Method

Definition: Returns a specified number of characters from an input stream.

Read

The Read method is a bit of an odd duck: what it’s primarily intended to do is read the first x number of characters typed in as part of StdIn. For example, suppose you have this simple VBScript script:

Wscript.StdOut.Write "Please enter your name: " 
strInput = WScript.StdIn.Read(10)
Wscript.Echo strInput

In turn, suppose the user types in the following:

Jonathan Haas

So what will the variable strInput be equal to? Well, since we used the Read method and asked for just the first 10 characters, strInput will be equal to this:

Jonathan H

Strange, but true!

So can you mimic this behavior in Windows PowerShell? Well, we’re not totally sure why you’d want to. But this should do the trick:

$strInput = Read-Host "Please enter your name"
$strInput.Substring(0, 10)

In the first line we’re simply using the Read-Host cmdlet to prompt the user to enter his or her name; in line 2 we’re calling the Substring method in order to grab the first 10 characters in the variable $strInput. (In case you’re wondering, the 0 means that we’re going to start with character 0, the first character in the string. The 10 means that we’re going to take, well, 10 characters total.) The net result? Here’s the net result:

Jonathan H

See conversions of other Windows Script Host methods and properties.
Return to the VBScript to Windows PowerShell home page