What Is PowerShell?
PowerShell is a powerful scripting language and command-line interface (CLI) developed by Microsoft. It’s built on the .NET Framework and is primarily used to automate administrative tasks, manage system configurations, and streamline IT operations. Think of it as the Windows equivalent of Bash in Linux—but with a twist: PowerShell is object-oriented, making it more versatile for developers and system admins alike.
Why PowerShell Stands Out:
- Object-Oriented Language (OOP): Unlike traditional shells, PowerShell works with objects, not plain text.
- Cross-Platform: Although native to Windows, it can also run on Linux (via package managers) and macOS (via Homebrew or manual installation).
- Extensive Scripting Capabilities: Scripts in PowerShell use the
.ps1file extension and are composed of small command units called cmdlets (pronounced “command-lets”).
PowerShell ISE (Integrated Scripting Environment):
PowerShell ISE is a built-in terminal console in Windows designed for:
- Writing and editing scripts
- Running and testing cmdlets
- Debugging with features like breakpoints and syntax highlighting
A Note on Case Sensitivity:
In Windows, PowerShell is case-insensitive by default. However, this doesn’t always hold true on other platforms like Linux or macOS—so be careful when scripting cross-platform!
Why Syntax Matters:
PowerShell has a vast library of commands, so understanding its syntax is key. Knowing how to structure commands, use parameters, and manipulate objects will unlock its full power.
Common PowerShell Commands & Their Aliases
| PowerShell Command | Alias(es) | Description |
|---|---|---|
Get-Help | (None) | Displays help info for any command. Try Get-Help Get-Process to learn more about it. |
Get-Command | (None) | Lists all available PowerShell commands. Great for discovering what’s available. |
Get-ChildItem | dir, ls, gci | Lists files and folders in the current directory. |
Get-Location | pwd, gl | Shows your current working directory. |
Set-Location | cd, chdir, sl | Changes your working directory. |
Get-Content | cat, gc, type | Displays the content of a file. |
Copy-Item | copy, cp, cpi | Copies files or directories. |
Remove-Item | del, rm, ri | Deletes files or directories. |
Move-Item | move, mv, mi | Moves files or directories to a new location. |
New-Item | ni | Creates a new file or folder. |
Out-File | >, >> | Redirects output to a file. Use Out-File when you need to specify extra options. |
Invoke-WebRequest | curl, iwr, wget | Fetches content from a web page—super useful for scripts and automation. |
Write-Output | echo, write | Sends output to the screen or next command in a pipeline. |
Clear-Host | cls, clear | Clears the terminal screen for a clean view. |
Example: Using a Few Command Together
Set-Location C:\Logs
Get-ChildItem *.log | Get-Content | Out-File CombinedLogs.tx
This script navigates to the Logs directory, grabs all .log files, reads their contents, and saves them to a single file.
Understanding PowerShell Parameters & Pipes
What Are PowerShell Parameters?
Parameters are command-line arguments you can pass to PowerShell commands to customize how they run. They make your scripts dynamic, flexible, and reusable.
Example syntax:
powershellCopyEditDo-Something -Parameter1 value1 -Parameter2
In this example:
Parameter1takes a specific value.Parameter2is a switch — it doesn’t require a value.
Want to find all commands that accept a specific parameter? Use this helpful trick:
powershellCopyEditGet-Help * -Parameter ComputerName
Risk Mitigation Parameters
PowerShell includes built-in parameters that help you avoid accidental changes or deletions.
| Parameter | Description | Example |
|---|---|---|
-Confirm | Prompts you before executing the action | New-Item test.txt -Confirm |
-WhatIf | Simulates the action and shows what would happen without making changes | Remove-Item test.txt -WhatIf |
These are especially useful when testing or running scripts that modify system files or settings.
Using the PowerShell Pipeline (|)
The pipeline character (|) allows you to chain commands together. It sends the output of one command into the next command in the sequence—similar to Bash or Splunk scripting.
Basic syntax:
powershellCopyEditCommand1 | Command2 | Command3
Real-world example:
powershellCopyEditGet-Service |
Where-Object -Property Status -EQ Running |
Select-Object Name, DisplayName, StartType |
Sort-Object -Property StartType, Name
What’s happening here:
Get-Service: Gets a list of all Windows services.Where-Object: Filters services with aStatusofRunning.Select-Object: Selects onlyName,DisplayName, andStartTypeproperties.Sort-Object: Sorts the output first byStartType, then byName.
These core concepts—parameters and pipes—are the building blocks for writing clean, powerful PowerShell scripts. Mastering them opens the door to advanced automation.
More PowerShell Pipe Examples
Pipelines let you chain multiple commands together by passing the output from one to the next. Here are a couple more examples to illustrate how versatile this can be:
| Command | Description |
|---|---|
"plan_A.txt" | Rename-Item -NewName "plan_B.md" | Renames the file plan_A.txt to plan_B.md. |
Get-ChildItem | Select-Object basename | Sort-Object * | Lists the names (base names only) of all files in the current directory, sorted alphabetically. |
Real-World PowerShell Pipe Examples
These examples showcase how SOC analysts, system admins, and threat hunters can harness the power of pipes in everyday scenarios.
| Command | What It Does |
|---|---|
Get-Process | Where-Object { $_.CPU -gt 100 } | Lists processes consuming more than 100 CPU seconds. |
Get-EventLog -LogName Security -Newest 50 | Select-Object TimeGenerated, EntryType, Message | Displays the 50 most recent Security event logs with key details. |
Get-Service | Where-Object { $_.Status -eq "Stopped" } | Sort-Object Name | Lists all stopped services and sorts them alphabetically. |
Get-ChildItem C:\Logs -Recurse | Where-Object { $_.Extension -eq ".log" } | Select-Object Name, LastWriteTime | Recursively searches for .log files and displays their names and last modified time. |
Get-LocalUser | Select-Object Name, Enabled | Where-Object { $_.Enabled -eq $false } | Finds all local user accounts that are disabled. |
Use Case Tip: These piped commands can be embedded into larger scripts for automation, incident response, or reporting.
Objects in PowerShell
PowerShell treats everything as an object—a fundamental unit that includes both properties and methods, just like in C#, Java, or Python.
- Accessing object properties or methods: Use a dot (
.) powershellCopyEdit(Get-Service -Name Fax).Status # Returns the status of the Fax service (Get-Service -Name Fax).GetType() # Returns the object type (ServiceController) - Discover object members (properties/methods): powershellCopyEdit
Get-Service -Name Fax | Get-Member
Variables in PowerShell
Variables are used to store data, similar to other programming languages.
Basic Commands:
| Command | Description |
|---|---|
New-Variable var1 | Creates a variable named var1 |
Get-Variable my* | Lists variables starting with my |
Remove-Variable bad_variable | Deletes a variable named bad_variable |
$var = "string" | Assigns a string to a variable |
$a,$b = 0 | Assigns the same value 0 to $a and $b |
$a,$b,$c = 'a','b','c' | Assigns respective values to each variable |
$a,$b = $b,$a | Swaps values of $a and $b |
$var = [int]5 | Enforces variable to store only integers |
Special Variables:
| Variable | Description |
|---|---|
$HOME | Path to user’s home directory |
$NULL | Represents null/empty value |
$TRUE | Boolean true |
$FALSE | Boolean false |
$PID | Process ID of the current PowerShell session |
Regular Expressions (Regex)
Regular expressions are patterns used to match character combinations in strings.
Common Regex Syntax:
| Syntax | Meaning |
|---|---|
[aeiou] | Match any single vowel |
[^aeiou] | Match any non-vowel |
[A-Z] | Uppercase characters |
\d / \D | Digit / Non-digit |
\w / \W | Word char (letter, digit, _) / Non-word |
\s / \S | Whitespace / Non-whitespace |
. | Any character except newline |
*, +, ? | Zero/more, one/more, zero/one occurrences |
{n,m} | Match between n and m times |
String Matching:
powershellCopyEdit"str" -Match '[aeiou]' # True if it contains a vowel
"data.txt" -NotMatch '\.exe$' # True if it doesn’t end with .exe
"Word" -CMatch 'word' # Case-sensitive match
Operators in PowerShell
Arithmetic Operators:
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | $a + $b | 30 |
- | Subtraction | $a - $b | -10 |
* | Multiplication | $a * $b | 200 |
/ | Division | $b / $a | 2 |
% | Modulus | $b % $a | 0 |
Comparison Operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
-eq | Equal | $a -eq $b | False |
-ne | Not equal | $a -ne $b | True |
-gt | Greater than | $b -gt $a | True |
-lt | Less than | $a -lt $b | True |
Logical Operators:
| Operator | Description | Example | Result |
|---|---|---|---|
-and | Logical AND | $a -and $b | True |
-or | Logical OR | $a -or 0 | True |
! | NOT | !($a -eq 10) | False |
-xor | Exclusive OR | $a -xor $b | False |
Assignment Operators:
| Operator | Description | Example |
|---|---|---|
= | Assign | $c = $a + $b |
+= | Add & assign | $c += $a |
-= | Subtract & assign | $c -= $a |
Redirection Operators
Control where output goes:
| Operator | Description | Example |
|---|---|---|
> | Overwrite to file/output device | command > out.txt |
>> | Append output to file | command >> log.txt |
2>&1 | Redirect error to standard output | command 2>&1 > all_output.txt |
Output Streams:
| Prefix | Stream | Example |
|---|---|---|
1> | Standard output | Do-Something 1>> result.txt |
2> | Standard error | command 2> error.log |
3> | Warnings | Do-Something 3> warnings.log |
4> | Verbose output | Do-Something 4>> verbose.txt |
5> | Debug messages | Do-Something 5>&1 |
6> | Info (PS 5.0+) | Do-Something 6>$null |
Matching & Collection Operators
| Operator | Description | Example |
|---|---|---|
-Like | Wildcard match | "file.txt" -Like "*.txt" |
-Match | Regex match | "log01" -Match '\d' |
-Contains | Collection contains a value | @("a", "b") -Contains "a" |
-In | Value exists in a collection | "a" -In @("a", "b") |
Miscellaneous
| Symbol | Description | Example |
|---|---|---|
() | Group expressions | (1+1)*2 → 4 |
$() | Return result of expression | "Today is $(Get-Date)" |
@() | Return results as an array | `@(Get-ChildItem |
[] | Type conversion | [int] "5" → 5 |
& | Run a command/pipeline | & 'Get-Process' (PowerShell 6.0+) |
Comments & Escaping
Use comments to document your scripts and escape special characters for formatting.
Commenting Syntax:
| Symbol | Description | Example |
|---|---|---|
# | Single-line comment | # This is a comment |
<# ... #> | Multi-line comment | <# Block comment here #> |
Escape Sequences:
| Escape | Output |
|---|---|
"`" | Escaped double quote |
`t | Tab |
`n | New line |
` | Line continuation |
Enumeration is the process of extracting information such as users, groups, resources, and other interesting data from a system.
Here’s a table of essential enumeration commands every pentester should know:
| Command | Description |
|---|---|
net accounts | Retrieve the system’s password policy. |
whoami /priv | View the privileges of the currently logged-in user. |
ipconfig /all | List all network interfaces, IP addresses, and DNS settings. |
Get-LocalUser | Select * | List all local users on the machine. |
Get-NetRoute | Display IP route information from the system’s routing table. |
Get-Command | List all available PowerShell commands. |
Enumeration Commands
Enumeration is the process of extracting information such as users, groups, resources, and other interesting data from a system.
Here’s a table of essential enumeration commands every pentester should know:
| Command | Description |
|---|---|
net accounts | Retrieve the system’s password policy. |
whoami /priv | View the privileges of the currently logged-in user. |
ipconfig /all | List all network interfaces, IP addresses, and DNS settings. |
Get-LocalUser | Select * | List all local users on the machine. |
Get-NetRoute | Display IP route information from the system’s routing table. |
Get-Command | List all available PowerShell commands. |
PowerShell for Administrators
PowerShell is built for automation, especially for system administration. Here’s a list of useful cmdlets for daily sysadmin tasks:
| Command | Description |
|---|---|
New-PSDrive -Name "L" -PSProvider FileSystem -Root "\\path\to\data" -Persist | Mounts a network drive (don’t use C:) |
Enable-PSRemoting | Enables remote PowerShell access |
Invoke-Command -ComputerName pc01, pc02 -ScriptBlock {cmd /c setup.exe} | Run batch scripts remotely |
Get-Hotfix | Lists installed software patches |
$Password = Read-Host -AsSecureString + New-LocalUser "User03" -Password $Password | Adds a new local user |
Get-Process | Lists current processes |
Start-Sleep 10 | Pauses script for 10 seconds |
Start-Job, Receive-Job | Manage background jobs |
New-PSSession, Get-PSSession | Create/view remote sessions |
Enable-NetFirewallRule | Enable a disabled firewall rule |
ConvertTo-Html | Convert objects to HTML format |
Invoke-RestMethod | Call a REST API endpoint |
Example For Backing-up Files:
powershellCopyEditGet-ChildItem C:\data -Recurse |
? { !$_.PsIsContainer -and $_.LastWriteTime -gt (Get-Date).Date } |
% { Copy-Item -Path $_.FullName -Destination "\\path\to\backup" }
Final Thoughts on PowerShell
PowerShell’s flexibility makes it an indispensable tool for anyone in the IT field. Whether you’re a security analyst, pen tester, developer, sysadmin, or just beginning your automation journey, PowerShell belongs in your toolkit. Have any favorite PowerShell tricks or tools you use? Drop them in the comments below, and let’s chat about them!