PowerShell Tutorial for Beginners – Start Here

PowerShell is an essential tool for system administrators and IT professionals. It is a powerful command-line shell and scripting language created by Microsoft. This tool is designed to help manage the Windows operating system and automate repetitive tasks.

Starting with PowerShell can seem complex for beginners, but you can start at the basics and work up to the advanced level. PowerShell allows users to automate tasks and manage systems more efficiently. It includes features like cmdlets, scripts, and providers for different administrative tasks.

A PowerShell tutorial for beginners should provide a step-by-step approach, starting with the basics, such as the PowerShell console and command syntax. Gradually, it will introduce scripting concepts, including variables, loops, and conditions, which are foundational for creating effective automation scripts.

Download 100+ PowerShell Cmdlet PDF FREE

How to Get Started with PowerShell?

Now, let me show you how to get started with PowerShell. First, we need to set up the PowerShell environment.

Install PowerShell

PowerShell comes pre-installed on Windows operating systems starting from Windows 7 SP1 and Windows Server 2008 R2 SP1. To install older versions or ensure you have the latest version, download the installer package from the official PowerShell GitHub page or through the Microsoft Store.

The following versions of Windows support PowerShell installations directly:

  • Windows 11
  • Windows 10
  • Windows 8.1
  • Windows 7 SP1

To install PowerShell on Windows 11, navigate to the Microsoft Store and search for “PowerShell”. Select the latest version and click “Install”.

Check out How to Update PowerShell on Windows 11?

Launch PowerShell

To launch PowerShell, use the search function in the Windows taskbar, type PowerShell, and select the application. Alternatively, press Win + X and select “Windows PowerShell” from the menu. In Windows 10, accessing PowerShell is straightforward with these steps:

  1. Type “PowerShell” in the Start menu.
  2. Right-click on Windows PowerShell.
  3. Select “Run as administrator” for elevated permissions.

To find the PowerShell version, type $PSVersionTable.PSVersion within the PowerShell environment and press Enter. This command outputs the version information

Use PowerShell ISE or Visual Studio Code for a more advanced scripting environment. To start PowerShell ISE, type powershell_ise.exe in the elevated Windows PowerShell.

Visual Studio Code offers a rich environment for PowerShell. Install the PowerShell extension from the Extensions view in Visual Studio Code. This allows you to write, debug, and run scripts efficiently.

PowerShell is also available across platforms, including Linux and MacOS. On these systems, install PowerShell 7 to access a similar feature set as on Windows. To install PowerShell on Linux, use commands like:

sudo apt-get install -y powershell

On MacOS, use:

brew install --cask powershell

Launch PowerShell by typing pwsh in the terminal on both Linux and MacOS after installation.

PowerShell Commands and Scripts

PowerShell scripting is a powerful tool for task automation and configuration management. To get started, you must understand its syntax, cmdlets, parameters, and script execution.

PowerShell Syntax

PowerShell uses a specific syntax that is essential for writing scripts. The basic components include commandskeywords, and symbolsCmdlets (pronounced “command-lets”) are built-in commands within PowerShell. They follow the Verb-Noun format, such as Get-Process.

Scripts are saved with a .ps1 extension. Commenting is done using # for single-line comments. Proper indentation and clear commands help in creating readable scripts. Variables are denoted with $, making them easy to identify.

PowerShell Cmdlets and Parameters

Cmdlets are the basic building blocks in PowerShell scripting. Each cmdlet has a specific purpose and can be combined to perform complex tasks.

Here are a few useful PowerShell commands.

  • Get-Command: Lists all cmdlets, functions, workflows, etc.
  • Get-Help: Provides help for a specific cmdlet.
  • Set-ExecutionPolicy: Changes the user’s execution policy.
  • Get-Service: Retrieves the status of services on a machine.
  • Get-Item: Retrieves items from a specified location.

Check out How to Prompt for Input in PowerShell? and PowerShell Prompt for Input Yes/No

Commands for Managing Files and Directories

PowerShell cmdlets can handle file and directory management with ease.

  • Get-ChildItem lists files and directories within a specified location. It can filter results using parameters like -Recurse to include all subdirectories. For example, Get-ChildItem -Path "C:\Users" -Recurse shows all files and folders under the Users directory.
  • Copy-Item copies files or directories from one location to another. Using Copy-Item -Path "C:\File.txt" -Destination "D:\Backup" creates a backup of File.txt.
  • Move-Item moves files or directories. For instance, Move-Item -Path "C:\File.txt" -Destination "D:\Documents" relocates File.txt to the Documents folder.
  • Remove-Item deletes files or directories. The command Remove-Item -Path "C:\OldFile.txt" permanently removes OldFile.txt from the system.

Check out tutorials on working with files and folders using PowerShell.

Run PowerShell Commands and Scripts

To run a command in PowerShell, one types the command name followed by its parameters and arguments. Running scripts is similar but requires pointing PowerShell to the script’s location.

For example, .\MyScript.ps1 executes a script named MyScript.ps1 located in the current directory.

To run a script from a different directory:

C:\Scripts\MyScript.ps1

What is the PowerShell Execution Policy

PowerShell includes several security features to protect your system. One key feature is the execution policy. This controls how scripts can be run on your computer. The main goal is to stop scripts from running without your permission.

There are several execution policies you can choose from:

  • Restricted: No scripts can run.
  • All Signed: Only scripts signed by a trusted publisher can run.
  • Remote Signed: Downloaded scripts must be signed by a trusted publisher.
  • Unrestricted: Any script can run, but you’ll get a warning before it runs.

To change the execution policy, use the Set-ExecutionPolicy cmdlet. For example, to set the policy to Remote Signed, type:

Set-ExecutionPolicy RemoteSigned

Remember, changing the execution policy might expose the system to security risks. Before modifying the execution policy, one should always ensure scripts are from a trusted source.

Here are a few basic PowerShell tutorials:

PowerShell Scripting Essentials

Before writing any PowerShell scripts, you should understand the basics of PowerShell programming. These elements include handling data types and variables, using control structures for decision-making, and managing errors and debugging scripts.

Data Types and Variables

In PowerShell, variables are used to store data that can be used and manipulated throughout the script. Variables are defined using the $ symbol. For example, $name = "John" assigns the string “John” to the variable $name.

PowerShell supports several data types:

Data TypeDescriptionExample
StringText enclosed in quotes.$name = "John Doe"
IntegerWhole numbers.$age = 30
DoubleFloating-point numbers.$price = 12.99
ArrayA collection of items, accessible by index$colors = 'red', 'blue'
BooleanTrue or false value$fileExists = $true
HashtableCollection of key/value pairs$person = @{Name="John"; Age=42}

Using data types and variables helps write efficient and readable scripts.

Read PowerShell Functions: Return Values and Multiple Values

PowerShell Control Structures

Control structures allow scripts to make decisions and repeat actions based on specified conditions. In PowerShell, conditional statements like ifelse, and elseif are commonly used. For instance:

if ($age -ge 18) {
    Write-Output "Adult"
} else {
    Write-Output "Minor"
}

Here are some PowerShell if else tutorials:

Loops in PowerShell

PowerShell offers several types of loops that allow you to repeat tasks efficiently. These include the For Loop, Foreach Statement, While Loop, and Do-While and Do-Until Loops.

The For Loop

The For Loop in PowerShell is ideal for iterating a set number of times. It uses a counter to keep track of the iterations.

Syntax:

for (<initialization>; <condition>; <increment>) {
    <script block>
}

Example:

for ($i = 1; $i -le 5; $i++) {
    Write-Output "Iteration $i"
}

In this example, the loop runs five times. The initialization sets the counter, the condition checks if the loop should continue, and the increment updates the counter.

The Foreach Statement

The Foreach Statement in PowerShell is best for iterating over collections, like arrays or hash tables. It processes each item in the collection one by one.

Syntax:

foreach ($item in $collection) {
    <script block>
}

Example:

$names = @("Alice", "Bob", "Charlie")
foreach ($name in $names) {
    Write-Output "Hello, $name"
}

This loop writes a greeting for each name in the array. It’s simple to use and ideal for tasks involving multiple items, each requiring the same operation.

The While Loop

In PowerShell, the While Loop continues running as long as its condition is true. It checks the condition before each iteration.

Syntax:

while (<condition>) {
    <script block>
}

Example:

$i = 0
while ($i -lt 3) {
    Write-Output "Count is $i"
    $i++
}

Here, the loop stops when $i reaches 3. It is often used for tasks where the number of iterations isn’t known beforehand but depends on some condition.

The Do-While and Do-Until Loops

The Do-While and Do-Until Loops in PowerShell are similar, but they check the condition after the loop body executes. This guarantees at least one execution of the loop block.

Syntax for Do-While:

do {
    <script block>
} while (<condition>)

Syntax for Do-Until:

do {
    <script block>
} until (<condition>)

Example of Do-While:

$i = 0
do {
    Write-Output "Count is $i"
    $i++
} while ($i -lt 3)

Example for Do-Until:

$i = 0
do {
    Write-Output "Count is $i"
    $i++
} until ($i -eq 3)

In these examples, the body of the loop executes first, and then the condition is checked.

Error Handling and Debugging

Error handling in PowerShell is crucial to ensure scripts run smoothly even when issues occur. PowerShell provides several ways to manage errors:

  • Try/Catch: Encloses code that might fail with try and handles errors with catch. Example:
try {
    $fileContent = Get-Content "C:\MyFile.txt"
} catch {
    Write-Output "File not found"
}
  • Error Variable$Error stores error messages from the most recent command. Example: Get-Content "C:\MyFile.txt" followed by $Error[0] shows the latest error.

Debugging tools are essential to find and fix issues in a PowerShell script. The Write-Debug cmdlet prints custom debug messages when the script is run in debug mode. Breakpoints can be set to pause execution and inspect variables.

PowerShell ISE and Visual Studio Code

Developers can write PowerShell scripts using the PowerShell Integrated Scripting Environment (ISE) or Visual Studio Code (VS Code) with the PowerShell extension.

  • PowerShell ISE: A built-in tool that offers a GUI for script development, with features such as syntax coloring, tab completion, and context-sensitive help.
  • Visual Studio Code: A sophisticated editor that supports PowerShell through a dedicated extension. This extension adds advanced functionalities like IntelliSense, debugging, and code navigation.
  • VS Code Extensions: Enhance the scripting experience with extra features. C# extension can be utilized for seamless .NET coding.

These are essential tools that you should use to write your PowerShell scripts.

PowerShell Tutorial for Beginners

Best Practices While Running Any PowerShell Script

While running a script in PowerShell, you should follow some best practices. Here are a few things to follow:

  • Use AllSigned or RemoteSigned policies to ensure a balance between security and flexibility.
  • When running scripts from internet sources, always review the code before execution to confirm its safety, even if it is signed.
  • Regularly check execution policies using Get-ExecutionPolicy to ensure they have not been altered unexpectedly.
  • Understand that the execution policy is not a definitive security measure but a part of a defense-in-depth strategy. Additional layers of security, such as antivirus software and user permissions, should also be in place to safeguard the system effectively.

PowerShell Providers and Modules

PowerShell Providers are a set of interfaces that allow access to different data stores. These data stores include the file system, registry, and certificate store.

Providers make it easier to navigate and manipulate these stores using a consistent cmdlet format, such as Get-ChildItem and Set-Item.

Examples of PowerShell Providers:

  • FileSystem: Access the file system.
  • Registry: Access the registry keys and values.
  • Certificate: Access X.509 certificates.

PowerShell Modules are collections of cmdlets, functions, providers, and other tools that help automate tasks. Modules make it easy to share and use toolsets.

Popular Modules:

  • ActiveDirectory: Manage Active Directory.
  • Azure: Manage Azure resources.
  • PSReadLine: Enhance the command-line experience.

To see all available modules on your system, use the command:

Get-Module -ListAvailable

To import a module for use in your session:

Import-Module <ModuleName>

To create a custom module, place your scripts in a .psm1 file and load it with Import-Module.

Benefits of Using Modules:

  • Modularity: Separate functionalities into distinct modules.
  • Reusability: Easily reuse scripts across different projects.
  • Versioning: Manage different versions of a module.

Example Commands:

  • Get-Module: List the modules.
  • Import-Module: Load a module.
  • New-Module: Create a new module.

Read PowerShell Function Examples with Parameters

PowerShell for System Administration

PowerShell is a powerful tool for automating many administrative tasks on Windows. It manages Windows services, handles system and network administration, and works with Active Directory.

Manage Windows Services

To work with Windows services, PowerShell provides a lot of useful commands like:

  • Get-Service: To get the status of services. The Get-Service command lets administrators list all services or filter by specific criteria
  • Start-Service: To start any Windows services
  •  Stop-Service to stop them. This helps in controlling services without needing to use the graphical interface.

System and Network Administration

PowerShell offers various cmdlets for system and network administration. Here are a few:

  • Get-Process is useful for viewing running processes.
  • Stop-Process to terminate processes that aren’t responding.
  • Test-Connection to ping a network
  • Get-ComputerInfo to get system information

Working with Active Directory

PowerShell provides a lot of commands to work with active directories (AD). Active Directory (AD) is essential for user and resource management. Here are a few commands:

  • Get-ADUser for retrieving user information
  • New-ADUser for creating new users
  • Get-ADGroup is used to get all AD groups
  • Add-ADGroupMember is used to get members from an AD group.

As an administrator, you can also do bulk operations like user creation, group management, and permissions assignment.

Remote Management with PowerShell

Remote management in PowerShell allows users to execute commands and manage systems from a central location.

What is PowerShell Remoting

PowerShell Remoting is a feature that allows users to run commands on remote machines. It is essential for managing multiple computers without needing physical access.

To enable remoting, use the Enable-PSRemoting cmdlet.

This sets up your machine to receive remote commands.

For running a command on multiple computers, the Invoke-Command cmdlet is used. An example command is:

Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { Get-UICulture }

This retrieves the UI culture settings from both Server01 and Server02.

The Enter-PSSession cmdlet allows users to start an interactive session with a remote computer. It’s ideal when you need to execute multiple commands interactively:

Enter-PSSession -ComputerName Server01

Ensure only authorized users can access remote management and always use encrypted connections.

Using Remote Sessions and Jobs

Managing remote systems efficiently can involve using remote sessions and background jobs. Remote sessions keep connections to remote machines active, which is useful for ongoing management tasks.

The New-PSSession cmdlet creates a persistent connection:

$session = New-PSSession -ComputerName Server01

Commands can then be run using this session:

Invoke-Command -Session $session -ScriptBlock { Get-Process }

Background jobs are useful for tasks that don’t need to be monitored actively. The Start-Job cmdlet runs commands in the background:

Start-Job -ScriptBlock { Get-EventLog -LogName System }

Check the status of these jobs with Get-Job and retrieve their results using Receive-Job:

Get-Job
Receive-Job -Id 1

As a PowerShell administrator, you can use remote management and automation to reduce the time and effort needed for routine tasks.

PowerShell Tutorials For Beginners

Here is the list of PowerShell tutorials for beginners.

Conclusion

I hope this guide will help you learn PowerShell as a beginner.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.