PowerShell Basics Level: Beginner Chapter 5: Turn Commands Into Scripts You Can Reuse

Your first script and data types

A first script is short: a comment, a variable, and an output line. Data types decide what you can do with a value, so learn the common ones early.

Lesson 2 of 2 in Chapter 5: Turn Commands Into Scripts You Can Reuse. Previous step in this path: Scripts and security: execution policy. 3 learning objectives, 10 examples, and a knowledge check.

Start: what you will learn

A first script is short: a comment, a variable, and an output line. Data types decide what you can do with a value, so learn the common ones early.

Learning objectives

  • Write, save, and run a first script
  • Name the common data types and give an example of each
  • Explain why type matters when you add or compare values

Concept in simple words

What it is: your first script is a short .ps1 file with a comment, a variable, and an output line. A comment is a note for the reader, and PowerShell ignores it when the script runs. A variable is a named place to store a value, marked with a dollar sign, such as $name. An output line, such as Write-Output, shows a result on screen. A data type is the kind of value a variable holds, such as text, a whole number, a decimal number, true or false, a date, or a list. The type decides what PowerShell can sensibly do with that value.

The problem it solves: without a script, every repeated task means retyping every command, in the right order, with no mistakes. With a script, you type the work once, save it, and run the same file again and again. If you improve the work, you change one file, and every future run uses the improved version. That is reuse in its simplest form, and it is also how you share work with someone else without dictating commands over your shoulder.

What PowerShell does behind a script: it reads the file from top to bottom, and runs each command in order. When it meets a variable assignment, it stores the value under that name for the rest of the run. When it meets Write-Output, it sends that value to the output stream, which is what you see on screen. When the file ends, the run ends. Variables set inside a normally run script do not stay in your session afterwards. That is normal behaviour, not an error. The script is a closed run, and the next run starts fresh.

Comments, in depth: a comment starts with a hash sign, #, and runs to the end of that line. PowerShell skips it completely, so it never affects the result. Use the first comment to say what the script does, in one plain sentence. You can also use a block comment, which starts with <# and ends with #>, for a longer note that spans several lines. Good comments answer why, not only what. A line that says store the name is less helpful than a line that says store the name, because the greeting uses it in the next line.

Variables, in depth: a variable name starts with a dollar sign, followed by a name you choose, such as $name or $count. Choose a clear name that says what the value means. A good rule is to start with a letter, and use only letters, numbers, and underscores in the name. The equals sign, =, assigns a value, meaning it stores the value on the right into the variable on the left. Assignment is not a comparison. It does not ask whether two things are equal. It stores.

Quotes, in depth: PowerShell has two kinds of quotes, and they behave differently. Double quotes let PowerShell replace a variable with its value, which is called expansion. So "Hello, $name" becomes Hello, Sam when $name holds Sam. Single quotes treat everything literally, so 'Hello, $name' stays as Hello, $name, dollar sign and all. If your greeting shows a dollar sign instead of a name, you almost certainly used single quotes where you needed double quotes.

Data types, one by one: a string, written [string], is text, such as "Sam" or "hello". An int, written [int], is a whole number, such as 5 or 30. A long, written [long], is a larger whole number, for values too big for an int. A double, written [double], is a decimal number, such as 2.5. A decimal, written [decimal], is also a decimal number, and it is the careful choice when exact decimal values matter, such as money. A bool, written [bool], is true or false, written $true or $false. A datetime, written [datetime], is a date and time, such as the value returned by Get-Date. An array is a list of values, written with @( ) or as values separated by commas. A hashtable is a set of key and value pairs, written with @{ }, such as a name paired with an age.

How PowerShell picks a type: most of the time, you do not state a type, and PowerShell works it out from the value you give it. The number 3 becomes an int, the text "Sam" becomes a string, and 2.5 becomes a double. PowerShell remembers that type with the variable. You can check it at any time with $value.GetType().Name, which answers with the type name, such as Int32 for an int, or String for text. GetType() asks the value what type it is, and .Name asks for just the short name of that type.

Why it works

Why type matters, with the plus sign: the same symbol can mean different things for different types. For numbers, plus adds, so 5 + 7 gives 12. For text, plus joins, which is called concatenation, so "5" + "5" gives 55, the two characters stuck together. PowerShell is not being difficult. It is doing the only thing that makes sense for each type. That is why a surprising result is often a type surprise, not a maths mistake. Check the type first, and the surprise usually explains itself.

Why type matters, with the star sign: the same idea applies to multiplication. For numbers, the star multiplies, so 3 * 2.5 gives 7.5. For text, the star repeats, so "5" * 2 gives 55, the text written twice. Again, PowerShell follows the type. If you expected a number answer and got repeated text, you were holding text, not numbers, and you need to convert before you calculate.

How it works, step by step

How it works, step by step: first, open an editor and write a comment line starting with a hash sign, saying what the script does. Next, create a variable with the equals sign, for example $name = "Sam", where the dollar sign marks a variable and the quotes mark text. Then add a Write-Output line to show a result. After that, save the file as plain text with a .ps1 ending, in a folder you can find again. Finally, move to its folder in PowerShell, and run it by typing its path, such as .\first.ps1. Read the output, and check it against what you expected.

Running a script, in depth: PowerShell needs a path to run a script file. From the folder that holds the file, type .\first.ps1, where the dot means the current folder, and the backslash separates the folder from the file name. Typing only first.ps1 will not run it, even if you are in the right folder, because PowerShell does not run a script by its bare name alone. Double clicking the file in a file manager does not run it either. It usually opens the file for editing. The path rule is a safety feature. It forces you to say exactly which file you mean.

Saving the file correctly: the .ps1 ending is what marks the file as a PowerShell script. If you save it as first.txt, PowerShell will not treat it as a script file, even if the contents look right. Save as plain text, not as a formatted document, because formatting codes hidden in a document file will confuse PowerShell. If your editor asks about encoding or file type, choose plain text. A clean file name with no spaces, such as first.ps1, also saves you from quoting trouble later.

Parameters, the reuse step: a script becomes far more reusable when it accepts input instead of fixing every value inside the file. A param block at the very top of the script declares those inputs, such as param([string]$Name). The block must come first, before other commands, apart from comments. You then run the same script with different values, such as .\greet.ps1 -Name Sam, and then .\greet.ps1 -Name Alex, and you get a different greeting each time, from the same file. Stating the type in the param block, such as [string], also tells PowerShell what kind of value you expect.

Reading input, and the type trap: Read-Host reads one line of input from the console, and that input arrives as text, even when the person types a number. That is the most common type trap for beginners. If you ask for a count with Read-Host and then add 5, you may get joined text instead of a sum. The fix is to convert first, with [int], before you calculate. Write [int]$count = Read-Host "How many", or convert the stored value with [int]$count, and then do the maths. Always convert input before maths, and check the type if the answer looks like joined text.

Lists, in depth: an array holds several values in order, such as @("red", "blue", "green"). You read one value by its position, called an index, and counting starts at zero, not at one. So $colors[0] gives red, the first value, and $colors[1] gives blue. The Count property tells you how many values are in the list, so $colors.Count gives 3 here. If you ask for a position past the end of the list, you do not get a helpful value, so check Count before you guess at an index.

Key and value pairs, in depth: a hashtable holds pairs, where each key names a value, such as @{ Name = "Sam"; Age = 30 }. You read a value by its key, such as $person.Name, which gives Sam. Keys are handy when order does not matter, but names do. A list is right when order matters, such as steps in order. A hashtable is right when you want to look something up by name, such as a setting by its setting name.

Dates, in depth: Get-Date returns a datetime value, which is a real date and time value, not just text that looks like a date. That matters, because you can ask a datetime value for its parts, and you can compare dates in date order. If you store a date as plain text, PowerShell will treat it as text, and sorting or comparing may follow text order instead of date order. When a value is a date, keep it as a datetime, and only turn it into text at the moment you display it.

Stating a type, in depth: you state a type by writing it in square brackets before the variable, such as [int]$count = 5. From then on, PowerShell tries to convert assigned values to that type. That is useful after reading text input, or when a value must always be a number. But a stated type is not magic. If you try to store text that is not a number, such as "five", in an [int] variable, PowerShell cannot convert it, and you get an error. Read the error as useful news. It tells you the input was not in the form you promised.

When to state a type, and when not to: let PowerShell infer the type for simple values, such as a name or a small count, because inference keeps scripts short and readable. State a type when the value must be a certain kind, such as a count read from input, a price that must stay decimal, or a flag that must be true or false. State a type in a param block, so callers know what to pass. Do not guess a type problem away by trying random symbols. Check the type with GetType().Name, fix the real cause, and rerun.

Worked examples

Read each example in order. Each one explains its parts, then shows what to look for in the output.

Syntax

Syntax
.\first.ps1

Example 1

A comment, a string variable, and an output line. The first line starts with #, so PowerShell skips it. The second line stores the text Izaz in $name. The third line uses double quotes, so $name is replaced with Izaz. Run it with .\first.ps1 from its folder, and check that the name appears inside the greeting.

Example 1
# first.ps1: greet the user
$name = "Izaz"
Write-Output "Hello, $name"

Illustrative output: Hello, Izaz

Example 2

Stating the type makes the addition numeric, even if the values came from text input. [int] before each variable promises a whole number. The plus sign then adds, because both values are numbers. Change one value to text without [int], and the same plus sign would join instead of add.

Example 2
[int]$a = 5
[int]$b = 7
$a + $b

Illustrative output: 12

Example 3

$count = 3 stores a whole number, which PowerShell treats as an int. $price = 2.5 stores a decimal number, which PowerShell treats as a double. The star is the multiplication symbol, so the last line multiplies the two values. Because one value is a decimal, the answer is a decimal too. If both values were whole numbers, the answer would be a whole number.

Example 3
$count = 3
$price = 2.5
$count * $price

Illustrative output: 7.5

Example 4

The same variable, shown two ways. Double quotes expand $name to Sam, so the first output is a real greeting. Single quotes are literal, so the second output shows the dollar sign and the name of the variable, not its value. If your output shows a dollar sign, change the quotes, not the variable.

Example 4
$name = "Sam"
Write-Output "Hello, $name"
Write-Output 'Hello, $name'

Illustrative output: Hello, Sam Hello, $name

Example 5

The same plus sign, two different types, two different answers. The first line joins two strings, so you get the text 55. The second line adds two numbers, so you get 12. The quotes are the whole difference. This is the fastest way to see why type matters.

Example 5
"5" + "5"
5 + 5

Illustrative output: 55 12

Example 6

An array is a list in order. @("red", "blue", "green") stores three strings. $colors[0] reads the first value, because counting starts at zero. $colors.Count reads how many values are in the list. Change the index to 1 and you get blue. Change it to 2 and you get green.

Example 6
$colors = @("red", "blue", "green")
$colors[0]
$colors.Count

Illustrative output: red 3

Example 7

A reusable script. The param block must be at the top, before other commands. [string] says the input must be text, and $Name holds whatever value the caller passes. Save this as greet.ps1, then run .\greet.ps1 -Name Sam for one greeting, and .\greet.ps1 -Name Alex for another, from the same file.

Example 7
param([string]$Name)
Write-Output "Hello, $Name"

Illustrative output: Hello, Sam

Example 8

Read-Host returns text, even when the person types a number. If you add 5 to the text directly, you may get joined text. Converting with [int] first turns the text into a number, so the plus sign adds. Type 7 at the prompt, and the final line gives a number answer, not joined text.

Example 8
$text = Read-Host "How many"
[int]$count = $text
$count + 5

Illustrative output: 12

Example 9

Get-Date returns a datetime value, not plain text. The second line asks that value for its type name. GetType() asks what type the value is, and .Name gives the short name. Look for DateTime in the output. If you saw String instead, the value would be text that only looks like a date.

Example 9
$today = Get-Date
$today.GetType().Name

Illustrative output: DateTime

Example 10

A hashtable is a set of key and value pairs. Name is the key, and Sam is its value. Age is another key, with the number 30 as its value. $person.Name looks up the value by its key, so you get Sam. Use a hashtable when you want to find a value by name, and an array when order matters most.

Example 10
$person = @{ Name = "Sam"; Age = 30 }
$person.Name

Illustrative output: Sam

Nothing on this page executes PowerShell code. The outputs above are illustrative only.

Common mistakes and troubleshooting

Read these before you try the examples, so you can spot the same problems in your own work.

  • Running a script from another folder without its full path, so PowerShell cannot find it. Use the full path or change to its folder first.
  • Adding text that looks like a number, and getting joined text instead of a sum. Check the type.
  • Saving a script as a text file, such as first.txt, instead of first.ps1, and then wondering why PowerShell will not run it as a script. The .ps1 ending is what marks the file as a PowerShell script.
  • Using single quotes for a greeting, and then wondering why the output shows $name instead of the name. Single quotes are literal. Use double quotes when you want a variable replaced with its value.
  • Forgetting the dollar sign, and writing name = "Sam" instead of $name = "Sam". Without the dollar sign, PowerShell does not know you mean a variable. Every variable reference needs its dollar sign.
  • Doing maths on Read-Host input without converting it first. Read-Host returns text, so convert with [int] before you add or multiply, or you will get joined or repeated text.
  • Counting array positions from one instead of zero. $colors[0] is the first value, not $colors[1]. If your first value looks wrong, check whether you started counting at one by mistake.
  • Putting the param block after other commands, or forgetting it and fixing values inside the file. A param block belongs at the top of the script, so the same file can be reused with different inputs.

Knowledge check

Knowledge check

What does "5" + "5" give in PowerShell?

Pick one answer. Feedback appears right away, and you can try again.

Remember this and next step

Remember this: a script is just saved commands, run from top to bottom by their path, and a type is just the kind of value in the box. Short scripts, clear comments, a quick type check when a result surprises you, and a param block when you want reuse, will carry you a long way.

Next step: What is a module