PowerShell Basics: Your Quick Reference Guide!

PowerShell has become one of the most pivotal technologies for IT professionals and system administrators working in the modern enterprise landscape. PowerShell allows you to easily automate repetitive tasks, improving overall productivity and providing more time to focus on higher-value tasks. Whether you manage on-premises Windows servers or cloud infrastructure on Azure, mastering PowerShell automation is now mandatory.

Yet, many administrators, even experienced ones, can feel overwhelmed when first learning PowerShell scripting. Getting over that initial learning curve to go from zero experience towards confidently writing scripts for real-world infrastructure automation may seem daunting. Where do you even begin, and what core concepts are vital to learning?

This is where this all-encompassing PowerShell quick reference guide aims to help. Consider it your treasure map, leading the way to mastering essential PowerShell skills. We’ll be covering everything from basic to advanced scripting, with plenty of actionable examples in between.

Follow this guide on a journey toward elevating your PowerShell knowledge. It’s the fastest route towards unlocking the immense power behind this automation framework used by hundreds of thousands of IT pros worldwide. The valuable scripting skills you’ll acquire here can pay dividends for your career while also saving many hours compared to repetitively clicking through GUIs.

So let’s get started! This reference will level up your PowerShell game faster than you imagined.

Getting Started with PowerShell

powershell tutorials

PowerShell is a command-line scripting tool that helps you automate and quickly solve tedious administrator tasks. Microsoft originally developed it for task automation and configuration management purposes. PowerShell combines the Power of the command-line shell and a scripting language! PowerShell is optimized for dealing with structured data, REST APIs, and object models. This quick reference guide will help you learn and master PowerShell, from the basics to advanced scripting.

Some examples of administrative tasks you can accomplish with PowerShell include:

  1. Windows PowerShell configuration changes, such as modifying the execution policy or importing modules
  2. User and group management through Active Directory
  3. File and folder management, including creating, deleting, renaming, and moving
  4. Windows service management, such as starting and stopping services
  5. PowerShell server automation, including managing virtual machines, databases, and network devices

By mastering the art of automation with PowerShell, you can transform the way you manage your systems and improve overall productivity significantly.

What exactly is PowerShell?

  • Windows PowerShell serves as an extremely efficient tool for managing system operations.
  • PowerShell is a versatile, cross-platform tool that combines a command-line shell, scripting language, and configuration management framework.
  • It’s a powerful compass that enables users to navigate through the vast sea of tasks that would typically be done through a graphical user interface.
  • PowerShell is highly preferred by corporate administrators for managing complex operations across large corporate networks with different PowerShell commands.

PowerShell scripts act as the engine that propels the system. A PowerShell script is a text file with a .ps1 extension, which contains commands for the PowerShell console to execute. These scripts are the heart of PowerShell, vital for automating tasks and managing systems. For instance, a script named Datecheck.ps1, which contains the command “Get-Date!”, is the most basic example of a PowerShell script.

To get the most out of PowerShell, consider it as a process of learning navigation. Start with the PowerShell console and the command line interface, gradually progressing to the comprehensive GUI for utilizing PowerShell. The key to mastering this navigation is familiarizing oneself with the extensive range of PowerShell commands available.

PowerShell also provides an administrator full access to COM, WMI and supports API calls from several applications, Such as:

  • SharePoint
  • Exchange Server
  • Windows Desktop OS, Server OS
  • SQL Server
  • VMWARE/Citrix 
  • Office 365, Azure, etc.

Installing and Upgrading PowerShell 7

Now that we’re underway, let’s make sure our Windows operating system is in optimal condition. To keep up with the changing tides, we need to upgrade to PowerShell 7. As the most recent version, PowerShell 7.3 (7.4 in preview mode) is available to all, even to Windows 7 users, albeit with some additional requirements.

PowerShell 7 is the most recent major version built on .NET Core to provide cross-platform support for Linux, macOS, and Windows. Here are the steps to get the latest PowerShell:

  • On Windows 10 and Windows Server 2019, PowerShell 7 comes pre-installed. Search for “PowerShell 7” to launch.
  • For older Windows OS versions: Update to PowerShell 7.
  • For Linux or macOS, install PowerShell via package manager like apt-get, yum or Homebrew.
  • Upgrade the existing PowerShell version by running the installation package to migrate settings.

Quick Launch Guide: Accessing PowerShell

executing powershell script

There are different ways to access PowerShell, depending on your needs and experience. Beginners can launch PowerShell through the console for simple commands, while advanced users can opt for the Integrated Scripting Environment (ISE) for a more comprehensive and user-friendly graphical interface.

Accessing the PowerShell console is as simple as:

  1. Typing “PowerShell” in the search field of the taskbar
  2. Selecting the “PowerShell 7x” result
  3. Selecting “Run as administrator” to launch PowerShell as an administrator.
opening powershell

Once the journey has started, there are ways to navigate and get help. The Get-Help command in PowerShell is like a trusty map, providing assistance and guidance about PowerShell commands and topics.

How do you write a PowerShell script?

To write a PowerShell script, follow these steps:

  1. Open a text editor: You can use Notepad, Visual Studio Code, PowerShell ISE or any other text editor of your choice to write PowerShell scripts.
  2. Write your PowerShell code: PowerShell scripts are composed of commands and scripts that use PowerShell cmdlets and functions. You can perform various tasks using PowerShell, such as file manipulation, system administration, and more.
  3. Save the script with a .ps1 extension: When saving your script, use the .ps1 file extension. For example, you can save your script as “MyScript.ps1”.

PowerShell ISE and Visual Studio Code

Managing system administration and IT can sometimes be challenging, especially when dealing with a Windows Server. That’s where the Windows PowerShell Integrated Scripting Environment (ISE) and Visual Studio Code come in, providing an interactive command line interface, including the Windows command line and Windows command prompt.

The PowerShell ISE is the default editor for Windows PowerShell, providing a window-based graphical user interface to run commands, write tests, and debug scripts. ISE is more than just a tool; it’s a companion. With features like syntax highlighting, multiline editing, tab completion, selective execution, and the capability to open multiple script windows simultaneously, it makes navigating the PowerShell sea a breeze.

Create and Execute PowerShell Scripts Using Visual Studio Code

Visual Studio Code (VS Code) is a free, open-source, and powerful code editor developed by Microsoft. It’s a great tool for creating and running PowerShell scripts. Here’s a step-by-step guide to get you started:

  1. Install Visual Studio Code: If you haven’t installed VS Code yet, download and install it from the official website.
  2. Install PowerShell Extension: Open VS Code, go to the Extensions view by clicking on the Extensions icon on the Activity Bar on the side of the window. Search for “PowerShell” in the search box and install the PowerShell extension provided by Microsoft.
  3. Create a New PowerShell Script: To create a new PowerShell script, click on “File” > “New File” (or use the shortcut Ctrl+N). Save the file with a .ps1 extension to tell VS Code that it’s a PowerShell script.
  4. Write Your Script: Now you can start writing your PowerShell script. VS Code provides features like syntax highlighting and IntelliSense (code completions) which make writing scripts easier.
  5. Run Your Script: To run your script, you can right-click anywhere in the script and select “Run PowerShell Script” from the context menu. Alternatively, you can use the F5 key to run the script. The output will be displayed in the Terminal pane at the bottom of the VS Code window.
edit powershell in visual studio code

Remember, you can also use VS Code’s debugging features to set breakpoints, step through your code, inspect variables, and see the call stack. You can start a debugging session by clicking on the “Run” icon on the Activity Bar and then clicking on the “Start Debugging” button (or by pressing F5). More here: How to use Visual Studio Code to Create and Run PowerShell Scripts?

PowerShell’s Execution Policy

PowerShell scripts are the foundation of the platform’s flexibility and strength in automation. Executing a script is as simple as entering its path in the PowerShell console. However, users must first ensure the correct execution policies are in place to allow the running of scripts, typically by setting it to RemoteSigned to run self-authored scripts while preventing unsigned scripts from other users.

  1. Launch PowerShell with administrator privileges.
  2. Set the appropriate execution policy (e.g., RemoteSigned) using the Set-ExecutionPolicy cmdlet.
  3. Enter the path to the script file in the PowerShell console, then press Enter to execute the script.

Before executing any PowerShell script, it’s essential to understand the various PowerShell execution policies available and how they affect script execution:

Execution PolicyDescription
RestrictedScripts are not allowed to run. This is the default policy for Windows operating systems.
AllSignedOnly scripts signed by a trusted publisher can be executed. Users will be prompted to accept the publisher’s certificate.
RemoteSignedLocal scripts can be executed without a digital signature, but remote scripts (downloaded from the internet) must be signed by a trusted publisher.
UnrestrictedAny script can be executed, regardless of its signature. This poses a significant security risk and is not recommended for most users.

Note: While using the unrestricted execution policy enables the execution of any script, it poses severe security risks. It is recommended to use the RemoteSigned execution policy for most use cases.

By following these guidelines and ensuring the appropriate execution policies are in place, you can leverage the power of PowerShell scripts to automate tasks and perform complex system management effectively and securely.

To change the Execution Policy, execute the below script from the PowerShell command window.

Set-ExecutionPolicy RemoteSigned

To further your understanding, refer to How to fix the “Running scripts is disabled on this system” error in PowerShell.

Introduction to PowerShell Cmdlets

Cmdlets are the heart of operating within PowerShell, offering single-function commands that work with .NET objects rather than text. The vast array of over 200 cmdlets allows users to perform a range of tasks, from manipulating files to custom scripting. For those new to PowerShell, the Get-Command cmdlet is a particularly useful feature, helping users discover the appropriate cmdlets for various operations.

Create an image of various electronic devices with a glowing blue aura, symbolizing their seamless integration with PowerShell cmdlets. PowerShell commands follow a consistent pattern, usually in the form of Verb-Noun. The verb specifies the action, and the noun represents the object to which the action is applied. For example:

  • Get-Location
  • Move-Item
  • New-Item

By using the Get-Command cmdlet, you can find cmdlets relevant to your task. The table below shows some frequent cmdlets:

CategoryCommand or CmdletDescription
BasicsGet-HelpDisplays detailed information about a cmdlet, usage, and examples.
BasicsGet-CommandDisplays a list of all available cmdlets and functions in PowerShell.
Files & FoldersGet-ChildItemDisplays items (files and folders) in a specified directory.
Files & FoldersCopy-ItemCopies a file or folder from one location to another.
SystemGet-ProcessDisplays a list of currently running processes on the system.
SystemRestart-ServiceRestarts a specified Windows service.
RegistryGet-ItemPropertyRetrieves the properties of a specified registry key or item.
RegistryNew-ItemPropertyCreates a new property for a specified registry key or item.

To gain further insight into a specific cmdlet, use the Get-Help cmdlet followed by the cmdlet name, which displays detailed documentation on its use and parameters. Familiarity with these essential cmdlets enables you to harness PowerShell’s capabilities for an extensive range of tasks, from simple file management to complex automation scripts.

Essential PowerShell Commands You Should Know: Select-Filter-Sort

Much like a seasoned sailor mastering essential knots, a skilled PowerShell user must become proficient in essential commands. Among these are:

  • Select-Object: allows you to select specific properties from an object
  • Where-Object (Filter): allows you to filter objects based on specified criteria
  • Sort-Object: allows you to sort objects based on specified properties

These commands are essential for selecting, filtering, and sorting data in scripts.

These commands are the ropes and knots of PowerShell, holding together the various tasks and processes that make up a script. Mastering these commands allows a PowerShell user to manipulate data effectively, akin to a seasoned sailor who can tie any knot at a moment’s notice. To further enhance your skills, consider exploring a PowerShell scripting tutorial. Master these day-to-day administrative PowerShell cmdlets:

Select, filter and sort data

Select-Object, Where-Object, Sort-Object

File system

Get-ChildItem, Copy-Item, Remove-Item


Get-Process, Stop-Process

Variables and Data Types

In PowerShell, variables and data types are dynamic, constantly changing and impacting the flow of operations. Variables in PowerShell are containers that can store various types of data. PowerShell supports various data types, including but not limited to:

  • Integers: These are whole numbers, both positive and negative.
  • Strings: These are sequences of characters, used to represent text.
  • Arrays: These are ordered collections of values, where each value is identified by an index.
  • Hash tables: These are collections of key-value pairs, where each value is identified by a unique key.

You can define variables to store all types of data like strings, integers, arrays, objects etc.:

$myVar = "PowerShell variables" 
$number = 10

Mastering Pipelines in PowerShell

Becoming proficient in the use of pipelines and objects in PowerShell is similar to mastering sailing techniques. Pipelining refers to the process of feeding the output of one command into another, which enhances the efficiency and effectiveness of command execution.

Get-Process | Where-Object CPU -GT 50

This pipelines processes by CPU into the Where filter. Just as a seasoned sailor knows how to use every rope on the ship, a proficient PowerShell user understands how to leverage objects. Objects are containers of structured data that can be manipulated, passed to other commands, or stored for later use.

Comments in PowerShell Scripts

In the realm of PowerShell, comments are like the secret notes of a seasoned sailor, providing valuable insights and explanations. They are non-executable lines in your scripts that are ignored by the PowerShell engine and primarily used for documentation and readability purposes.

There are two types of comments in PowerShell:

  • Single Line Comments: These are lines preceded by a hash symbol (#). Everything after the # on the same line is considered a comment.
  • Multi-line Comments: These are blocks of text enclosed between <# and #>. Everything within these tags is considered a comment.
# This is a single line comment
Get-Service # This gets a list of services

   This is a multi-line comment.
   It can span multiple lines.

Just as a sailor’s notes can provide valuable insights for future voyages, comments in PowerShell scripts can provide valuable insights for future code review and maintenance. They are the sailor’s notes of the PowerShell sea, guiding future travelers and making the journey smoother. More here: How to Add Comments in PowerShell Scripts?

Getting Help in PowerShell

PowerShell, like a vast ocean, is full of mysteries and treasures. But fear not, as it also has a built-in guide, the Get-Help command, which acts as your trusty sea chart.

The Get-Help command is an invaluable tool for beginners and experienced users alike. It provides detailed information about PowerShell cmdlets and concepts. Simply type “Get-Help” followed by the cmdlet or concept you need help with, and PowerShell will display a comprehensive guide.

For example, if you need help with the Get-Process cmdlet, you would type “Get-Help Get-Process”. PowerShell will then display information about the cmdlet, including its syntax, parameters, outputs, and examples of how to use it.

Moreover, you can use parameters with the Get-Help command to customize the output. For instance, the -Detailed parameter provides more detailed information, while the -Examples parameter only shows examples of how to use the cmdlet.

Get-Help -verb get
Get-Help -noun file
Get-help  stop-process -examples
Get-help  stop-process -full
Get-help SP*

PowerShell Shortcuts and Aliases

In PowerShell, aliases are shortcuts to secret sea routes known only to experienced sailors. They help expedite tasks and make command execution more efficient. For instance, tab completion in PowerShell is a feature that helps in cycling through commands, flags, and paths by typing the beginning of the command and pressing the TAB key, similar to the functionality in the command prompt.

Set-Alias -Name gs -Value Get-Service
gs #Now runs Get-Service

Just as a seasoned sailor knows every nook and cranny of his ship, a proficient PowerShell user knows the shortcuts and aliases like the back of his hand. They make navigating the PowerShell sea smoother and faster, ensuring a successful voyage every time. To learn more on aliases in PowerShell, refer to: PowerShell Aliases: A Beginner’s Guide

PowerShell Operators

As a sailor uses a compass, a map, and stars for navigation, a PowerShell user employs operators to guide through the script. PowerShell includes the following types of operators:

Here’s a list of these operators supported in PowerShell:

Arithmetic+, -, *, /, %Addition, subtraction, multiplication, division, modulus
Assignment=, +=, -=, *=, /=, %=Assigns values to variables
Comparison-eq, -ne, -gt, -ge, -lt, -leEquality, non-equality, greater/less than, greater/less than or equal
Logical-and, -or, -notLogical AND, OR, and NOT
Bitwise-band, -bor, -bxor, -bnot, -shl, -shrBitwise operations
String+, -replace, -match, -notmatch, -like, -notlikeString concatenation and comparison
Redirection>, >>, 2>, 2>&1Redirects output to files or streams
Array,, +, -Array manipulation
Member Access.Accesses properties and methods of objects
Type-is, -isnot, -asTests or converts object types
Special Operators$_, ${}, @(), @(,), $null, $$, $^Various special purposes like pipeline variable, null value, etc.

Here is an example demonstrating some common comparison and logical operators in PowerShell:

#Comparison Operators

$num1 = 10
$num2 = 20

$num1 -eq $num2 #equals, will return false
$num1 -ne $num2 #not equals, will return true
$num1 -gt 5 #greater than, will return true

#Using comparison operators in if statements
if ($num1 -le 15) {
  "Number less than or equal to 15"

#Logical operators
$process1Running = $true
$process2Running = $false

if ($process1Running -and $process2Running) {
  "Both processes are running" #False condition 

if ($process1Running -or $process2Running) {
  "At least one process is running" #True condition

These operators are the compass points of PowerShell, guiding the user in making decisions and performing tasks within scripts. They are the lighthouses in the sea of PowerShell, guiding the way in the dark.

Objects & Arrays in PowerShell

Objects and arrays in PowerShell function like cargo, housing valuable data and information. An object is a data structure that contains properties and methods, while an array is an object that can store multiple items simultaneously.

In PowerShell, almost everything is an object. An object is a data structure that stores data (properties) and actions (methods).

# Creating a simple custom object
$person = New-Object PSObject -Property @{
    FirstName = 'John'
    LastName = 'Doe'
    Age = 30

# Accessing properties of an object
$person.FirstName  # Outputs 'John'
$person.LastName   # Outputs 'Doe'
$person.Age        # Outputs 30

# Calling a method on an object
# For example, converting a string to uppercase
$string = "hello world"
$upperString = $string.ToUpper()  # Outputs 'HELLO WORLD'


An array is a collection of items. In PowerShell, arrays are flexible and can even contain elements of different types.

# Creating an array
$numbers = 1, 2, 3, 4, 5

# Accessing elements of an array
$numbers[0]  # Outputs 1 (first element)
$numbers[2]  # Outputs 3 (third element)

# Arrays can contain different types
$mixedArray = 10, "Hello", $true, 3.14

# Adding an element to an array
$numbers += 6  # Adds 6 to the end of the array

# Iterating over an array
foreach ($number in $numbers) {
    Write-Host $number

Just as a ship’s cargo holds the wealth of the voyage, objects and arrays in PowerShell hold the wealth of data. They allow for efficient data storage and manipulation, ensuring a successful journey in the PowerShell sea. More here: PowerShell Array: All You Need to Know!

PowerShell Control flow: Loops

powershell guide

In PowerShell, loops function like the steady rhythm of ocean waves, unchanging and repetitive. The primary looping constructs in PowerShell are the Do While loop and the ForEach loop.

Just as a sailor can predict the rhythm of the waves, a proficient PowerShell user can master the rhythm of loops. These constructs are used for repetitive tasks and iterating through data, ensuring a smooth and efficient journey. PowerShell provides a variety of looping constructs for repetitive tasks and iterating through data. The primary looping constructs in PowerShell are:

  • Do-While Loop: This loop continues to execute a block of statements as long as a specified condition remains true. The condition is checked after each iteration, which guarantees that the loop will execute at least once.
  • For Loop: This loop repeats a block of statements for a specified number of times. It’s typically used when the exact number of iterations is known.
  • ForEach Loop: This loop executes a block of statements for each item in a collection or array.
  • While Loop: Similar to the Do-While loop, this loop continues to execute as long as a specified condition remains true. However, the condition is checked before each iteration, meaning the loop may not execute at all if the condition is initially false.

Mastering these loops allows for efficient repetition of tasks and data iteration, ensuring a smooth and efficient journey in the PowerShell sea.

For Loop in PowerShell

Repeat tasks efficiently using PowerShell’s ForEach and For loop statements:

# for loop example
for ($i = 0; $i -lt 5; $i++) {
    Write-Host "The value of i is $i"

The ForEach takes the below syntax:

$numbers = 1, 2, 3, 4, 5
foreach ($number in $numbers) {
    Write-Host $number

Further Reading:

While Loop

The while loop repeats a block of code as long as the specified condition is true.

# while loop example
$count = 1
while ($count -le 5) {
    Write-Host "Count is $count"

Learn more: Mastering PowerShell While Loops: A Comprehensive Guide

Do-while Loop

The do-while loop also repeats a block of code as long as the condition is true, but the code block is executed at least once because the condition is evaluated after the block execution.

# do-while loop example
$count = 1
do {
    Write-Host "Count is $count"
} while ($count -le 5)

Do-until Loop

Similar to do-while, but it continues until a specified condition becomes true.

# do-until loop example
$count = 1
do {
    Write-Host "Count is $count"
} until ($count -gt 5)

These loop constructs provide flexibility for iterating over data and repetitive tasks in PowerShell scripts. You can learn more here: PowerShell: How to use Do-While, Do-Until Loops?

Using conditional statements in PowerShell

PowerShell Learning

In PowerShell, conditional statements and comparisons act like a rudder, directing the script towards the desired path. They allow for decision-making within scripts, directing the flow of execution based on the outcome of the comparison.

# if, elseif, else example
$age = 18
if ($age -lt 18) {
    Write-Host "Underage"
} elseif ($age -eq 18) {
    Write-Host "Just turned 18"
} else {
    Write-Host "Over 18"

More here: How to Use the If Else Statement in PowerShell?

The switch statement allows you to test a variable against a series of values. You can learn more here: PowerShell Switch Statement: The Beginner’s Guide!

# switch statement example
$color = "Red"
switch ($color) {
    "Red" {
        Write-Host "Color is Red"
    "Blue" {
        Write-Host "Color is Blue"
    "Green" {
        Write-Host "Color is Green"
    default {
        Write-Host "Another Color"

Just as a skilled sailor can steer his ship in any direction, a proficient PowerShell user can steer a script towards the desired outcome using conditional statements and comparisons. They are the rudder of the PowerShell ship, guiding the script safely to its destination.

Filtering with the ‘Where’ Command in PowerShell

In the PowerShell scripting language, the ‘Where’ command, also known as the ‘Where-Object’, acts like a filter in a sailor’s navigation system, helping to sort through a sea of data to find the information that is most relevant.

The ‘Where’ command filters the output of a command, allowing you to see only the objects that meet certain criteria. It’s like a net that catches only the fish (or data) that you’re interested in.

Here’s a simple example of how it works:

Get-Process | Where-Object {$_.CPU -gt 1000}

In this example, the ‘Get-Process’ command retrieves all the running processes on the system. The output is then piped (‘|’) to the ‘Where-Object’ command, which filters out all the processes whose CPU usage is greater than 1000.

Just as a sailor uses a net to catch fish, a proficient PowerShell user uses the ‘Where’ command to catch and filter data. It’s an invaluable tool in the PowerShell toolkit, helping you to navigate the vast sea of information in your system. More here: How to Use the PowerShell Where-Object cmdlet to filter?

PowerShell Functions

In the realm of PowerShell, functions serve as the propellers of our system. They carry out specific tasks and can be reused throughout the script, making the code more modular and efficient.

#Define function
Function sayHello()
  write-host "Hello"

#Call the function

Just as a sailor adjusts the sails to best catch the wind, a proficient PowerShell user can adjust and customize functions to best meet the needs of the script. They are the sails of the PowerShell ship, capturing the winds of efficiency and propelling the script towards its destination. Learn more here: PowerShell Functions: A Comprehensive Beginner’s Guide

Exporting and Importing Data to CSV in PowerShell

In PowerShell, exporting and importing data to a CSV file is a way to save data and reuse it later, ensuring a smooth and efficient journey. PowerShell provides two cmdlets for this purpose: Export-Csv and Import-Csv.

In its vast arsenal of capabilities, PowerShell provides a handy cmdlet for exporting data into a CSV file format. This cmdlet, known as Export-Csv, allows us to save and document our data, which we can then reuse or analyze at a later time.

The Export-Csv cmdlet in PowerShell allows you to export data to a CSV file. It’s like marking your current position on a map for future reference. Here’s how you can use it:

# Create a variable to hold the data
$data = Get-Process

# Export the data to a CSV file
$data | Export-Csv -Path .\ProcessData.csv -NoTypeInformation

In this example, we first get a list of all processes using the Get-Process cmdlet and store it in the variable $data and then use the Export-CSV cmdlet to export it to a CSV file.

Import from CSV file in PowerShell

Importing data from a CSV file in PowerShell is straightforward and can be done using the Import-Csv cmdlet. This cmdlet reads the CSV file and converts it into a collection of custom objects where the properties of the objects are derived from the column headers in the CSV.

Here’s a basic example to illustrate how you can import data from a CSV file:


Now, you can write a PowerShell script to import this CSV file:

# Path to the CSV file
$CSVFilePath = "C:\Temp\UserData.csv"

# Import the CSV file
$UserData = Import-Csv -Path $CSVFilePath

# Display the imported data
$UserData | Format-Table Name, Age, Email

Error Handling in PowerShell

In PowerShell, errors are comparable to storms. They can disrupt the smooth sailing of a script. However, with try-catch blocks and error variables, these storms can be weathered.

try {
    # Code that might cause an exception
    $result = 1 / 0
catch {
    # Code to handle the error
    Write-Host "An error occurred: $_"
finally {
    # Code that runs regardless of whether an error occurred
    Write-Host "Cleanup actions go here."

Just as a seasoned sailor knows how to navigate through a storm, a proficient PowerShell user knows how to navigate through errors. They can handle and resolve errors, ensuring the script safely reaches its destination. Refer to my other post: Error Handling with PowerShell Try Catch Block: Demystified!

PowerShell Modules and Snap-ins: Extending Functionality

PowerShell modules act as additional propellers on our system, enhancing its capabilities and ensuring smoother operation. They provide additional commands, functions, and tools to extend the capabilities of PowerShell. Modules package together cmdlets, functions, variables, etc. Import modules using Import-Module <Path>:

Import-Module AzureRM #Import Azure Resource Manager module
Get-AzureRmVm #Now access Azure VMs

Just as a ship with more sails can travel faster and more efficiently, a PowerShell script with more modules can perform more tasks and do so more efficiently. They are the extra sails on the PowerShell ship, driving it forward towards its destination.  

Below is a table showcasing a few popular PowerShell modules:

Module NameDescription
Active DirectoryCmdlets for administering and managing Active Directory domains, domain controllers, and user accounts.
SqlServerA set of cmdlets for managing SQL Server instances, databases, and other configurations.
Exchange OnlineAllows administration of Office 365 Exchange online organization, mailboxes, and more from PowerShell.
PSReadLineProvides an improved command-line editing experience in the PowerShell console with features like syntax coloring, multiline editing, and rich history.
PnP PowerShellAllows automation of SharePoint online sites, content types, lists and more.
Microsoft TeamsAutomates the creation, setup and administration of Teams accounts.

To enhance your PowerShell experience, explore and experiment with different modules that cater to your specific needs. To manage module installation and updates, use the following cmdlets:

  • Find-Module – Discover modules available in the PowerShell Gallery.
  • Install-Module – Install a new module.
  • Update-Module – Update an existing module to the latest version.

PowerShell SnapIns

PowerShell contains hundreds of commands, which are called cmdlets. These application specific cmdlets usually warped to the “Snap-ins”. So, to use SharePoint cmdlets in PowerShell, You need to add the SharePoint PowerShell snap-in first.

To start with, Add PowerShell snapin to your script as the first line:

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Now, you can use PowerShell to interact directly with SharePoint Web Applications, Site collections, Sites, Lists, etc. E.g.,

Get-SPSite -identity "https://sharepoint-site-url"

PowerShell Remoting

PowerShell remoting functions like a long-range lens, enabling remote system management and distant command execution. It’s a feature that enables commands to be executed on local or remote systems. PowerShell remoting is enabled by default on Windows Server 2012 and later, but it needs to be manually enabled on client operating systems like Windows 10. Once enabled, you can use the Enter-PSSession cmdlet to start an interactive session with a remote computer or the Invoke-Command cmdlet to run a command or script on a remote computer.

Invoke-Command -ComputerName SERVER01 
{Get-EventLog -LogName Application -Newest 100}

Just as a captain uses a telescope to view distant lands, a proficient PowerShell user uses remoting to manage and control remote systems. It’s the telescope of the PowerShell ship, extending the user’s reach and enabling efficient management of remote systems.

Creating scheduled tasks to run PowerShell Scripts

Scheduled tasks in PowerShell act like a well-coordinated crew, performing tasks timely to ensure smooth system operation. They automate the execution of PowerShell scripts, making the journey more efficient.

To create a scheduled task in Windows to run a PowerShell script, you can use the Task Scheduler, which is a built-in Windows tool. Here are the general steps:

  1. Open Task Scheduler: You can search for “Task Scheduler” in the Start menu and open it.
  2. Create a New Task: In Task Scheduler, go to the “Action” menu and select “Create Task.”
  3. Configure the Task:
    • General Tab: Give your task a name and configure other settings like whether the task should run with highest privileges.
    • Triggers Tab: Set when and how often you want the task to run (e.g., daily, at a specific time).
    • Actions Tab: This is where you set up the task to run your PowerShell script.
      • Click “New,” and in the “Action” drop-down, select “Start a program.”
      • In the “Program/script” field, enter powershell.exe.
      • In the “Add arguments” field, enter -File "C:\path\to\your\script.ps1", replacing the path with the actual path to your PowerShell script.
    • Conditions Tab and Settings Tab: These tabs contain additional settings that control the behavior of the task.
  4. Save the Task: Once you’ve configured all the settings, click “OK” to save and schedule your task.

Ensure your script and Task Scheduler settings are correctly configured for your specific requirements. For more detailed guidance or specific scenarios, you might need to refer: How to Create a Scheduled Task to Run a PowerShell Script?

Just as a disciplined crew ensures the ship stays on course, scheduled tasks ensure that scripts are executed on time and in the right order. They are the disciplined crew of the PowerShell ship, ensuring a smooth and efficient journey.

PowerShell Across Platforms: Windows, macOS, Linux

PowerShell in Windows Mac Linux

PowerShell is not merely restricted to a single platform; it’s a comprehensive tool that extends across multiple platforms. From its Windows origins, PowerShell has expanded to macOS and Linux, becoming more versatile and accessible.

Core PowerShell functionality works across Windows, Linux and macOS, but some OS-specific cmdlets like managing Windows services have OS restrictions or alternatives.

Common PowerShell Errors and Their Solutions

In the world of PowerShell, errors are like unexpected storms that can suddenly hit your journey. But, just like any seasoned sailor, you can learn to navigate these storms and turn them into mere bumps on your voyage. Here are some common errors you might encounter in PowerShell and their solutions:

Parse Errors:

These errors occur when PowerShell cannot understand a piece of your script, usually due to syntax errors. The solution is to check your script for syntax errors, verify all code blocks, braces, brackets, and quotes are balanced, and correct them. E.g.,

-File C:\Script.ps1 : Missing opening or closing parenthesis.

Access Denied Errors:

These errors happen when you try to perform an action that you do not have the necessary permissions for. The solution is to run the script with elevated permissions or to change the permissions on the object you are trying to access.

New-Item : Access to the path 'C:\Folder' is denied.

Command Not Found Exception:

This error occurs when PowerShell can’t find the command you are trying to run. The solution is to check your spelling and ensure that the command exists. Import the correct module that contains the missing cmdlet.

Get-SomeCmdlet : The term 'Get-SomeCmdlet' is not recognized as the name of a cmdlet...

Terminating Errors:

These errors stop the execution of the script. They usually occur when a severe error happens, such as a missing required parameter in a cmdlet. To handle terminating errors, use try-catch-finally blocks.

try {
    # Attempting to create a directory in a non-existing drive
    New-Item -Path "X:\Temp" -ItemType Directory -ErrorAction Stop
catch {
    Write-Host -f Red "Caught a terminating error: $_"

Non-terminating Errors:

These are the most common errors in PowerShell. They do not stop the execution of the script and usually occur when a cmdlet encounters an error but continues to execute. To handle non-terminating errors, use the ErrorAction parameter with the value of Stop to make them terminating.

Get-ChildItem : Cannot find path 'C:\SomePath' because it does not exist

When encountering errors, the Get-Help, Get-Member, and Get-Command cmdlets can be invaluable for troubleshooting. Additionally, the error messages in PowerShell are usually quite descriptive, so reading them carefully can provide good clues for resolving the issue.

Remember, just like a sailor who learns to predict and navigate storms, a proficient PowerShell user learns to predict, handle, and correct errors. It’s all part of the journey in the vast sea of PowerShell.

Wrapping up

Mastering PowerShell scripting and automation is an essential skill for modern IT professionals, helping to streamline their workflows and boost productivity. As a cross-platform task automation tool, PowerShell offers powerful scripting capabilities, and this quick reference guide aims to provide users with the knowledge needed to excel in using the platform effectively.

By following this guide, you can enhance your understanding of PowerShell’s practical use across different operating systems, learn how to use its features, and discover its modules for extended functionality. From managing remote systems to automating tasks, PowerShell is a trusted compass guiding IT professionals and system administrators through the vast sea of tasks and processes. It’s a journey worth embarking on, filled with challenges, discoveries, and rewards, as we sail towards efficiency and precision.

“The secret of getting ahead is getting started.” – Mark Twain


How can I launch PowerShell as an administrator?

To launch PowerShell as an administrator, right-click on the Windows PowerShell search result and select “Run as administrator”.

How can I get a list of commands in PowerShell?

You can use the Get-Command cmdlet to retrieve a list of all PowerShell commands on your computer. Additionally, you can use Get-Help to view the syntax of individual cmdlets.

What are PowerShell modules?

Modules in PowerShell are used to extend its native capabilities through additional cmdlets and functions. They offer expanded operational scope, allowing users to enhance the tool according to their specific automation and configuration needs.

How do I run PowerShell scripts?

You can execute a PowerShell script by entering its path in the PowerShell console. Before running a script, ensure the correct execution policies are in place to allow the running of scripts, usually by setting it to RemoteSigned to run self-authored scripts while preventing unsigned scripts from other users.

What are cmdlets in PowerShell?

Cmdlets are single-function commands that work with .NET objects instead of text, allowing users to perform various tasks, such as manipulating files, modifying configuration settings, and running custom scripts.

Is PowerShell available on other platforms besides Windows?

Yes, PowerShell is open-source and cross-platform, which means it can be used on Linux and macOS as well as on Windows.

Which is the equivalent PowerShell command for CLS?

For clearing the screen in PowerShell, you can use the command Clear-Host;, its aliases cls; and clear;

Is PowerShell case sensitive?

PowerShell is case-insensitive for variable and cmdlet names by default, but it can perform case-sensitive operations when specified. For example, “MyVariable” and “myvariable” would be treated as the same variable. However, “Hello” -ceq “hello” would return False.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *