Skip to main content

powershell

Intro

PowerShell is a powerful tool for both IT professionals and developers because it offers:

  • Rich scripting and automation: It lets you automate repetitive tasks across many servers, saving time and ensuring consistency.
  • Interactive shell environment: You can run commands interactively to manage and configure systems efficiently.
  • Object-oriented + Developer-native approach: Everything you work with in PowerShell is treated as an object, making it intuitive and powerful, especially since it's based on the .NET framework.

Command syntax

  • cmdlet: A cmdlet is a combination of a verb and a noun/resource, like Get-Service or Get-Help.
  • command: A powershell command is a combination of a cmdlet and parameters to pass to the cmdlet.

IMPORTANT

Powershell is case-insensitive

When you run a powershell command, it returns an object describing the resource.

Piping

The pipe operator | works the exact same way it does in bash, piping output from one command as input to another command.

get-service | out-file c:\services.txt

Important cmdlets

Getting help

The Get-Help cmdlet is a universal cmdlet that takes in another cmdlet as an argument and returns help information about that cmdlet:

Get-Help <cmdlet>

You also have these additional options to organize how the help information comes back:

  • -examples: returns command examples
  • -detailed: returns detailed text information.
  • -full: returns all info.
  • -online: links you to the online documentation for the command.

Listing commands with Get-Command

Run the Get-Command cmdlet to list all possible commands in powershell.

Process management with Get-Service

The Get-Service cmdlet returns a list of all service objects, where a service represents a process on the machine.

Since it returns a list of thousands of services, it's important to pipe the output of the Get-Service cmdlet into some filtering command.

For example, the below command lists all services with their status property as "stopped".

Get-Service | Where-Object {$_.status -eq "stopped"}

Important flags

-whatif

The -whatif flag lets you perform a dry-run of a command without actually running it, just to see what the output would be.

Normally the command below, where you're piping a list of service objects into the Stop-Service cmdlet, would kill every single process on your computer and force you to restart.

Get-Service | Stop-Service

But with the -whatif flag it lets you perform a dry run and view the output of the command without actually running it:

Get-Service | Stop-Service -whatif

-confirm

The -confirm flag will ask you to confirm the command execution for each object the operation is being performed on.

Get-Service | Stop-Service -confirm

Object-oriented info withGet-Member

Since objects in powershell are based off of classes in .NET, you have a powerfull way of listing methods and properties on object isntances and then being able to use them.

For example, piping the output of a list of objects in powershell to the Get-Member cmdlet will list all the methods and properties on those objects:

Get-Service | Get-Member

Aliases

Powershell bridges the gap for bash developers by providing aliases for common bash commands and mapping them to the underlying powershell command.

For example, the alias for the bash ls command maps to the Get-ChildItem command in powershell, which is what actually lists a directory.

Functions

Functions let you extend PowerShell by writing your own reusable commands tailored to your needs.

We invoke functions the same way as we do cmdlets

NOTE

functions vs cmdlets


PowerShell functions and cmdlets are similar in how you use them—they're both called like commands. However, cmdlets are built-in commands designed for specific tasks, while functions can be created by you to perform custom or more complex operations.

  • Functions can bundle multiple commands or logic inside them, giving you flexibility to automate tasks like calculations or processing data.
  • cmdlets are predefined, built-in commands.

You can create functions in powershell with the function keyword, like so:

  1. Type the function <functionname> syntax in the powershell console.
  2. Then hit enter to start writing the function body, doing shift + enter to go into a new line.
function add
{
$add = [int](2+2)
write-output "$add"
}

Object formatting

Object formatting allows you to format and transform lists of objects you get back from a powershell cmdlet:

Get-Service | format-list DisplayName, Status
Get-Service | format-list *
Get-Service | Sort-Object -Property status | format-table DisplayName, Status

Here are the different cmdlets you can use to format the data you get back and perform transformations on, and then write the data to stdout, finishing the stream:

  • Format-List: displays list of objects in a list format. It accepts a comma-separated list of object properties to show in the list.
  • Format-Table: displays list of objects in a table format. It accepts a comma-separated list of object properties to show in the list.

Here are the transformation cmdlets that work as streams, meaning you can pass their output as stdin to another command.

  • Sort-Object: groups objects or sorts by them, accepts these flags:
    • -Property <propertyname>: the property to group by

NOTE

When referencing properties on a cmdlet, you can use * to refer to all properties.

Output

Get-Service | format-list DisplayName, Status | Out-File C:\Users\amallick.ENGINEERS\Documents\temp\services.txt
  • Out-File: this cmdlet accepts an output filepath to write the incoming data to.
  • Export-Csv: this cmdlet accepts an output csv filepath to write the incoming data, forcing the data to parse as a CSV

Modules

A module is a collection of cmdlets for a particular function or application.

A PowerShell module is essentially a package that contains a collection of related cmdlets (commands) designed for a specific function or technology.

  • For example, there are modules for VMware, Citrix, Azure, and Office 365, each providing commands tailored to manage those environments.
  • Modules help organize and extend PowerShell's capabilities, allowing you to easily access and run commands related to particular tasks

Modules basics

List modules

To list all available modules, run the Get-Module command:

Get-Module -ListAvailable

Import module manually

In PowerShell 3.0 and later, modules can even load automatically when you run a command from them, making it easier to work with a wide range of tools without manually importing each module.

However, the syntax is still there if you want to manually import/load a module using the Import-Module cmdlet

Import-Module -name applocker

Installating third-party modules

Use the Install-Module cmdlet to install third-party modules.

Here is the basic syntax:

Install-Module -Name $packagename

And here is how to install Azure as a third-party module:

Install-Module -Name AzureAD

Execution policies

PowerShell execution policies control which scripts are allowed to run on your system to help protect against running untrusted code. Here are the four main policies:

  • Restricted: No scripts are allowed to run. This is the most secure setting and blocks all scripts, including those you create locally.
  • AllSigned: Only scripts that are digitally signed by a trusted publisher can run, whether they are local or downloaded.
  • RemoteSigned (default): Locally created scripts run without restriction, but scripts downloaded from the internet must be digitally signed.
  • Unrestricted: All scripts can run regardless of signature. This is risky for production environments and should only be used temporarily for testing.

NOTE

The default policy is RemoteSigned, balancing security and usability.

If you encounter errors running scripts, it’s often due to these policies, and you can change them with the Set-ExecutionPolicy command.

WARNING

Just be cautious, especially with Unrestricted, to avoid security risks.

Getting the execution policy

To get the current execution policy of PowerShell, use the Get-ExecutionPolicy cmdlet

Get-ExecutionPolicy

Setting the execution policy

To set the current execution policy of PowerShell, use the Set-ExecutionPolicy cmdlet and then pass in as the argument one of the 4 available execution policies to choose from.

Set-ExecutionPolicy restricted

Powershell 7 features

PowerShell 7 is designed to coexist with PowerShell 5.1 on the same system without interfering with each other. This is possible because PowerShell 7 installs into a new directory (%programfiles%\PowerShell\7), separate from where PowerShell 5.1 is installed.

This setup lets you run either version independently depending on your needs. So, you can have both versions available and choose which one to use for different tasks or scripts, which is helpful when transitioning or working with different environments.

Pipeline parallelization

Pipeline parallelization in PowerShell 7 allows you to process multiple objects at the same time instead of one after another, which can speed up tasks that handle many items. This is done using the ForEach-Object cmdlet with the -Parallel parameter.

Here's a simple example:

1..5 | ForEach-Object -Parallel { Start-Sleep -Seconds $_ "Processed item $_" }

In this example, numbers 1 to 5 are processed in parallel. Each item causes a sleep for that number of seconds, but because they run simultaneously, the total time is roughly the longest sleep, not the sum of all sleeps.

This feature is useful when you have tasks that can run independently and you want to save time by running them concurrently.

Get-Error and ConsiseView

  • Get-Error: Print detailed information about the last error that occurred.
  • ConciseView: provides a streamlined way to view errors. When enabled (it's the default view), it shows a simple single error message if the error isn't from a script.
    • But if the error comes from a script and involves multiple issues, it displays a detailed multiline error message with a pointer to the exact line where the error happened, similar to a stack trace.

Powershell administration

Check powershell version

View the value of the $PSVersionTable variable to see what the current powershell version is.

Powershell access levels

You can run PowerShell either as an administrator or just a normal user.

If you're not an admin, you can't run the Enable-PSRemoting cmdlet to enable SSHing into other windows servers, but if you do have admin permissions, you're able to run sensitive cmdlets like that.

Powershell ISE

The ise command in pwoershell gives you an IDE to write powershell scripts with intellisense on steroids.

When writing a powershell script, you have two choices of execution:

  • execute entire script: press FN + F5 to run the entire script
  • execute selection: highlight some lines of code, and then press FN + F8 to run only the selected lines of code

Here are the intellisense tips to keep in mind:

  • use the correct case: Intellisense only works when you use the correct casing, like Get-Service.
  • use CTRL + SPACE: this shortcut works exactly like VSCode to give you intellisense options directly

SSHing into a remote windows server

You can also SSH into a remote Windows server and run PowerShell ISE on there.

The shortcut to do this is CTRL + SHIFT + R

Running commands remotely

You can use RPC with powershell super simply with the -ComputerName flag:

Get-Service -ComputerName mycomputer | Out-Gridview

Grid View

You can view all of the properties and methods on an object easier through the gridview in ISE, which pulls up a GUI showcasing all of the different properties and methods of the object in detail.

To achieve this, pipe object output into the Out-Gridview cmdlet

Get-Service | Out-Gridview

NOTE

What makes this so useful? You have a GUI to easily view and filter properties.

If you want to filter object properties beforehand before piping the data stream to the gridview, use the Select-Object cmdlet to select specific properties first, then piping the output of that command to the gridview.

Get-Service | Select-Object DisplayName, Status, ServiceType | Out-GridView

Office 365 Powershell

Installation and setup

  1. Install this via powershell administrator access:
Install-Module -Name AzureAD
  1. See if it worked by listing all commands that are exposed on the installed module.
Get-Command -module AzureAD

Azure Powershell

Azure integrates with powershell very well and has three types of ways to use azure in the command-line:

  • Azure powershell: client-based shell that you install on your local machine, comes with Azure module installed to allow you to run azure commands.
  • Azure cloud shell: Shell in the azure cloud that you can use. It comes with all commands and authentication already there.
  • Azure CLI: a cross-platform CLI you install.