logo

Windows PowerShell Scripting Tutorial for Beginners

Introduction

Windows PowerShell is a tool for task automation and configuration management that combines a command line shell with a scripting language. IT professionals rely on PowerShell to:

  • Automate common tasks
  • Manage remote machines
  • Share data between applications
  • Manage infrastructure as code

Learning even a few basic set of Windows PowerShell commands and core scripting capabilities can help you achieve significant automation. To help, this PowerShell tutorial covers PowerShell scripting basics for beginners.

Caution: Once you’ve learned a few PowerShell basics, it is easy to start running commands — but they can have a profound impact on the stability and security of your IT ecosystem. As you are getting started with PowerShell, be sure to experiment with it only in a sandboxed environment.

Setting up your PowerShell environment

Before you can run PowerShell scripts, you need to set up the Windows PowerShell environment. Here are the steps involved.

Install PowerShell

PowerShell comes pre-installed on most Windows operating systems. However, if you need to install a newer version, you can download it from the Microsoft website or use Windows Package Manager (Winget) or Chocolatey Package Manager.

Run PowerShell

To launch the PowerShell command line, enter powershell.exe in the Windows Start menu. You’ll see a screen like the following:

PowerShell Scripting Tutorial for Beginners.

Check the execution policy

By default, PowerShell restricts the running of scripts for security reasons. You can check your policy’s setting by running the Get-ExecutionPolicy command:

PowerShell Scripting Tutorial for Beginners.

You will get one of the following values:

  • Restricted — No PowerShell scripts may be run. This is the default setting.
  • AllSigned — You can run PowerShell scripts signed by a trusted developer.
  • RemoteSigned — You can run your own scripts or scripts signed by a trusted developer.
  • Unrestricted — You can run any script you want.

To change the execution policy setting, use the Set-ExecutionPolicy cmdlet:

PowerShell Scripting Tutorial for Beginners.

Install modules and packages

Windows PowerShell can be extended with additional modules and packages from the PowerShell Gallery public repository or other sources.

You can use the Install-Module cmdletto install modules directly from the PowerShell Gallery. Then you can use the cmdlets and functions defined in the module just like built-in PowerShell commands.

The most commonly used modules include:

  • Active Directory
  • Microsoft Exchange Server
  • Azure Active Directory
  • Office 365 (M365)
  • SQL Server
  • SharePoint Server
  • Internet Information Services

For a complete list, run this cmdlet:

Get-Module -ListAvailable

PowerShell cmdlets

PowerShell includes a wide range of cmdlets (pronounced “command-lets”) for common administrative tasks, such as managing processes, services, files, and users. Each one performs a single function but they can be combined in PowerShell scripting.

Cmdlets have a verb-noun structure, where the verb indicates the action to be performed and the noun specifies the target of the action, such as Get-Help, Set-Item, Start-Service or Stop-Process. Other key verbs include Out, which is used to output something (such as a file), and New, which is used to create something (“new” is not a verb, of course, but it functions as one).

Cmdlets typically produce objects as output, allowing for easy manipulation and integration with other cmdlets and scripts.

Examples of PowerShell cmdlets

  • Get-Process: Gets the information about running processes of the system.
  • Get-Service: Retrieves the status of services on the system.
  • Get-ChildItem: Retrieves a list of files and folders in a directory.

Cmdlet aliases

Many cmdlets have one or more aliases, which are shortened versions of their names. For example, the following two commands perform the same action:

Start-Process notepad

start notepad

Similarly, you can use either of the following commands to stop the Notepad process:

Stop-Process -Name notepad

spps -Name notepad

To see all aliases, run the Get-Alias cmdlet:

Cmdlet parameters and arguments

Cmdlets accept parameters that control their behavior. Parameters are specified using a hyphen followed by the parameter name, such as -Name or -Path.

Some parameters accept arguments, which are values of a particular data type (data types are explained below).

For example, here is the syntax of the Get-Process cmdlet with its parameters in orange and their arguments in green:

Get-Process

[-Name <String[]>]
[-ComputerName <String[]>]
[-FileVersionInfo]
[-Module]
[-InputObject <Process[]>]
[-IncludeUserName] [-ExcludeUserName]
[-Credential <PSCredential>]
[-Id <Int32[]>]
[-IncludeTotalProcessorTime]
[-WhatIf]
[-Confirm]

Data types

Here are some common data types in PowerShell:

  • String: A string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). A string can include letters, numbers, symbols and spaces.
  • Integer: Integers are whole numbers without any decimal or fractional parts.
  • Double: Doubles are floating-point numbers with decimal precision, such as 3.14 or -0.5.
  • Boolean: Booleans are often used in conditional expressions and comparisons. The only possible values are true and false.
  • Hashtable: A hashtable is a collection of key-value pairs. Each key in a hashtable must be unique. Hashtables are often used to store and retrieve data using named keys.
  • Array: An array is a collection of ordered and indexed elements of the same data type, such as a set of names or integers. In PowerShell, you can create an array by assigning a comma-separated list of values enclosed in parentheses to a variable, as shown here:
$fruits = ("apple", "banana", "orange")

To access the elements of an array, you can use the index operator [n]. The index of the first element in the array is 0. Below is an example:

$fruits = ("apple", "banana", "orange")

Write-Host $fruits[0] # Output from first element: apple

Write-Host $fruits[1] # Output from second element: banana

Write-Host $fruits[2] # Output from third element: orange

You can modify the elements of an array by assigning a new value to an index:

$fruits = ("apple", "banana", "orange")

$fruits[1] = "grape"

Write-Host $fruits[1] # Output: grape

Variables

Variables are used to store and manipulate data in PowerShell. A variable is a named container that holds a value, such as a string, number, array or objects. PowerShell variables are loosely typed, meaning you do not need to declare the data type of a variable when you assign a value to it. The data type is determined dynamically based on the assigned value.

Variable names in PowerShell are comprised of the $ symbol followed by the name of the variable. Variable names are not case?sensitive, so, for instance, “$MyVariable” and “$myvariable” refer to the same variable.

Each variable has a scope that determines where is can be accessed: global, script, function or local. By default, variables are local to the scope in which they are created.

To assign a value to a variable, use the = operator, as shown in the following two examples:

$myVariable = "Hello, World!"

$number = 42

Pipes

Cmdlets can be connected using the pipeline operator |, which passes the output of one cmdlet to the next cmdlet. This enables creating one-line commands to perform complex operations.

For example, this command uses a pipe to output the specified string to a file:

"Hello, World!" | Out-File C:pstest.txt

And the following example gets all services and sorts them by their status:

Get-Service | Sort-Object -property Status

You can use multiple pipes. For instance, here the first command gets all services, the second filters for running services only, and the third command limits the output to just their display names:

Get-Service | WHERE {$_.status -eq "Running"} | SELECT displayname

Getting help

You can use Get-Help to see details about any cmdlet:

To get examples for a cmdlet, add the -Examples parameter:

Get-Help Get-Process -Examples

Some commonly used cmdlets

Working with files and folders

You can use PowerShell to simplify tasks such as creating, copying, moving, deleting and modifying file and folder properties.

By using pipelines, conditional logic and loops, you can perform more complex file and folder manipulation tasks. For example, you can use the Get-ChildItem cmdlet to retrieve a list of files in a directory, filter the results using the Where-Object cmdlet, and then use Remove-Item to delete the selected files.

Below are some common PowerShell cmdlets for working with files and folders:

  • Get-ChildItem: Retrieves a list of files and folders in a specified directory
  • New-Item: Creates new files and folders
  • Copy-Item: Copies files and folders from one location to another
  • Move-Item: Moves files and folders from one location to another
  • Remove-Item: Delete files and folders
  • Set-Item: Modifies the properties of files and folders.
  • Test-Path: Checks whether a file or folder exists at a specified path
  • Get-Content: Retrieves the content of a file and outputs it to the console
  • Set-Content: Writes content to a file, overwriting any existing content

Working with date and time

Below are some common PowerShell cmdlets for working with dates and time.

  • Get-Date: Use this cmdlet to retrieve the current date and time. You can also use it to convert strings to DateTime objects and format dates according to specific patterns.
  • Get-Date -Format: This cmdlet allows you to retrieve the current system date and time in a specific format. For example, you can use Get-Date -Format ‘yyyy-mm-dd’ to get the date in “YYYY-MM-DD” format.
  • Set-Date: This cmdlet allows you to set the system date and time.
  • New-TimeSpan: This cmdlet is used to calculate the time span between two dates. It returns a Timespan object representing the time difference, which can be used for further calculations or formatting.

Below are some examples of how you can work with dates and time in PowerShell.

To get the current time and date:

$currentDateTime = Get-Date

To create a DateTime object for a specific date in past:

$customDate = [DateTime]::Parse("2023-11-10")

Calculate the time span between the current date and a past date and store it in the variable $timeDifference:

$timeDifference = New-TimeSpan -Start $currentDateTime -End $customDate

Print the value of the variable $timeDifference:

Write-host $timeDifference

PowerShell scripting

PowerShell scripting is a powerful way to automate tasks, manage systems and perform various operations using the PowerShell scripting language.

PowerShell Integrated Scripting Environment (ISE)

The built-in Integrated Scripting Environment enables PowerShell scripting in a graphical user interface. It provides a powerful set of features for creating, editing, debugging and executing PowerShell scripts, including multiline editing, tab completion, syntax coloring, selective execution and context-sensitive help.

Many of the same actions you can take in the Windows PowerShell console are available in menu items and keyboard shortcuts. For example, when debugging a script in the Integrated Scripting Environment, you can right-click a line of code in the edit pane to set a breakpoint. Whether you are a beginner or an experienced PowerShell user, the PowerShell ISE can streamline your workflows and increase your productivity.

To launch the PowerShell ISE, enter powershell ise in the Start menu:

Key elements of the PowerShell ISE include:

  • Menu bar: The Menu bar offers drop-down menus for File, Edit, View, Tools, Debug, Add-ons and Help.
  • Toolbar: The toolbar under the Menus bar provides buttons that perform actions such as copy, cut, paste, run script, run selection and stop operation.
  • Scripting tabs: Under the toolbar in the screenshot above, you can see several tabs. Each one is a workspace for writing and running a PowerShell script. The fully qualified path of the script file is displayed in a tooltip when you place mouse cursor on the script tab.
  • Status bar: At the very bottom of the screen under the scripting tab is a status bar that shows the completion status of the commands and scripts you have run and any error messages.
  • Commands pane: On the right side of the PowerShell ISE is a pane that lists all available commands.
  • Text-size slider: At the bottom right is a slider you can use to increase or decrease the size of the text on the screen.

Sample scripts

Below is a simple example of a PowerShell script that demonstrates how to define variables, use an if-else statement and print a message in the PowerShell console.

# Define variables

$name = "Jennifer"

$age = 35

# Display a greeting based on the age

if ($age -ge 18) {

    Write-Host "Hello, $name! You are an adult."

} else {

    Write-Host "Hello, $name! You are a minor."

}

Here is another simple PowerShell script; it prompts the user for their name and then greets them:

# Prompt the user for their name

$name = Read-Host "Enter your name"

# Greet the user

Write-Host "Hello, $name! Welcome to PowerShell scripting."

Adding comments to scripts

Leaving comments in your scripts will help you — and your colleagues — better understand what they do. A one-line comment starts with a number sign (#), and a block comment starts with “<#” and ends with “#>”.

Brackets, parentheses and braces

In PowerShell, delimiters are used for many purposes, including defining arrays, accessing elements, grouping expressions and specifying script blocks. Here are some of the most common:

  • Square brackets: Square brackets ([]) are used to define and access elements of an array.
$fruits = @("apple", "banana", "orange")

Write-Host $fruits[0]  # Output: apple
  • Parentheses: Parentheses are widely used in PowerShell, such as to pass arguments, enclose multiple instructions sets or resolve ambiguity. The operator $() is used when you need to nest parentheses in a command.
$result = $("The result is: " + (2 + 3))

Write-Host $result #Output: The result is: 5
  • Curly braces: Braces ({}) are used to define script blocks, which are used in control structures like loops and conditional statements (described below), as well as with cmdlets like ForEach-Object and Where-Object. For example:
$numbers = @(1, 2, 3, 4, 5)

$filtered = $numbers | Where-Object { $_ -gt 3 }

Write-Host $filtered  # Output: 4 5

Loops

Loops are used in PowerShell scripts to repeat a block of code multiple times. Here are the most common types of loops:

  • For loop: Used to execute a block of code a number of times based on the factors specified. Below is an example that will execute a write statement 5 times:
for ($i = 1; $i -le 5; $i++) {

Write-Host "Iteration $i"

}
  • ForEach loop: Iterates through the elements in a collection, such as an array or a set of objects, and executes the code for each one. Here’s an example:
$colors = "Red", "Green", "Blue"

foreach ($color in $colors) {

       Write-Host "Color: $color"

}
  • While loop: Executes a block of code as long as a certain condition is met. Below is an example.
$i = 1

while ($i -le 5) {

    Write-Host "Iteration $i"

    $i++

}
  • Do-While loop: Similar to a “while” loop but guarantees that the block of code is executed at least once before the condition is checked. Here’s an example:
$i = 1

do {

    Write-Host "Iteration $i"

    $i++

} while ($i -le 5)

Conditions

Conditions are used to control the flow of PowerShell scripts. Here are some conditional statements in PowerShell:

  • If statement: Executes the code if (and only if) the specified condition is true. Here’s an example:
$num = 10

if ($num -gt 5) {

    Write-Host "The number is greater than 5"

}
  • If-else statement: Extends the “if” statement by providing a block of code to execute if the condition is not true. Here’s an example:
$num = 3

if ($num -gt 5) {

    Write-Host "The number is greater than 5"

}

else {

    Write-Host "The number is not greater than 5"

}
  • Else-if statement: Allows for specifying multiple conditions to be checked in sequence instead of just two. Here’s an example:
$num = 5

if ($num -gt 5) {

    Write-Host "The number is greater than 5"

}

elseif ($num -eq 5) {

    Write-Host "The number is equal to 5"

}

else {

    Write-Host "The number is less than 5"

}

PowerShell scripting tutorial summary

This tutorial covered all the PowerShell basics, from how to install and configure PowerShell to running common commands to writing more complex PowerShell scripts. Keep in mind that if you forget something, you can always use the Get-Help cmdlet!

Additional resources

Useful PowerShell scripts

Manage AD users

Manage AD computers

Manage groups and OUs

Manage other things

Advanced PowerShell scripting guidance

Other resources

Microsoft’s FAQ

Is PowerShell hard to learn?

Getting started with Microsoft PowerShell can be really easy, since the language is simple and you can easily get information about any cmdlet. But it’s essential to also understand the systems you are interfacing with, so that your scripts do not lead to serious issues, such as system downtime or security incidents.

Where do I start learning PowerShell?

We recommend Windows PowerShell Scripting Tutorial for Beginners. It covers PowerShell scripting basics, including how to run PowerShell scripts and use the most common PowerShell commands. Another good source is the PowerShell page on the Microsoft website, which includes a solid introductory course.

Ben is the Technical Product Manager for Netwrix Privilege Secure. He came to Netwrix via Stealthbits Technologies, where he worked as an engineer on StealthAUDIT (now Netwrix Enterprise Auditor). Ben holds a Master’s degree in mathematics from Louisiana State University.