Reader small image

You're reading from  PowerShell Automation and Scripting for Cybersecurity

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781800566378
Edition1st Edition
Right arrow
Author (1)
Miriam C. Wiesner
Miriam C. Wiesner
author image
Miriam C. Wiesner

Miriam C. Wiesner is a senior security researcher at Microsoft, with over 15 years of experience in IT and IT security. She has held various positions, including administrator/system engineer, software developer, premier field engineer, program manager, security consultant, and pentester. She is also a renowned creator of open source tools based in PowerShell, including EventList and JEAnalyzer. She has been invited multiple times to present the research behind her tools at many international conferences, such as Black Hat (the US, Europe, and Asia), PSConfEU, and MITRE ATT&CK workshop. Outside of work, Miriam is a dedicated wife and mother, residing with her family near Nuremberg, Germany.
Read more about Miriam C. Wiesner

Right arrow

PowerShell Scripting Fundamentals

Now that you have learned how to get started with PowerShell, let’s have a closer look at PowerShell scripting fundamentals to refresh our knowledge.

We will start with the basics, such as working with variables, operators, and control structures. Then, we will dive deeper, putting the big picture together when it comes to cmdlets, functions, and even modules.

After working through this chapter, you should be able to create your very own scripts and even know how to create your own modules.

In this chapter, we are going to cover the following topics:

  • Variables
  • Operators
  • Control structures
  • Naming conventions
  • Cmdlets
  • Functions
  • Aliases
  • Modules

Technical requirements

For this chapter, you will need the following:

Variables

A variable is a storage location that developers can use to store information with a so-called value. Variables always have names that allow you to call them independently of the values that are stored within. In PowerShell, the $ sign at the beginning indicates a variable:

> $i = 1
> $string = "Hello World!"
> $this_is_a_variable = "test"

Variables are great for storing simple values, strings, and also the output of commands:

> Get-Date
Monday, November 2, 2020 6:43:59 PM
> $date = Get-Date
> Write-Host "Today is" $date
Today is 11/2/2020 6:44:40 PM

As you can see in these examples, not only can we store strings and numbers within a variable, we can also store the output of a cmdlet such as Get-Date and reuse it within our code.

Data types

In contrast to other scripting or programming languages, you don’t necessarily need to define the data type for variables. When defining a variable...

Operators

Operators help you not only to perform mathematical or logical operations but they are also a good way to compare values or redirect values.

Arithmetic operators

Arithmetic operators can be used to calculate values. They are as follows:

  • Addition (+):
    > $a = 3; $b = 5; $result = $a + $b
    > $result
    8
  • Subtraction (-):
    > $a = 3; $b = 5; $result = $b - $a
    > $result
    2
  • Multiplication (*):
    > $a = 3; $b = 5; $result = $a * $b
    > $result
    15
  • Division (/):
    > $a = 12; $b = 4; $result = $a / $b
    > $result
    3
  • Modulus (%): In case you have never worked with modulus in the past, % is a great way to check whether there is a remainder if a number is divided by a divisor. Modulus provides you with the remainder:
    > 7%2
    1
    > 8%2
    0
    > 7%4
    3

Of course, you can also combine different arithmetic operators as you are used to:

> $a = 3; $b = 5; $c = 2
> $result = ($a + $b) * $c
> $result
16

When combining different arithmetic operators...

Control structures

A control structure is some kind of programmatic logic that assesses conditions and variables and decides which defined action will be taken if a certain condition is met.

Use the operators that we learned about in the last section to define the conditions, which will be assessed using the control structures introduced in this section.

Conditions

If you want to select which action is performed if a certain condition is met, you can use one of the following selection control structures: either an if/elseif/else construct or the switch statement.

If/elseif/else

if, elseif, and else can be used to check whether a certain condition is True and run an action if the condition is fulfilled:

if (<condition>)
{
    <action>
}
elseif (<condition 2>)
{
    <action 2>
}
...
else
{
    <action 3>
}

You can use the if statement to check...

Naming conventions

Cmdlets and functions both follow the schema verb-noun, such as Get-Help or Stop-Process. So, if you write your own functions or cmdlets, make sure to follow the name guidelines and recommendations.

Microsoft has released a list of approved verbs. Although it is not technically enforced to use approved verbs, it is strongly recommended to do so in order to comply with PowerShell best practices and avoid conflicts with automatic variables and reserved words. Additionally, using approved verbs is required when publishing PowerShell modules to the PowerShell Gallery, as it will trigger a warning message if non-approved verbs are used. Here is the link for the approved verbs:

https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands

Finding the approved verbs

If you are in the process of writing your code and quickly want to check which approved verbs exist, you can leverage the Get-Verb command...

PowerShell profiles

PowerShell profiles are configuration files that allow you to personalize your PowerShell environment. These profiles can be used to customize the behavior and environment of PowerShell sessions. They are scripts that are executed when a PowerShell session is started, allowing users to set variables, define functions, create aliases, and more.

Any variables, functions, or aliases defined in the appropriate PowerShell profile will be loaded every time a PowerShell session is started. This means you can have a consistent and personalized PowerShell environment across all your sessions.

There are several different types of profiles and more than one can be processed by PowerShell. PowerShell profiles are stored as plain text files on your system, and there are several types of profiles available:

  • All Users, All Hosts ($profile.AllUsersAllHosts): This profile applies to all users for all PowerShell hosts.
  • All Users, Current Host ($profile.AllUsersCurrentHost...

Understanding PSDrives in PowerShell

PowerShell includes a feature called PowerShell drives (PSDrives). PSDrives in PowerShell are similar to filesystem drives in Windows, but instead of accessing files and folders, you use PSDrives to access a variety of data stores. These data stores can include directories, registry keys, and other data sources, which can be accessed through a consistent and familiar interface.

PSDrives are powered by PSProviders, which are the underlying components that provide access to data stores. PSProviders are similar to drivers in Windows, which allow access to different hardware devices. In the case of PowerShell, PSProviders allow you to access different data stores in a uniform way, using the same set of cmdlets and syntax.

For example, the Env:\ PSDrive is a built-in PowerShell drive that provides access to environment variables. To retrieve all environment variables that have the path string in their name, you can use the Get-ChildItem cmdlet...

Making your code reusable

In this section, we will explore the concept of making your code reusable in PowerShell. Reusability is an important aspect of coding that allows you to create a function, cmdlet, or module once and use it multiple times without having to rewrite the same code again and again. Through this, you can save time and effort in the long run.

We will start by discussing cmdlets, followed by functions and aliases, and finally, we will explore PowerShell modules, which are collections of PowerShell commands and functions that can be easily shared and installed on other systems, which is a great way to package and distribute your reusable code.

Cmdlets

A cmdlet (pronounced as commandlet) is a type of PowerShell command that performs a specific task and can be written in C# or in another .NET language. This includes advanced functions, which are also considered cmdlets but have more advanced features than regular functions.

Get-Command can help you to differentiate...

Summary

In this chapter, you have learned the fundamentals of PowerShell scripting. After refreshing the basics of variables, operators, and control structures, you are able to create your very own scripts, functions, and modules.

Now that you are familiar with the PowerShell basics and you are able to work with PowerShell on your local system, let’s dive deeper into PowerShell remoting and its security considerations in the next chapter.

Further reading

If you want to explore some of the topics that were mentioned in this chapter, check out these resources:

  • Everything you want to know about arrays: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays
  • Everything you want to know about hashtables: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable
  • Everything you want to know about $null: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null
  • Everything you want to know about PSCustomObject: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject
  • About functions: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions
  • Functions 101: https://docs.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions
  • About functions’ advanced parameters: https://docs.microsoft...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
PowerShell Automation and Scripting for Cybersecurity
Published in: Aug 2023Publisher: PacktISBN-13: 9781800566378
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Miriam C. Wiesner

Miriam C. Wiesner is a senior security researcher at Microsoft, with over 15 years of experience in IT and IT security. She has held various positions, including administrator/system engineer, software developer, premier field engineer, program manager, security consultant, and pentester. She is also a renowned creator of open source tools based in PowerShell, including EventList and JEAnalyzer. She has been invited multiple times to present the research behind her tools at many international conferences, such as Black Hat (the US, Europe, and Asia), PSConfEU, and MITRE ATT&CK workshop. Outside of work, Miriam is a dedicated wife and mother, residing with her family near Nuremberg, Germany.
Read more about Miriam C. Wiesner