Write your first PowerShell code
Posted by Superadmin on January 29 2023 03:42:27

Write your first PowerShell code

 

 

In this module, you begin learning the basics of programming by writing and running code in PowerShell.

Learning objectives

 

After you've completed this module, you'll be able to:

Introduction

PowerShell is a powerful, cross-platform task automation and configuration management framework. It consists of a command-line shell and programming language. Here are its most common uses:

PowerShell is a great language to learn whether you have prior programming experience or not. It's a beginner-friendly language because of its readability, focus on simplicity, and built-in help system.

The best way to learn how to code in any language is to write as much code as possible. We encourage you to type along with the exercises in this module and others in this learning path. Typing the code yourself in each exercise and solving the coding challenges can accelerate your learning and teach you small foundational concepts to build on with practice and exploration.

Learning objectives

 

After you've completed this module, you'll be able to:

This module gives you your first look at the PowerShell syntax. It provides invaluable insights and introduces many new ideas that will be expanded on in other modules.

 

 

 

Exercise - "Hello World!"

 

Write your first lines of code

 

In this exercise, you'll follow a longstanding tradition among software developers of printing the phrase "Hello World!" to a command line or console window. As you'll see, you can learn a lot from even this simple exercise.

Step 1: Type the code in Cloud Shell

 

In this module, you'll use a version of a code editor in Shell to write and run scripts.

 

 

 

In this module, you'll use a version of a code editor in Cloud Shell to write and run scripts.

  1. In the Cloud Shell terminal, type the following code:

    PowerShell
    New-Item HelloWorld.ps1
    code HelloWorld.ps1
    

    The New-Item command creates a new .ps1 file in the current directory. The .ps1 file name extension is the extension that's used for PowerShell scripts.

    The code command followed by the file name of the script you want to work with opens the file in the Cloud Shell code editor. Another window opens that allows you to write and edit scripts and then save them to run in Cloud Shell. If you want to open a file that's stored in another location, you can define the full path instead of using only the file name.

  2. In the code editor window, type the following code:

    PowerShell
    Write-Output 'Hello World!'
    
  3. Use the Ctrl+S keyboard shortcut in Windows (or ⌘+S on macOS) to save the file.

    We'll explain how and why it works soon. But first, you should run your code to ensure that you've typed it correctly.

      Note

    You might be tempted to use the Copy button on the code sample to skip all the typing. However, we encourage you to type this line of code yourself. The physical act of typing builds muscle memory and helps you gain insights that you might not get otherwise.

Step 2: Run the script

To run the script, enter the following command in the Cloud Shell terminal:

PowerShell
. ./HelloWorld.ps1

  Note

Be sure to include the dot (.) at the beginning of the command. This tells PowerShell to run the script or file that's being called.

Step 3: Observe the result

 

You should see the following output in Cloud Shell:

Output
Hello World!

What to do if you see an error message

Where other languages require every character to be precise, PowerShell is more relaxed. It's case insensitive, meaning that it doesn't care whether you accidentally type an upper or lowercase letter where you aren't supposed to. It interprets Write-Output and write-output the same way. The main things to watch out for are misspellings or having an extra or missing space.

 

 

If an error occurs, it might look something like this:

Output
 Write-Outpu: The term 'Write-Outpu' is not recognized as a name of a cmdlet, function, script file, or executable program. 
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

In this example, PowerShell is telling us that we incorrectly wrote Write-Outpu instead of Write-Output, and it can't find the command we specified.

Reading these errors is essential in helping you learn what caused them. When you run a program and you get an error, the error often includes the line number where the issue occurred, a description of the error, and sometimes a suggestion for how to fix it.

 Note

Not all errors are as easy as the preceding example to read and understand. Some might take a little bit of testing and investigation to figure out their cause.

Step 4: Create a new file and write code to receive input

  1. In the open HelloWorld.ps1 file, comment out the code you wrote in the editor by adding a number sign (#) before the command. Below the commented line, add the following lines of code:

    PowerShell
    # Write-Output -InputObject 'Hello World!'
    
    $name = Read-Host -Prompt "Please enter your name"
    Write-Output "Congratulations $name! You have written your first code with PowerShell!"
    

 Note

You create a code comment by prefixing a line of text with the number sign (#). This useful technique helps you prevent certain code from running without having to remove it entirely. You can also use comments to add information for yourself or others who read your code later. You can place comments anywhere in your code, and any text after the # on the same line is commented out.

  1. Save the file, and then run the script by using the same command you used earlier:

     
    . ./HelloWorld.ps1
    
  2. At the prompt that asks for your name, type your name, and then select Enter.

    The output is a message with your name inserted. For example:

    Output
    Congratulations Chase! You have written your first code with PowerShell!
    

How did your program work?

 

In this exercise, you invoked a cmdlet called Write-Output. Cmdlets are the main way you use PowerShell. The command syntax is a Verb-Noun format. This makes it easy to understand what the code is trying to do. The cmdlet's name is its intent. The code is doing something (verb) to a thing (noun).

 

Hello World! and the congratulatory sentence are both string inputs for the Write-Output cmdlet to process and output. A string is a simple data type that computers use. In PowerShell, you can enclose strings in either single quotation marks ('') or double quotation marks (""). For our code, we'll use double quotation marks to allow PowerShell to display variable values instead of variable names. You'll learn more about data types and how to define them in a later module.

 

 

By using Read-Host, you can write a message to prompt a user for input. You define the message for the user with the -Prompt parameter. Parameters allow a cmdlet to take input from a user. You store the input in a variable called $name, and then you use the Write-Output cmdlet to display the custom message in the Cloud Shell terminal.

 

You'll learn more about variables in a later module. For now, just think of them as containers that store values to make your code more flexible. Instead of having to type a name into every program, you can store a value in a variable and reuse it to get different results.

 

You define a variable by placing a dollar sign ($) at the beginning of a word. After the word, use an equal sign (=) followed by the value you want to store in the variable. In the preceding example, you stored the name "Chase." Variables can be named anything, but it's best to name them something that helps you understand what it's storing and where to use it. For example, $name is storing someone's first name.

 

Many cmdlets work much like the preceding example. A user provides input to the cmdlet, the cmdlet does something, and then the cmdlet produces an output. This process can be something like writing to the output pane, computing an equation, changing something in the environment, or many other things.

Recap

Let's take a moment to recap what you've learned in this first unit:

 

 

How PowerShell code works

 

To help you understand how code works, we need to talk about what a program is, what a programming language is, and how that language communicates commands to your computer.

What is a program?

A program is a set of instructions that complete computing tasks. The instructions are compiled into a format the computer can understand and then run by a user. A user can be a person or another program. The computer executes the instructions in order, one line at a time, until there are no more lines to execute or the program is explicitly told to stop.

Even the most basic programs do one or more of the following tasks:

A program can take different forms for different purposes. A program can be:

Some programs, including those you'll write in this module, need only a few lines of code. But complex programs such as operating systems need tens of thousands or sometimes millions of lines of code.

What is a programming language?

The job of a programming language is to enable a person to write instructions for a computer in a human-readable and understandable way. Computers understand language in a very different way than humans ordinarily do. Programming languages give program writers a very specific and less complicated way of interfacing with computers to give them instructions. The instructions you write in a programming language are called code.

There are many programming languages, each with a different syntax. However, after you've learned your first programming language, you can apply many of its concepts to each new language you learn.

What is syntax?

Like any spoken or written language, programming languages have their own grammatical rules, known as syntax. The syntax of any programming language includes keywordsoperators, or other types of rules that might be specific to that language.

Keywords are specific words reserved by a programming language that have special meaning and behavior. In PowerShell, many of the keywords read like English. For example, ifwhile, and return are some of the keywords you'll use to write code in PowerShell and many other languages.

Operators are special characters, such as parentheses (()) or equal signs (=). These characters tell the computer to perform specific mathematical, relational, or logical operations to produce a result.

When you typed your code in the Cloud Shell terminal in the preceding unit, you might have noticed small changes to the color of the text and symbols. This color coding is called syntax highlighting. As you're reading your code, syntax highlighting can help you spot any mistakes you might have made. This feature is available and even more robust in many code editors, such as Visual Studio Code.

Compiling code in PowerShell

Computers aren't good at reading our programs in the way we write them. Programming languages need to be translated into a form that the computer can understand. Programming languages have various ways of doing this.

Many programming languages compile code as an individual step. You write your code, run it through a special program called a compiler, and the compiler produces an executable package to run.

Other languages, such as Python, have what's called an interpreter, which interprets the code for the computer and executes the code one line at a time as it's interpreting it.

PowerShell works both a little differently and a little similarly to the compiled and interpreted approaches.

PowerShell is compiled into an abstract syntax tree (AST), first in memory, and then run. But you don't need to do a deep dive here to use PowerShell. All you need to know is that the computer checks your code first in the AST as it looks for major issues. Then, if everything is okay, your program is run by the computer without the need for a compiled executable program. This approach is useful, because it ensures that your code will run correctly before it's run by the computer, where it might otherwise make changes and stop because of a syntax error. By contrast, an interpreted language such as Python runs the code until it finds something wrong in the syntax.

Exploring PowerShell

An important feature of PowerShell is its built-in help system, which gives you easy access to information about PowerShell commands. If you get stuck as you're writing, you can look up help for commands or PowerShell concepts by using the Get-Help command. For example, to see all the details about the Write-Output command, you can type and run the following command:

PowerShell
Get-Help -Name 'Write-Output' -Full

Get-Help is the command to run and Write-Output is the name of the command to get help for. The -Full switch tells PowerShell to get all information for the specified command, including a command description, parameter information, examples, and more. This help information is accessible in any PowerShell terminal, including the Azure Cloud Shell terminal.

If you want to explore all the commands that PowerShell has to offer, you can use Get-Command * to view the full list. The asterisk (*) is a wildcard character in PowerShell. It allows you to match patterns to find information more dynamically. In this case, you use the * to filter for all available commands. For example, to get all commands that have User in them, run Get-Command *User*.

Another great thing about PowerShell is that it comes with an integrated shell. By using the shell, you can test your code and interact with the output without having to run your code every time you want to test something. To ensure that your code will work as expected, you can type it right in the terminal.

 

 

 

Challenge

 

Step 1: Close any open files in the Cloud Shell code editor

Use the keyboard shortcut Ctrl+Q in Windows (or ⌘+Q on macOS) to close any open files in the Azure Cloud Shell code editor.

Step 2: Create a new file to write your code

Create a new file named GettingStarted.ps1, and use the Cloud Shell code editor to open it.

Step 3: Write code in the Cloud Shell code editor to display two messages

Use the techniques you've already learned to print one message and then collect user input to reuse in a second message. Earlier, you displayed a message in just one line of code. You then requested input from a user and then reused that value to print a custom message. Use both techniques for this challenge.

No matter how you do it, your code should produce something like the following output. In this example, replace the placeholder text <current date> and <your name> with values that you choose.

Output
Today's date is <current date>.
Today is the day <your name> began a PowerShell programming journey.

Step 4: Run the code

 

Close the code editor, and run the script in Cloud Shell.

Whether you get stuck and need to peek at the solution or you finish successfully, continue on to view a solution to this challenge.

 

Solution

The following code is one possible solution to the challenge in the preceding unit.

PowerShell
$date = Read-Host "What is today's date"
$name = Read-Host "Please enter your name"
Write-Output "Today's date is $date."
Write-Output "Today is the day $name began a PowerShell programming journey."

This code is only one possible solution. Your code could look different. However you wrote the code, you should have used Read-Host and Write-Output to produce the desired output.

Output
Today's date is 02/05/2021.
Today is the day Chase began a PowerShell programming journey.

 

If you were successful, congratulations! Continue on to the knowledge check in the next unit.

 Important

 

If you had trouble completing this challenge, it might be a good idea to review the previous units before you continue on. All new ideas we discuss in other modules depend on your understanding of the ideas that were presented in this module.

 

 

 

 

 

 

 

 

 

 

 

 

Check your knowledge

 

 

How does PowerShell compile?

2. 

Which of the following statements is true about PowerShell.

3. 

What is wrong with this line of code? Read-host "What is wrong with this line of code?"

Summary

Congratulations on taking your first steps toward writing programs by using PowerShell.

In this module, your goal was to become familiar with PowerShell syntax and to write code that takes input from a user and outputs it to the console.

You learned what programming languages are and how they communicate to the computer. You wrote your first programs by using basic PowerShell syntax elements, such as cmdlets, parameters, and variables. You learned how to display string data to the console and receive string input from users. And you learned what to look for when you find errors in your code.