PowerShell Genie

Variables

Store a value, inspect its type and avoid treating a display string as reusable data.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

A variable holds a value. In $student = 'Ada', the value is a string. The assignment itself does not normally emit that value, so the greeting on the next line is the visible output.

Double-quoted strings expand variable references; single-quoted strings preserve them literally. Change the example greeting to single quotes and predict whether you will see Ada or $student. This is useful when constructing paths, but it is also an easy way to create a path containing an unintended literal dollar sign.

A command can return zero, one or several values. If a report always expects a collection, capture it with @(...). Do not assume that a variable contains a single object just because a previous test happened to return one.

Keep a number as a number while calculating. Converting a count or duration into a sentence too early makes later sorting and arithmetic harder. Add units and labels when presenting the result.

Inspect this example’s structure

Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

$student = 'Ada' "Hello, $student"
  1. Stage 1$studentPositional values or no named parameters

    What happens

    The greeting reads the current value of student at that line. Changing the variable later does not rewrite a string that was already produced. In your own PowerShell session, inspect a value with $student.GetType().FullName when its type is uncertain.

    Worth remembering

    Quote deliberately and inspect the returned value before assuming its type or count.

    Primary documentation

    Microsoft Learn: variables

    Try it

    Illustrative output · values vary by environment

    1PS> $student = 'Ada'
    2PS> "Hello, $student"

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Stores a value, then interpolates it inside a double-quoted string.

      Show reference output

      Illustrative output · values vary by environment

      Hello, Ada

      Practise this

      Assign a numeric variable

      Store the number 12 in $count.

      Review the lesson

      Keep going

      Next: PowerShell Arrays
      Genie guideVariables

      Store a value, inspect its type and avoid treating a display string as reusable data.