What is PowerShell and how to use it: The Ultimate guide

PowerShell is an object-oriented command-line shell and scripting language that automates the administration and maintenance of servers. It offers a variety of features and constructs to simplify the life of administrators.

In this article, we will delve into PowerShell, covering its key features, syntax, and semantics. Additionally, we will explore using PowerShell for remote connections, server management, and file system operations.

What is PowerShell and what can you do with it?

PowerShell comprises a command-line tool, a scripting language, and a configuration management framework.

  • Command-line tool: A dynamic shell that accepts and returns .NET objects. The object-oriented nature of the shell simplifies the process of creating and maintaining complex scripts.
  • Scripting language: The PowerShell scripting language leverages the .NET Common Language Runtime (CLR) to offer a comprehensive automation framework. It’s often used for server administration and for testing and deploying applications in CI/CD environments.
  • Configuration management: PowerShell Desired State Configuration (DSC) is a configuration-as-code platform that can manage infrastructure across all deployment stages, from testing and staging to pre-production and production. It uses PowerShell scripts, called DSC configurations, to define the desired state of an infrastructure.

Why would you want to use PowerShell?

There are many reasons to use PowerShell. Here are some common ones:

  • To automate administrative tasks: Whether you want to create and manage user groups, install or uninstall software, provision a multi-server environment, or manage permissions, PowerShell offers you an easy, declarative way to do so. Automating administrative tasks increases operational efficiency and decreases chances of human errors.
  • To troubleshoot problems: You can also use PowerShell to troubleshoot problems on a system. For example, you can use the shell to fetch real-time information about the system state, and you can run PowerShell commands to fix any problems.
  • To manage remote systems: Administrators can use PowerShell to connect to establish remote connections and execute commands. This is invaluable for distributed environments with many nodes and virtual machines (VMs).
  • To manage cloud-based services: Microsoft Azure, Amazon Web Services, and VMware all offer PowerShell modules that can be used to manage their cloud services and resources. These modules allow you to use the familiar PowerShell interface and language to manage your cloud infrastructure.
  • To write powerful scripts: PowerShell is a fully-featured scripting language that can be tailored to specific needs. It offers native support for CSV, XML, and JSON. It also has an extensible type and formatting system. These features empower administrators to automate intricate workflows, apply advanced system configurations, and solve complex business challenges.
  • To manage non-Windows resources: PowerShell is a cross-platform solution that can be used on Windows, Linux, and macOS. This makes it a great choice for managing hybrid environments where you have a mix of Windows and non-Windows systems.

Key features of PowerShell

Here are a few standout features of PowerShell:

  • Rich history: PowerShell can store command history at the session and global level. This allows you to access previously run commands, which can help troubleshoot problems or repeat tasks.
  • Extensible by design: PowerShell is extensible, allowing you to create your own cmdlets and modules to meet specific business needs.
  • Chaining commands: PowerShell supports command chaining, which allows you to string together multiple commands. For example, you can use command chaining to create a new user, set their password, and add them to a group, all in one command.
  • Built-in help: PowerShell has a built-in help system, similar to the Linux man pages. The help system also provides examples of how to use different cmdlets.
  • Tab completion: PowerShell offers tab completion and command prediction by default, which allows for a more intuitive scripting experience.
  • Configuration as code: The PowerShell DSC allows you to automate complex deployment and configuration scenarios and use push or pull models for deploying configurations.

The ultimate guide to using PowerShell

In the following sections, we will explore the key concepts of PowerShell and then discuss how to use PowerShell to perform common tasks.

Modules

A module is a self-contained PowerShell package that allows PowerShell code to be modularized and shared. It’s a collection of PowerShell elements, including cmdlets, functions, variables, aliases, and workflows that are grouped together for a specific purpose. Modules offer several benefits:

  • Modular code is clean and easy to maintain.
  • Modules can be reused across different sessions and environments.
  • Modules are a great way to extend PowerShell and then share those extensions with other people. For example, PowerShell modules exist for Azure, SQL Server, Active Directory, and other tools.
  • PowerShell supports nested modules, which allows you to import a module inside another.

A module has the four basic building blocks:

  • A source code file, which is typically a PowerShell script.
  • Additional information, such as a help file or any other script that the above file may need.
  • A manifest file to describe the contents and metadata of the module.
  • A directory to store all the above.

There are four different types of modules: manifest, script, binary, and dynamic.

  • A manifest module uses a “.psd1” file to define all of its elements but doesn’t include any script.
  • A script module uses a “.psm1” file to encapsulate any valid PowerShell code.
  • A binary module is a “.dll” file that contains compiled, executable code.
  • A dynamic module is an ephemeral module that’s dynamically created via the New-Module cmdlet.

Cmdlets

Commands in PowerShell are known as cmdlets. They are a foundational element of PowerShell, used to interact with the operating system and other resources. Each cmdlet is designed to perform a specific function.

Unlike traditional commands in other languages and tools, cmdlets follow a consistent naming convention of “verb-noun”, which describes their actions. For example, “Get-Service” retrieves information about running services, while “Get-Credential” retrieves credentials objects.

PowerShell offers a diverse range of cmdlets for different use cases. To get a list of all installed cmdlets on a system, use this command:

Get-Command -Type Cmdlet

You can also leverage the extensibility of PowerShell to define your own cmdlet. For example, you may create a cmdlet to interact with a specific cloud service.

Desired State Configuration (DSC)

As we saw earlier, DSC is a configuration-as-code platform used to manage modern IT infrastructures. DSC supports both Windows and Linux, and can also be used to automate tasks on Microsoft Azure. It has three main building blocks:

  • Configurations: A configuration is a PowerShell script that defines the desired state of a system. It includes a list of resources and the desired settings.
  • Resources: These represent individual configuration items. PowerShell includes several built-in resources, such as the archive resource, file resource, user resource, and registry resource. You can also create your own resource to implement custom functionalities.
  • Local Configuration Manager (LCM): An engine which parses and executes the configurations on a node. The LCM is also responsible for maintaining the desired state of configurations.

PowerShell Desired State Configuration is a great way to manage node clusters. Administrators can use it to install features on multiple machines at once, detect and fix configuration drift, and enforce security controls.

PowerShell Integrated Scripting Environment (ISE)

The PowerShell Integrated Scripting Environment (ISE) is a graphical user interface used to write, debug, and test PowerShell scripts. The ISE boasts an array of features for PowerShell users, including the following:

  • Syntax highlighting: The ISE can highlight the syntax of PowerShell code, making it easier to read and edit.
  • Multi-line editing: The ISE allows users to write multi-line code. Hitting “Shift” + “Enter” adds a new line under the current line.
  • Selective execution: You can also execute a part of a script by selecting the desired text and then clicking “Run Script”.
  • Console window: The ISE has a built-in console window to run and test PowerShell commands.
  • Multi-tab editing: With the ISE, you can open multiple tabs, each with its own editing environment and console window.

Syntax and semantics

PowerShell has a clear and logical syntax that combines elements of object-oriented programming with the ease of command-line scripting. To write efficient PowerShell scripts, it’s important to first understand its syntax and semantics.

In PowerShell, everything is an object, including variables, functions, and commands. When you run a command, PowerShell often returns objects instead of plain text. This approach enables you to access the properties and methods directly, simplifying data manipulation.

Functions

Functions are reusable blocks of code. The following code defines a function that takes in the name of a user and then prints a “Hello” greeting:

function Get-UserInfo {  
param(
[string]$Name
)
Write-Host "Hello, $Name!"
}

The function can be called as follows:

Get-UserInfo(“John”) 

Variables

PowerShell uses loosely typed variables. You can define a variable by giving a value to a name without the need to specify an explicit type. PowerShell dynamically determines the data type based on the stored data.

Variables start with the $ sign. For example, the following code initializes a variable called “name” and assigns it a value.

$name = "John"  

Switch

The switch statement is used to perform conditional branching based on the value of an expression. For example, you should use switch if you need to evaluate a single expression against different possible values and execute different logic depending on the matched value.

For example, the following code uses a switch statement to print the appropriate message to the console, depending on the value of the variable “fruit”. The “default” block is executed when nothing else matches.

$fruit = Get-FruitName() 
switch ($fruit) {
"strawberry" {
Write-Host "You have a strawberry."
}
"banana" {
Write-Host "You have a banana."
}
"cherry" {
Write-Host "You have a cherry."
}
default {
Write-Host "You have something else."
}
}

Loops

PowerShell offers multiple loop constructs, including “for”, “foreach”, “while”, and “do...while”. Use these loops to repeat commands or operations based on specified conditions. For example, the following code defines a “for” loop that runs until the variable “i” is less than or equal to 5, incrementing the value of “i” in each iteration.

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

This logic can also be executed via a “do…while” loop:

$counter = 1 
do {
Write-Host "Iteration $counter"
$counter++
} while ($counter -le 5)

Data structures

PowerShell also supports advanced data structures, including arrays and hash tables. These data structures make it easy to store different kinds of data and implement complicated scripting use cases.

All you need to do to create an array is assign multiple values to a variable while initializing it. For example, the following code will create an array named “myArray”:

$myArray = 22,5,10,8,12,9,80  

Single element arrays can be created by placing a comma after the first element:

$myArray = 22,   

You can also create strongly-typed arrays:

[int32[]]$myArray = 1500, 11, 23, 1213    

To access an array element, use this syntax:

$myArray[0]     

A hash table stores key-value pairs of data. Use the following syntax to create an empty hash table:

$myHash = @{}     

Or if you want to provide values at initialization:

$myHash = @{ Id = 1; Name = "John"; Age = 22}     

Creating and running your first script in PowerShell

Follow these steps to create and run your first PowerShell script:

  • Create a new file with a .ps1 extension. Let’s name it “first_script.ps1”.
  • Open the file in the PowerShell ISE, or any text editor.
  • Copy and paste the following line to the file:

Write-Host "Hello, world!"

  • Save the file and then open a PowerShell console.
  • Navigate to the directory that contains the script file, and run the following command:

.\first_script.ps1

That’s it! You should see the message “Hello, world!” printed on the console.

How to schedule the execution of a PowerShell script

You can use the Windows Task Scheduler to run a script on a schedule. Follow these steps to do so:

  • Open the Task Scheduler.
  • In the Task Scheduler, click on the "Create Task" button.
  • In the "Create Task" wizard, select the "Triggers" tab.
  • From the "Triggers" tab, select the type of trigger that you want to use. For example, you may select "On a schedule" to run the script daily, weekly, or monthly.
  • Move to the "Actions" tab, click “New”, and choose “Start a program” from the “Action” dropdown.
  • In the "Program/Script" field, enter the path to the PowerShell script that you want to run.
  • In the "Add Arguments" field, you can specify any arguments that you want to pass to the script.
  • Move back to the “General” tab, review your selections, and hit “OK”.

Using PowerShell for server management

You can use PowerShell for different aspects of server management, including the following:

Remote maintenance

PowerShell offers certain built-in cmdlets for running commands on remote machines. For example, the “Restart-Computer” cmdlet restarts a remote computer, and the “Get-Process” cmdlet can be used to get a list of all processes running on a remote computer.

You can also establish a remote connection with a server and issue commands directly using the “Enter-PSSession” cmdlet.

Starting and stopping remote services

The “Set-Service” cmdlet allows you to start, suspend, or stop a service running on a remote computer.

Test connections

Use the “Test-Connection” cmdlet to test the connection with one or a network of remote computers.

System monitoring

PowerShell can collect and analyze performance data, event logs, and system metrics. For example, the “Get-EventLog” cmdlet can be used to fetch event logs from a remote computer in real time.

Active Directory integration

PowerShell can integrate with Active Directory services. This allows administrators to use scripting for user and group management, as well as domain-related tasks.

Some handy PowerShell commands you should know

Here are a few useful PowerShell cmdlets that every administrator should know:

Creating a folder

You can use the “New-Item” cmdlet to create a new folder in PowerShell.


New-Item -ItemType Directory -Path "D:\Path\NewFolder"

Moving a folder

To move a folder, you can use the “Move-Item” cmdlet.


Move-Item -Path "C:\SourceFolder" -Destination "C:\DestinationFolder"

Renaming a folder

You can rename a folder using the “Rename-Item” cmdlet.


Rename-Item -Path "C:\OldName" -NewName "C:\NewName"

Copying files

Use the “Copy-Item” cmdlet to copy files.


Copy-Item -Path "C:\SourceFile.txt" -Destination "D:\DestinationFolder\"

Deleting files and folders

Use the “Remove-Item” cmdlet to delete files and folders.

# Delete a file 
Remove-Item -Path "C:\Path\File.txt"
# Delete a folder and its contents recursively
Remove-Item -Path "C:\Path\Folder" -Recurse

Checking if a file exists

The “Test-Path” cmdlet lets you check if a file exists.


$filePath = "C:\Path\myFile.txt"
if (Test-Path -Path $filePath -PathType Leaf) {
Write-Host "File exists."
} else {
Write-Host "File does not exist."
}

Creating remote sessions

To create an encrypted remote session, use the “New-PSSession” cmdlet.


New-PSSession -ComputerName {remoteServer} -Port 8081 -UseSSL
Plugin

Conclusion

PowerShell is a comprehensive solution for configuring, deploying, and administering resources in today's hybrid IT infrastructures. Whether you want to codify the provisioning and maintenance of an environment, modify the registry settings of a local or remote computer, or write complicated automation scripts, you can use PowerShell to do so.

Was this article helpful?

Related Articles

Write For Us

Write for Site24x7 is a special writing program that supports writers who create content for Site24x7 "Learn" portal. Get paid for your writing.

Write For Us

Write for Site24x7 is a special writing program that supports writers who create content for Site24x7 “Learn” portal. Get paid for your writing.

Apply Now
Write For Us