Understanding the Basics of PowerShell: Scripting

Windows PowerShell is a versatile framework designed to help IT professionals automate administrative tasks and manage system configurations. It combines a command-line interface with a scripting language, making it an essential tool for Windows system administration. PowerShell can interact with Windows OS’s, file systems, and various APIs, allowing users to manage servers, workstations, and even cloud resources efficiently.

PowerShell is built on the .NET framework, which allows it to interact with .NET objects and leverage the features of the .NET ecosystem to provide a rich environment for managing both local and remote systems. Let’s go through the fundamentals and basics of PowerShell by exploring its syntax, key components, and basic scripting techniques.

Key Features of PowerShell

  • Object-Oriented: Unlike traditional command-line interfaces that return text, PowerShell cmdlets return .NET objects. This allows for complex data manipulation and processing.
  • Pipelines: Cmdlets can be combined in pipelines, passing data from one cmdlet to another, enabling efficient data processing.
  • Remote Management: PowerShell supports remote management, allowing administrators to manage multiple systems from a single console.
  • Scripting Language: PowerShell includes a robust scripting language that supports variables, loops, conditionals, and functions.

PowerShell Syntax Basics

Understanding PowerShell syntax is crucial for effective scripting and being able to leverage its full capabilities. PowerShell was designed with simplicity and readability in mind, which reduces the learning curve and allows new users to understand what is going on within a script. Let’s first discuss each of the core elements and rules of PowerShell:

1. Cmdlets

Cmdlets (pronounced “command-lets”) are the core components of PowerShell. They are small, single-function commands that perform specific tasks. Cmdlets use a Verb-Noun naming convention, which makes the purpose of the command clear, easy to understand, and helps maintain consistency across various operations.

  • Verb: Describes the action to be performed (e.g., Get, Set, Remove, Start)
  • Noun: Describes the object or resource being acted upon (e.g., Process, Service, Item)

Here are a few examples of common PowerShell cmdlets:

  • Get-Process: Retrieves information about running processes
  • Set-Location: Changes the current working directory
  • Start-Service: Starts a specified service

2. Parameters

Cmdlets will also typically include parameters that modify the behavior or scope of the command. Parameters can be identified easily as they are always preceded by a hyphen ( – ). They can either accept values to define a scope or act as switches to modify the behavior of a cmdlet.  Let’s take a look at an example of each type of parameter.

Parameter Example

In this example:

  • -Name is a parameter that specifies the name of the process to retrieve
  • “notepad” is the value passed to the -Name parameter

Other parameters that act as switches don’t require a value.

Parameter Example

Here, the -Force parameter forces the process to stop immediately, without a prompt for confirmation by the user.

3. Pipelines

The pipeline ( | ) is a powerful feature in PowerShell that allows you to pass the output of one cmdlet as input to another. This facilitates complex operations by chaining cmdlets together in a clear and concise flow. This not only makes it easier to combine various commands together, but also allows you to follow the logic of the script to understand its overall purpose. For instance, let’s go back to our previous example of stopping a process:

Pipeline Example

In this example:

  • Get-Process retrieves a list of all processes
  • Where-Object filters the list to include only those processes with a name equal to “notepad”
  • Stop-Process stops the running Notepad process

The pipeline also has a special symbol ( $_ ) that is used to represent the current object in the pipeline, allowing you to access properties of that object.  In the above example, you can see that in the Where-Object cmdlet we are referring to the current object in the pipeline using this symbol in order to filter out the objects that do not match. By using the pipeline, we can combine these 3 cmdlets together by passing the results of the output of the previous command to the next command in the pipeline.

4. Variables

Variables in PowerShell are denoted by the dollar sign ( $ ). They are used to store data that can be reused in scripts. Variables can hold data such as strings, numbers, arrays, Boolean values, or even objects. For instance:

Variable Example

Here, $name holds a string value, $age an integer value, $isStudent holds a Boolean value. We can also have variables hold the values of the result of a previous command.

Variable Example

Here, we are creating a variable named “process” and are passing the result of our Get-Process cmdlet to it for the process named “notepad.” We can then reference that process object directly by entering the variable name, allowing us to see the values of the previous Get-Process command.

5. Objects, Properties & Methods

In PowerShell, everything is an object. This means that even simple data types like strings and numbers are represented as objects. Objects have properties that store information about the object, and methods that perform actions on the object.

  • Properties: These are data fields that store information about the object
  • Methods: These are functions or actions that the object can perform

You can access the properties of an object directly using dot notation.  Here we are storing the result of our Get-Process command for the Notepad process into a variable named $process and then referencing its properties directly using dot notation.

Objects, Properties, & Methods Example

In this example:

  • $process.Name retrieves the Name property of the process
  • $process.Id retrieves the process ID property of the process

We can also use methods to act on the object directly.

Objects, Properties, & Methods Example

Here, we are taking the result of the Get-Process cmdlet for the Notepad process and directly closing that process using the Close() method.

Learn More About PowerShell Objects >

Basic PowerShell Scripting Techniques

Now that we have some of the basic concepts covered, we can put them together to create a more complex script. Scripting in PowerShell allows you to automate tasks and create reusable processes.

PowerShell scripts are saved with a .ps1 extension. You can write and edit scripts using any text editor, but using an IDE like PowerShell ISE or Visual Studio Code provides syntax highlighting and other useful features that can make the script building process faster and easier. Let’s now take a look at some of the basic techniques that can be employed to build PowerShell scripts.

1. Loops

Loops are essential for performing repetitive tasks in PowerShell. PowerShell supports several types of loops, including for, foreach, and while. Each type of loop has its own set of unique uses.

  • For: Used to iterate a specific number of times

Loop Example

This loop will execute five times, printing the iteration number for each.

  • Foreach: Used to iterate over elements in a collection (such as an array or hash table)

Loop Example

This loop will iterate over each element in the $people array and print the person’s name.

  • While: Continues to execute as long as a specified condition is true

Loop Example

This loop will continue to execute until the $count variable reaches 5.

  • Do-While: similar to a While loop, but guarantees the code block will be executed at least once

Loop Example

This loop is the same as above but will execute the code block once regardless of the current value in the $count variable.

Here’s a more complex example using foreach where we will get a list of all files in a folder, loop through them and print out their filename.:

Loop Example

2. Conditional Statements

Conditional statements allow you to execute different code based on certain conditions. These statements help control the flow of your script and are essential for decision-making logic. PowerShell supports if, else, elseif, and switch statements, as well as comparison operators to evaluate conditions and logical operators to combine multiple conditions together for evaluation.  Let’s take another look at our previous script where we looped through files in a folder:

Conditional Statements

Here, we are testing each file from the folder to determine its file extension and then moving it to another folder based off that condition.  We are using the comparison operator -contains to test if the filename contains the extension we are looking for.

  • if checks if the file is a CSV and moves to the CSV folder if true
  • elseif checks if the file is an Excel file and moves to the Excel folder if true
  • else handles cases where neither condition is met

We can expand upon this example to perform more complex expressions.  Perhaps we want to test for the file extension AND the file size.  We can combine multiple comparisons in our if statement by using the logical -and operator.  Here we are checking if the file is a CSV AND over 5000 bytes:

Conditional Statements

3. Functions

Functions in PowerShell are reusable blocks of code that can be called from anywhere within your script to perform a specific task. Functions allow you to modularize your code, making it easier to manage, reuse important code blocks to avoid code duplication, and troubleshoot issues.  They are defined using the function keyword and can accept parameters as input values as well as return values back to your main script. Let’s take a look at a basic example of a simple function, with both input and output values:

Functions

In this function:

  • The function is defined with the “function” keyword and given the name “Add-Numbers” , following the traditional Verb-Noun format.
  • param defines the input parameters $a and $b, both with a type of integer, indicating that both input values must be integer numbers.
  • The function performs actions to calculate the sum of $a and $b and stores the result in the variable $sum
  • The function returns the result of the calculation using the $sum variable

Once our function is defined, we can call our function similar to any other cmdlet:

Functions

You can see that we called it by using the function name, followed by the input parameter names along with our specified values for each. The result of the function was the output of our calculation (5 + 7), 12. Now we have a reusable block of code we can call at any point to perform a specific task, rather than having to recreate it each time we need this process done in our script.

Putting PowerShell Scripting Best Practices in Action

PowerShell is a potent tool for automating tasks and managing systems. By understanding its syntax, cmdlets, and scripting techniques, you can streamline administrative tasks and enhance your productivity. Start by experimenting with simple cmdlets and scripts, and gradually explore more advanced features as you become more comfortable. With PowerShell, the possibilities for automation and system management are endless.

PowerShell Automation

Looking to supercharge PowerShell processes?

LEARN MORE