Don’t do that #5: Specify the type of variable with Read-Host

By | February 24, 2015

Don’t do that: You could write some scripts to other departments (ex: Helpdesk) and asks some input for the end user, let’s take this basic example where you ask to the user to enter a number:

$number = Read-Host "Enter a number"

Do that: It’s better to specify directly the type we want, it’s called “type casting“: convert data from one type to another.

Powershell usually select the correct type but in some cases it is necessary to specify the type. In somes cases it can be problematic.

This code returns a string.

$number = Read-Host -Prompt 'Enter a number'


This code returns an unsigned integer :

[uint16]$number = Read-Host -Prompt 'Enter a number'


Try to specify the type depending on context.

Note1: uint16 (u = unsigned, only positive)

Note 2:  [ ] is the cast operator


Leave a Reply

Your email address will not be published.