Introduction

Ahoy there! If you’re here, you’ve either heard whispers of the marvels of PowerShell and want to discover more, or you’ve sailed over from the first room of the Command Line module Windows Command Line. Either way, you’re about to embark on a journey to discover the marvels of this powerful shell, learning how to use it to uncover the secrets of any Windows system. Avast, then—on board!


Learning Objectives

This is the second room in the Command Line module. It is an introductory room to PowerShell, the second—only historically—command-line utility built for the Windows operating system.

  • Learn what PowerShell is and its capabilities.
  • Understand the basic structure of PowerShell’s language.
  • Learn and run some basic PowerShell commands.
  • Understand PowerShell’s many applications in the cyber security industry.

Room Prerequisites


What is PowerShell

PowerShell is a cross-platform task automation and configuration management solution from Microsoft. It’s more than just a command-line shell; it’s a powerful combination of:

  • Command-line shell: An interactive interface for executing commands.
  • Scripting language: Allows for the creation of automated scripts for complex tasks.
  • Configuration management framework: Facilitates the management and configuration of systems across different platforms.

PowerShell’s core strength lies in its object-oriented nature. Unlike older command-line tools that handle data as text strings, PowerShell operates on objects. This allows for more efficient data manipulation and system interaction. Initially Windows-only, PowerShell Core (released in 2016) extended its reach to macOS and Linux.

A Brief History

PowerShell’s development was driven by the limitations of existing Windows command-line tools (like cmd.exe and batch files) in managing complex enterprise environments. Jeffrey Snover, a Microsoft engineer, spearheaded its creation, recognizing the need for a tool that could effectively interact with Windows’ structured data and APIs.

Snover’s solution was an object-oriented approach, blending the simplicity of scripting with the power of the .NET framework. This addressed the incompatibility between Windows’ structured data handling and the text-based approach of traditional Unix tools. Released in 2006, PowerShell revolutionized Windows system administration through its object manipulation capabilities. The subsequent release of PowerShell Core further cemented its position as a versatile cross-platform automation solution.

The Power of Objects

In programming, an object encapsulates data (properties) and actions (methods). A PowerShell object might represent a file, with properties like Name, Length, LastWriteTime, and methods like Copy-Item or Move-Item.

PowerShell cmdlets (pronounced “command-lets”) return objects, not just text. This significantly enhances data manipulation capabilities, eliminating the need for text parsing. This object-based approach is a key differentiator between PowerShell and older command-line tools.

Questions

  1. What do we call the advanced approach used to develop PowerShell?
    • object-oriented

PowerShell Basics

Accessing PowerShell

PowerShell can be launched in several ways:

  • Start Menu: Search for “powershell” and select “Windows PowerShell” or “PowerShell”.
  • Run Dialog (Win + R): Type powershell and press Enter.
  • File Explorer: Type powershell in the address bar of any folder to open PowerShell in that directory.
  • Task Manager: File > Run new task > powershell.
  • From cmd.exe: Type powershell and press Enter.

The PowerShell prompt (PS C:\Users\... >) indicates the current working directory.

Cmdlet Syntax: Verb-Noun

PowerShell commands are called cmdlets. They follow a consistent Verb-Noun naming convention (e.g., Get-Process, Set-Location). The verb describes the action, and the noun specifies the target object.

Essential Cmdlets

  • Get-Command: Lists available cmdlets, functions, aliases, and scripts. Use -CommandType to filter (e.g., Get-Command -CommandType Function).

  • Get-Help: Provides detailed information about a cmdlet. Use options like -Examples, -Detailed, -Full, or -Online for different levels of information (e.g., Get-Help Get-Process -Examples).

  • Get-Alias: Lists available aliases (shortcuts for cmdlets). Many common commands (e.g., dir, cd) have PowerShell aliases.

Managing Modules

PowerShell’s functionality can be extended by installing modules – collections of cmdlets.

  • Find-Module: Searches for modules in online repositories (like the PowerShell Gallery). Use wildcards to search partially (e.g., Find-Module -Name "Azure*").

  • Install-Module: Downloads and installs a module. (e.g., Install-Module -Name "AzureAzAccount"). Be aware of security implications when installing modules from untrusted sources.

Example Workflow

  1. Launch PowerShell.
  2. List available cmdlets: Get-Command
  3. Get help on a specific cmdlet: Get-Help Get-Process
  4. Search for available modules: Find-Module -Name "ActiveDirectory*"
  5. Install a module: Install-Module -Name "ActiveDirectory" (requires internet connection)

Questions

  1. How would you retrieve a list of commands that start with the verb Remove? (for the sake of this question, avoid the use of quotes (” or ’) in your answer)
    • Get-Command -Name Remove*
  2. What cmdlet has its traditional counterpart echo as an alias?
    • Write-Output
  3. What is the command to retrieve some example usage for the cmdlet New-LocalUser?
    • Get-Help New-LocalUser -examples

Navigating the File System and Working with Files

  • Get-ChildItem [-Path <string>]: Lists the contents (files and subdirectories) of a specified path. If no path is provided, it lists the current directory. This is analogous to dir in the Windows command prompt or ls in Unix-like systems.

  • Set-Location [-Path <string>]: Changes the current working directory. Equivalent to cd in the Windows command prompt.

File and Directory Management

PowerShell streamlines file and directory management with a unified set of cmdlets. Unlike the traditional command prompt, which uses separate commands for files and directories (e.g., del, rmdir), PowerShell uses a single cmdlet for various operations:

  • New-Item [-Path <string>] [-ItemType <string>]: Creates new items (files or directories).

    • -ItemType Directory: Creates a new directory.
    • -ItemType File: Creates a new empty file.
  • Remove-Item [-Path <string>] [-Force]: Deletes files and directories. The -Force parameter is crucial for deleting directories that are not empty. This is equivalent to a combination of del and rmdir in the Windows command prompt.

  • Copy-Item [-Path <string>] [-Destination <string>]: Copies files or directories. Similar to the copy command in the Windows command prompt.

  • Move-Item [-Path <string>] [-Destination <string>]: Moves or renames files or directories. Analogous to the move command in the Windows command prompt.

  • Get-Content [-Path <string>]: Reads and displays the contents of a file. Similar to the type command in the Windows command prompt or cat in Unix-like systems.

Example: Creating and Managing Files

# Change to the Documents directory
Set-Location -Path "C:\Users\YourUserName\Documents"
 
# Create a new directory
New-Item -Path .\MyProject -ItemType Directory
 
# Create a new text file
New-Item -Path .\MyProject\data.txt -ItemType File
 
# Add some content to the file
"This is some sample data" | Out-File -FilePath .\MyProject\data.txt
 
# Display the file contents
Get-Content -Path .\MyProject\data.txt
 
# Copy the file
Copy-Item -Path .\MyProject\data.txt -Destination .\MyProject\data_copy.txt
 
# Move the directory
Move-Item -Path .\MyProject -Destination .\MyProject_Renamed
 
# Remove the directory (requires -Force if not empty)
Remove-Item -Path .\MyProject_Renamed -Force
 

This example demonstrates the basic usage of PowerShell cmdlets for managing the file system. Remember to always exercise caution when using Remove-Item, especially with the -Force parameter. Proper backups are essential before performing potentially destructive operations.

Questions

  1. What cmdlet can you use instead of the traditional Windows command type?
    • Get-Content
  2. What PowerShell command would you use to display the content of the “C:\Users” directory? (for the sake of this question, avoid the use of quotes (” or ’) in your answer)
    • Get-ChildItem -Path C:\Users
  3. How many items are displayed by the command described in the previous question?
    • 4

Piping, Filtering and Sorting Data

This note explains how to use PowerShell’s piping capabilities along with filtering and sorting cmdlets for efficient data manipulation.

Piping (|)

Piping (|) sends the output (objects) of one cmdlet to the input of another, creating a chain of commands. This is far more powerful in PowerShell than in traditional command-line interfaces because it passes objects, not just text. Objects retain their properties and methods, enabling more complex operations.

graph LR
    A[Get-ChildItem] --> B[Process Items] --> C[Sort-Object]
    C --> D[Output]

Sorting Data (Sort-Object)

The Sort-Object cmdlet sorts objects based on specified properties.

Get-ChildItem | Sort-Object Length # Sorts files by size
Get-Process | Sort-Object -Property CPU -Descending # Sorts processes by CPU usage (descending)

Filtering Data (Where-Object)

Where-Object filters objects based on specified conditions. It uses comparison operators:

  • -eq: Equal to
  • -ne: Not equal to
  • -gt: Greater than
  • -ge: Greater than or equal to
  • -lt: Less than
  • -le: Less than or equal to
  • -like: Matches a wildcard pattern (e.g., -like "A*" matches strings starting with “A”)
PS C:\Users\captain\Documents\captain-cabin> Get-ChildItem | Where-Object -Property "Extension" -eq ".txt"
 
    Directory: C:\Users\captain\Documents\captain-cabin
 
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          9/4/2024  12:50 PM              0 captain-boots.txt
-a----          9/4/2024  12:14 PM            264 captain-hat.txt
-a----          9/4/2024  12:14 PM            264 captain-hat2.txt
-a----          9/4/2024  12:37 PM           2116 ship-flag.txt
graph LR
    A[Get-ChildItem] --> B[Filter: Only .txt files] --> C[Where-Object]
    C --> D[Output]

Selecting Properties (Select-Object)

Select-Object selects specific properties from objects or limits the number of objects returned.

Get-ChildItem | Select-Object Name, Length # Shows only Name and Length properties
Get-Process | Select-Object -First 5 # Shows the first 5 processes

Searching Text (Select-String)

Select-String searches for text patterns within files. It supports regular expressions.

Select-String -Path .\myfile.log -Pattern "error" # Searches for "error" in myfile.log

Combining Cmdlets

PowerShell’s strength is in combining these cmdlets. For example, finding the largest file:

Get-ChildItem | Sort-Object -Property Length -Descending | Select-Object -First 1

This demonstrates how piping, combined with sorting and filtering cmdlets, empowers efficient data manipulation in PowerShell. The object-based nature of PowerShell allows for more flexible and powerful data processing than traditional command-line tools.

Questions

  1. How would you retrieve the items in the current directory with size greater than 100? for the sake of this question, avoid the use of quotes (” or ’) in your answer
    • Get-ChildItem | Where-Object -Property Length -gt 100

System and Network Information

PowerShell was created to address a growing need for a powerful automation and management tool to help system administrators and IT professionals. As such, it offers a range of cmdlets that allow the retrieval of detailed information about system configuration and network settings.

The Get-ComputerInfo cmdlet retrieves comprehensive system information, including operating system information, hardware specifications, BIOS details, and more. It provides a snapshot of the entire system configuration in a single command. Its traditional counterpart systeminfo retrieves only a small set of the same details.

PS C:\Users\captain> Get-ComputerInfo
 
WindowsBuildLabEx                                       : 20348.859.amd64fre.fe_release_svc_prod2.220707-1832
WindowsCurrentVersion                                   : 6.3
WindowsEditionId                                        : ServerDatacenter
WindowsInstallationType                                 : Server Core
WindowsInstallDateFromRegistry                          : 4/23/2024 6:36:29 PM
WindowsProductId                                        : 00454-60000-00001-AA763
WindowsProductName                                      : Windows Server 2022 Datacenter
[...]

Essential for managing user accounts and understanding the machine’s security configuration, Get-LocalUser lists all the local user accounts on the system. The default output displays, for each user, username, account status, and description.

PS C:\Users\captain> Get-LocalUser
 
Name               Enabled Description
----               ------- -----------
Administrator      True    Built-in account for administering the computer/domain
captain            True    The beloved captain of this pirate ship.
DefaultAccount     False   A user account managed by the system.
Guest              False   Built-in account for guest access to the computer/domain
WDAGUtilityAccount False   A user account managed and used by the system for Windows Defender Application Guard scenarios.

Similar to the traditional ipconfig command, the following two cmdlets can be used to retrieve detailed information about the system’s network configuration.

Get-NetIPConfiguration provides detailed information about the network interfaces on the system, including IP addresses, DNS servers, and gateway configurations.

PS C:\Users\captain> Get-NetIPConfiguration
 
InterfaceAlias       : Ethernet
InterfaceIndex       : 5
InterfaceDescription : Amazon Elastic Network Adapter
NetProfile.Name      : Network 3
IPv4Address          : 10.10.178.209
IPv6DefaultGateway   :
IPv4DefaultGateway   : 10.10.0.1
DNSServer            : 10.0.0.2

In case we need specific details about the IP addresses assigned to the network interfaces, the Get-NetIPAddress cmdlet will show details for all IP addresses configured on the system, including those that are not currently active.

PS C:\Users\captain> Get-NetIPAddress
 
IPAddress         : fe80::3fef:360c:304:64e%5
InterfaceIndex    : 5
InterfaceAlias    : Ethernet
AddressFamily     : IPv6
Type              : Unicast
PrefixLength      : 64
PrefixOrigin      : WellKnown
SuffixOrigin      : Link
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore
 
IPAddress         : ::1
InterfaceIndex    : 1
InterfaceAlias    : Loopback Pseudo-Interface 1
AddressFamily     : IPv6
[...]
 
IPAddress         : 10.10.178.209
InterfaceIndex    : 5
InterfaceAlias    : Ethernet
AddressFamily     : IPv4
[...]
 
IPAddress         : 127.0.0.1
InterfaceIndex    : 1
InterfaceAlias    : Loopback Pseudo-Interface 1
AddressFamily     : IPv4
[...]

These cmdlets give IT professionals the ability to quickly access crucial system and network information directly from the command line, making it easier to monitor and manage both local and remote machines.

Questions

  1. Other than your current user and the default “Administrator” account, what other user is enabled on the target machine?
    • p1r4t3
  2. This lad has hidden his account among the others with no regard for our beloved captain! What is the motto he has so bluntly put as his account’s description?
    • A merry life and a short one.
  3. Now a small challenge to put it all together. This shady lad that we just found hidden among the local users has his own home folder in the “C:\Users” directory. Can you navigate the filesystem and find the hidden treasure inside this pirate’s home?
    • THM{p34rlInAsh3ll}

Real-Time System Analysis

To gather more advanced system information, especially concerning dynamic aspects like running processes, services, and active network connections, we can leverage a set of cmdlets that go beyond static machine details.

Get-Process

Get-Process provides a detailed view of all currently running processes, including CPU and memory usage, making it a powerful tool for monitoring and troubleshooting.

PS C:\Users\captain> Get-Process
 
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
     67       5      872        500       0.06   2340   0 AggregatorHost
     55       5      712       2672       0.02   3024   0 AM_Delta_Patch_1.417.483.0
    309      13    18312       1256       0.52   1524   0 amazon-ssm-agent
     78       6     4440        944       0.02    516   0 cmd
     94       7     1224       1744       0.31    568   0 conhost
[...]

Get-Service

Similarly, Get-Service allows the retrieval of information about the status of services on the machine, such as which services are running, stopped, or paused. It is used extensively in troubleshooting by system administrators, but also by forensics analysts hunting for anomalous services installed on the system.

PS C:\Users\captain> Get-Service
 
Status   Name               DisplayName
------   ----               -----------
Stopped  Amazon EC2Launch   Amazon EC2Launch
Running  AmazonSSMAgent     Amazon SSM Agent
Stopped  AppIDSvc           Application Identity
Running  BFE                Base Filtering Engine
Running  CertPropSvc        Certificate Propagation
Stopped  ClipSVC            Client License Service (ClipSVC)
[...]

Get-NetTCPConnection

To monitor active network connections, Get-NetTCPConnection displays current TCP connections, giving insights into both local and remote endpoints. This cmdlet is particularly handy during an incident response or malware analysis task, as it can uncover hidden backdoors or established connections towards an attacker-controlled server.

PS C:\Users\captain> Get-NetTCPConnection
 
LocalAddress        LocalPort RemoteAddress       RemotePort State       AppliedSetting OwningProcess
------------        --------- -------------       ---------- -----       -------------- -------------
[...]
::                  22        ::                  0          Listen                     1444
10.10.178.209       49695     199.232.26.172      80         TimeWait                   0
0.0.0.0             49668     0.0.0.0             0          Listen                     424
0.0.0.0             49667     0.0.0.0             0          Listen                     652
0.0.0.0             49666     0.0.0.0             0          Listen                     388
0.0.0.0             49665     0.0.0.0             0          Listen                     560
0.0.0.0             49664     0.0.0.0             0          Listen                     672
0.0.0.0             3389      0.0.0.0             0          Listen                     980
10.10.178.209       139       0.0.0.0             0          Listen                     4
0.0.0.0             135       0.0.0.0             0          Listen                     908
10.10.178.209       22        10.14.87.60         53523      Established Internet       1444
0.0.0.0             22        0.0.0.0             0          Listen                     1444

Get-FileHash

Additionally, we are going to mention Get-FileHash as a useful cmdlet for generating file hashes, which is particularly valuable in incident response, threat hunting, and malware analysis, as it helps verify file integrity and detect potential tampering.

PS C:\Users\captain\Documents\captain-cabin> Get-FileHash -Path .\ship-flag.txt
 
Algorithm       Hash                      Path
---------       ----                      ----
SHA256          54D2EC3C12BF3D[...]       C:\Users\captain\Documents\captain-cabin\ship-flag.txt

These cmdlets collectively provide a comprehensive set of tools for real-time system monitoring and analysis, proving especially useful to incident responders and threat hunters.

Questions

  1. In the previous task, you found a marvellous treasure carefully hidden in the target machine. What is the hash of the file that contains it?
    • 71FC5EC11C2497A32F8F08E61399687D90ABE6E204D2964DF589543A613F3E08
  2. What property retrieved by default by Get-NetTCPConnection contains information about the process that has started the connection?
    • OwningProcess
  3. It’s time for another small challenge. Some vital service has been installed on this pirate ship to guarantee that the captain can always navigate safely. But something isn’t working as expected, and the captain wonders why. Investigating, they find out the truth, at last: the service has been tampered with! The shady lad from before has modified the service DisplayName to reflect his very own motto, the same that he put in his user description.With this information and the PowerShell knowledge you have built so far, can you find the service name?
    • p1r4t3-s-compass

Scripting

Scripting is the process of writing and executing a series of commands contained in a text file, known as a script, to automate tasks that one would generally perform manually in a shell, like PowerShell.

Simply speaking, scripting is like giving a computer a to-do list, where each line in the script is a task that the computer will carry out automatically. This saves time, reduces the chance of errors, and allows to perform tasks that are too complex or tedious to do manually. As you learn more about shells and scripting, you’ll discover that scripts can be powerful tools for managing systems, processing data, and much more.

Learning scripting with PowerShell goes beyond the scope of this room. Nonetheless, we must understand that its power makes it a crucial skill across all cyber security roles.

  • For blue team professionals such as incident responders, malware analysts, and threat hunters, PowerShell scripts can automate many different tasks, including log analysis, detecting anomalies, and extracting indicators of compromise (IOCs). These scripts can also be used to reverse-engineer malicious code (malware) or automate the scanning of systems for signs of intrusion.
  • For the red team, including penetration testers and ethical hackers, PowerShell scripts can automate tasks like system enumeration, executing remote commands, and crafting obfuscated scripts to bypass defences. Its deep integration with all types of systems makes it a powerful tool for simulating attacks and testing systems’ resilience against real-world threats.
  • Staying in the context of cyber security, system administrators benefit from PowerShell scripting for automating integrity checks, managing system configurations, and securing networks, especially in remote or large-scale environments. PowerShell scripts can be designed to enforce security policies, monitor systems health, and respond automatically to security incidents, thus enhancing the overall security posture.

Whether used defensively or offensively, PowerShell scripting is an essential capability in the cyber security toolkit.

Before concluding this task about scripting, we can’t go without mentioning the Invoke-Command cmdlet.

Invoke-Command is essential for executing commands on remote systems, making it fundamental for system administrators, security engineers and penetration testers. Invoke-Command enables efficient remote management and—combining it with scripting—automation of tasks across multiple machines. It can also be used to execute payloads or commands on target systems during an engagement by penetration testers—or attackers alike.

Let us discover some example usage for this powerful cmdlet by consulting the Get-Help “examples” page:

PS C:\Users\captain> Get-Help Invoke-Command -examples
 
NAME
    Invoke-Command
 
SYNOPSIS
    Runs commands on local and remote computers.
 
    ------------- Example 1: Run a script on a server -------------
 
    Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01
 
    The FilePath parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.
 
    --------- Example 2: Run a command on a remote server ---------
 
    Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -ScriptBlock { Get-Culture }
 
    The ComputerName parameter specifies the name of the remote computer. The Credential parameter is used to run the command in the security context of Domain01\User01, a user who has permission to run commands. The ScriptBlock parameter specifies the command to be run on the remote computer.
 
    In response, PowerShell requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.
[...]

The first two examples provided by the Get-Help “examples” page and reported above are enough to grasp the simplicity and power of the Invoke-Command cmdlet.

The first example shows how the cmdlet can be very easily combined with any custom script to automate tasks on remote computers.

The second example demonstrates that we don’t need to know how to script to benefit from the power of Invoke-Command. In fact, by appending the -ScriptBlock { ... } parameter to the cmdlet’s syntax, we can execute any command (or sequence of commands) on the remote computer. The result would be the same as if we were typing the commands in a local PowerShell session on the remote computer itself.

Questions

  1. What is the syntax to execute the command Get-Service on a remote computer named “RoyalFortune”? Assume you don’t need to provide credentials to establish the connection. for the sake of this question, avoid the use of quotes (” or ’) in your answer
    • Invoke-Command -ComputerName RoyalFortune -ScriptBlock { Get-Service }