PowerShell for Cybersecurity - Lab
Duration: 90-120 minutes Difficulty: Beginner Environment: Windows 11 Pro VM on VMWare Fusion
Important Safety Notice
CRITICAL: The techniques you'll learn in this lab are powerful and must be used responsibly. You should ONLY use these commands on systems you own or have explicit written permission to test. Unauthorized access to computer systems is illegal and unethical. These skills are for defensive security and learning purposes only.
Lab Setup
Step 1: Opening PowerShell as Administrator
You need to open PowerShell with administrator privileges. Many security-related commands require elevated access to view system information and logs.
Click the Start menu
Type
PowerShellRight-click on Windows PowerShell
Select Run as administrator
Click Yes when prompted by User Account Control
Important: The title bar should say 'Administrator: Windows PowerShell'. If you don't see 'Administrator' in the title, close PowerShell and try again.
Step 2: Set Execution Policy
PowerShell has a security feature called 'Execution Policy' that controls whether scripts can run. Let's check the current policy and adjust it if needed.
Get-ExecutionPolicyIf you see 'Restricted', it means scripts can't run. Change this temporarily for your user account only:
Type 'Y' and press Enter when prompted. This allows locally created scripts to run, but still requires downloaded scripts to be signed by a trusted publisher.
Step 3: Enable Security Event Logging
Windows 11 doesn't enable all security auditing by default. You need to enable audit policies so that security events like logon attempts are actually recorded.
IMPORTANT: This must be done in PowerShell running as Administrator
Run these commands one by one:
These commands enable Windows to log security events. Without this, the Security event log would be mostly empty.
Step 4: Verify Event Log Access
Now verify that you can access the Security event log. If you get an error about 'registry access not allowed', it means PowerShell isn't running as Administrator.
You should see a list of event logs including Security, System, and Application. The 'Entries' column shows how many events are in each log. Don't worry if Security has 0 or very few entries right now—we just enabled auditing, so new events will start appearing as you work.
Module 1: System Reconnaissance
Introduction
System reconnaissance is the first phase of any security assessment or investigation. You need to understand the environment: What operating system is running? Who are the users? What's the system configuration? Let's learn how to gather this information quickly using PowerShell.
Exercise 1.1: Gathering System Information
Command 1: Basic System Information
This command breaks down as follows:
Get-ComputerInfo- Retrieves comprehensive system information|- This is called a 'pipe'. It takes the output from the left side and sends it to the right sideSelect-Object- Filters the output to show only specific propertiesWe're selecting: Computer Name, Windows Version, Architecture (32-bit or 64-bit), and Processor information
Look at your output. You can see your computer name, the Windows version, and that you're running a 64-bit system. Different OS versions have different vulnerabilities. An attacker would look for this information to find exploits that work on your specific system.
Command 2: Operating System Details
This command uses CIM—the Common Information Model—to query Windows Management Instrumentation, or WMI. Notice the 'LastBootUpTime' field. This tells you when the system was last restarted.
Why would you care about when a system was last rebooted? If you're investigating a suspected compromise and you see the system was rebooted at 3 AM last night, that's suspicious. It could mean someone installed malware that required a reboot, or they were trying to clear evidence from memory.
Command 3: Current User
This simple command shows your current user account. It's one of the first commands an attacker runs after gaining access to a system.
Command 4: User Privileges
This shows your privileges—what you're allowed to do on the system. Look for privileges like 'SeDebugPrivilege' or 'SeImpersonatePrivilege'. These are powerful and can be abused by attackers for privilege escalation.
Notice some privileges say 'Disabled'. This means you have the privilege, but it's not currently active. Programs can enable these privileges when needed. Attackers look for accounts with powerful privileges to exploit.
Exercise 1.2: Enumerating Local Users and Groups
Command 1: List Local Users
This lists all local user accounts. Pay attention to:
Name - The account name
Enabled - Is the account active?
LastLogon - When did they last log in? If this is blank, the account has never been used
PasswordLastSet - When was the password last changed? Old passwords are security risks
Look at your output. Do you see any accounts you don't recognize? Any enabled accounts that have never been used? Those are potential security risks. In a real investigation, you'd investigate any unexpected accounts.
Command 2: List Administrators
This is one of the MOST IMPORTANT commands you'll learn. It shows who has administrator privileges on this machine. Administrators have complete control over the system. If you see an unexpected account here, that's a major red flag.
In a security audit, you'd document everyone in this list and verify they should have admin rights. Principle of least privilege: users should only have the minimum permissions needed to do their job.
Command 3: Find Unused Accounts
This command introduces filtering with Where-Object. You're finding accounts where LastLogon equals null—meaning they've never been used. The $_ represents each item as it goes through the filter.
Look at your results. Are any of these accounts enabled? An enabled account that's never been used is suspicious. It could be a backdoor account created by an attacker. What would you do if you found one in a real investigation?
Expected answer: Investigate when it was created, disable it, check if it's in any privileged groups, review logs for any activity.
Module 2: Process and Service Analysis
Introduction
Malware runs as processes on a system. Learning to identify suspicious processes is a critical skill for detecting active threats. You'll also look at services, which are programs that run in the background and often start automatically when Windows boots.
Exercise 2.1: Investigating Running Processes
Command 1: Top CPU Usage Processes
This command lists all running processes and shows the top 10 by CPU usage:
Get-Process- Gets all running processesSelect-Object Name, Id, CPU, Path- Shows only these propertiesSort-Object CPU -Descending- Sorts by CPU usage, highest firstSelect-Object -First 10- Shows only the top 10
Look at the processes using the most CPU. Do you recognize them? High CPU usage can indicate cryptomining malware or other malicious activity. The 'Id' column is the Process ID or PID—a unique number for each running process. The 'Path' shows where the executable file is located.
Command 2: Processes Without Company Information
This is a powerful detection technique. Most legitimate software has a 'Company' name embedded in the executable—like Microsoft Corporation. This command finds processes that DON'T have a company name, which is suspicious.
Look at your results. You'll probably see some legitimate processes here too—not all software includes company information. But this is a great starting point for finding suspicious processes. In a real investigation, you'd research each one.
Important Note: Some system processes might not have a Path. That's normal for certain kernel-level processes. But if you see a process with no company name AND a path in a user's Downloads folder or Temp directory, that's highly suspicious.
Command 3: All Processes with Company Information
This shows all processes that have a file path, sorted by company. It's useful for getting an overview of what's running and who made it.
Practical Exercise: Analyze Notepad Process
Open Notepad—click Start and type 'Notepad', then open it. Keep it open.
This shows EVERYTHING about the Notepad process. Look for:
Id - The Process ID
Path - Should be
C:\Windows\System32\notepad.exeCompany - Should be 'Microsoft Corporation'
StartTime - When you opened it
Why is the Path important? Imagine you see 'notepad.exe' running, but the path is C:\Users\YourName\Downloads\notepad.exe. That's NOT the real Notepad—it's malware disguised with a trusted name. Always verify the path!
Exercise 2.2: Analyzing Services
Command 1: List All Services
This lists all services. The 'Status' shows if it's Running or Stopped. The 'StartType' shows when it starts:
Automatic - Starts when Windows boots
Manual - Starts when needed
Disabled - Can't start at all
Command 2: Failed Automatic Services
This finds services that are supposed to start automatically but aren't running. This could indicate:
A service that failed to start (potential system problem)
A service that was stopped by malware
A service that's disabled as part of system hardening
In a real investigation, you'd check if any critical security services are in this list—like antivirus or Windows Defender.
Command 3: Check Windows Defender Services
This searches for services with 'Defender' in the name. The -like operator allows wildcards (*). This is useful for quickly checking if security software is running.
You should see Windows Defender services here. If they're stopped or disabled on a production system, that's a major red flag—someone might have disabled your antivirus.
Module 3: Network Security Analysis
Introduction
Network connections are how malware communicates with attackers—sending stolen data out or receiving commands. You'll learn how to see all network connections and identify which programs are responsible for them.
Exercise 3.1: Examining Network Connections
Command 1: All TCP Connections
This shows all TCP network connections. The columns are:
LocalAddress - Your computer's IP address
LocalPort - The port your computer is using
RemoteAddress - The IP address you're connected to
RemotePort - The port on the remote computer
State - The connection status (Established, Listen, etc.)
OwningProcess - The Process ID responsible for this connection
You'll see a lot of output. Focus on the 'State' column. 'Established' means data is actively being transferred. 'Listen' means a program is waiting for incoming connections.
Command 2: Established Connections Only
This filters to show only established connections—active communication happening right now. These are the most interesting for security investigations.
Command 3: Advanced - Process Names for Connections
This is more advanced, but very powerful. It takes each connection and looks up the process name. Now instead of just seeing a Process ID, you see the actual program name. How it works:
ForEach-Object- Loops through each connectionGet-Process -Id $_.OwningProcess- Gets the process for each connection[PSCustomObject]@{...}- Creates a custom object with the data you wantThe result shows which program is responsible for each connection
Practical Exercise: Generate Network Activity
Open your web browser and visit any website—like google.com. Keep the browser open.
Run the advanced command again:
Can you find your browser's connections? Look for the browser process name—like 'msedge', 'chrome', or 'firefox'. You should see connections to remote IP addresses on port 443 (HTTPS) or port 80 (HTTP).
In a real investigation, if you saw connections to unknown IP addresses from unexpected processes, you'd investigate. You'd look up the IP address to see what country it's in, who owns it, and if it's known to be malicious.
Exercise 3.2: Network Configuration Review
Command 1: Network Adapters
This shows your network adapters and their IP addresses. You'll see both IPv4 and IPv6 addresses. The 'InterfaceAlias' is the network adapter name—like 'Ethernet' or 'Wi-Fi'.
Command 2: DNS Servers
This shows your DNS server addresses. DNS translates domain names like 'google.com' into IP addresses. This is critical for security because attackers sometimes change DNS settings to redirect your traffic to malicious servers.
You should recognize these DNS servers. Common ones are:
8.8.8.8 (Google)
1.1.1.1 (Cloudflare)
Your router's IP (like 192.168.1.1)
If you see unfamiliar DNS servers, investigate them.
Command 3: Default Gateway
This shows your default gateway—the router that sends your traffic to the internet. The '0.0.0.0/0' means 'all traffic'. This is useful for understanding your network topology.
Module 4: Windows Event Log Analysis
Introduction
Windows Event Logs are like a detailed diary of everything that happens on a system. They record logon attempts, system errors, security events, and much more. For security investigations, event logs are often the most valuable source of evidence.
Exercise 4.1: Introduction to Event Logs
Command 1: List Available Event Logs
This shows all available event logs on the system. The main ones you care about are:
Security - Authentication, access control, security events
System - Hardware, drivers, system services
Application - Software events
The 'Entries' column shows how many events are in each log.
Troubleshooting: If you get "Requested registry access is not allowed" error, it means PowerShell isn't running as Administrator. Close PowerShell, right-click it, and select 'Run as administrator'. Make sure you see 'Administrator' in the title bar.
Command 2: Recent System Events
This retrieves the 10 most recent events from the System log. The columns are:
TimeGenerated - When the event occurred
EntryType - Information, Warning, or Error
Source - What component generated the event
EventID - A unique number identifying the event type
Message - Details about what happened
Event IDs are important. Each type of event has a specific ID. For example, Event ID 4624 is always a successful logon. Security analysts memorize common Event IDs.
Exercise 4.2: Investigating Failed Logon Attempts
Command 1: Search for Failed Logons
This searches the Security log for Event ID 4625 and shows the first 10 results. If your Security log is empty or has no 4625 events, that's okay—it means there haven't been any failed logon attempts yet.
Practical Exercise - Generate a Failed Logon Event
If you have no results, let's create a failed logon event:
Press Windows key + L to lock your screen
Try to log in with an INCORRECT password (just type random characters)
You'll get an error—that's expected
Log back in with your correct password
Return to PowerShell
Now run the command again:
You should see your failed logon attempt logged! Look at the TimeGenerated—it should be just a minute or two ago. The Message contains details like the account name and the reason for failure.
Command 2: Count Failed Logons
This counts the total number of failed logon attempts. In a real investigation, if you saw hundreds or thousands of failed attempts, that would indicate an attack.
Exercise 4.3: Successful Logon Events
Command: Recent Successful Logons
This shows recent successful logons. You should see your own logon from when you started this lab. The Message field contains details like the account name and logon type.
In the Message, look for 'Logon Type'. Different numbers mean different things:
Type 2 - Interactive logon (keyboard)
Type 3 - Network logon (accessing a shared folder)
Type 10 - Remote Desktop
Knowing the logon type helps you understand how someone accessed the system.
Exercise 4.4: System Event Analysis
Command 1: System Errors in Last 24 Hours
This finds system errors in the last 24 hours. The -After (Get-Date).AddDays(-1) part is a time filter. Get-Date gets the current date and time, and AddDays(-1) subtracts one day.
Look at the errors. Are there any patterns? Repeated errors from the same source could indicate a failing driver or hardware issue. Attackers sometimes exploit driver vulnerabilities.
Command 2: Recent Warnings
This shows the 20 most recent warnings. Warnings aren't as severe as errors, but they still indicate potential issues.
Advanced Technique - Export Events to CSV
This exports the 100 most recent Security events to a CSV file on your desktop. CSV files can be opened in Excel for easier analysis. The $env:USERNAME automatically inserts your username into the path.
Check your desktop—you should see a file called 'SecurityEvents.csv'. You can open it in Excel or any text editor. This is useful for sharing findings with your team or keeping records for compliance.
Module 5: File System Forensics
Introduction
File system forensics involves searching for suspicious files, analyzing file properties, and detecting hidden or malicious content. Attackers often drop files on systems—malware, tools, or stolen data.
Exercise 5.1: Searching for Suspicious Files
Command 1: Recent Files in Downloads
This searches your Downloads folder for files modified in the last 7 days:
Get-ChildItem- Lists files and folders (like 'dir' or 'ls')-Path C:\Users\$env:USERNAME\Downloads- The folder to search-Recurse- Search subfolders too-File- Only show files, not foldersWhere-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)}- Filter for files modified in the last 7 daysSelect-Object Name, LastWriteTime, Length- Show these properties
The Downloads folder is a common place for malware to land—from malicious email attachments or drive-by downloads. In an investigation, you'd look for unexpected files here.
Command 2: Executable Files in Downloads
This finds all executable files (.exe) in your Downloads folder. Executables can be legitimate software installers or malware. The -Filter parameter is faster than Where-Object for simple pattern matching.
Do you recognize all these files? Any .exe files you don't remember downloading should be investigated. Check the file name, the date, and the size. Research the file name online to see if it's known malware.
Command 3: Script Files in User Profile
This searches for script files in your user profile:
*.ps1 - PowerShell scripts
*.bat - Batch files
*.vbs - VBScript files
Attackers often use scripts to automate tasks. The -ErrorAction SilentlyContinue suppresses errors for folders you don't have permission to access.
This might take a minute to run because it's searching your entire user profile. Script files in unexpected locations—like Temp folders or AppData—are suspicious.
Exercise 5.2: File Hash Calculation
Command 1: SHA256 Hash
This calculates the SHA256 hash of notepad.exe. SHA256 is the current industry standard—it produces a 64-character hexadecimal string.
Copy this hash. You could search for it on VirusTotal.com to see if this file is known to be malicious. For notepad.exe, it should be clean—but if you found an unknown file, this is how you'd check it.
Command 2: MD5 Hash
This calculates the MD5 hash of the same file. MD5 is older and less secure than SHA256, but you'll still see it in some contexts. Notice the hash is shorter—32 characters instead of 64.
Practical Exercise: Hash Sensitivity Test
Let's see how sensitive hashes are to changes:
Open Notepad
Type 'Hello World'
Save it to your Desktop as 'test.txt'
Close Notepad
Run this command and note the hash value.
Now:
Open test.txt again
Add a single character—just type '!' at the end so it says 'Hello World!'
Save and close
Run the command again. Look at the hash now—it's completely different! You only added one character, but the entire hash changed. This is why hashes are so useful for detecting tampering.
Exercise 5.3: Finding Hidden Files
Command: Find Hidden Files
The -Force parameter is the key here—it makes PowerShell show hidden and system files. Without it, you'd never see them. This searches your entire user profile for hidden files.
You'll probably see some legitimate hidden files—like configuration files for applications. But in an investigation, you'd examine each one to determine if it's legitimate or malicious.
Module 6: Security Automation
Introduction
So far you've been running commands one at a time. But PowerShell's real power is automation—combining multiple commands into scripts that run automatically. This saves time and ensures consistency.
Exercise 6.1: Creating a System Information Report
You're going to create a script that generates a comprehensive security report. It will gather system information, list administrators, show running processes, and display network connections—all in one text file.
The Complete Script:
This script works as follows:
$reportPathis a variable that stores the file pathOut-File -FilePath $reportPathwrites to the file-Appendadds to the file instead of overwriting itYou're using commands you already know, just combining them
Write-Hostdisplays a message in green when it's done
Copy this entire script and paste it into PowerShell. You can copy multiple lines at once. Then press Enter to run it.
Check your Desktop—you should see a file called 'SecurityReport.txt'. Open it and look at the contents. This is a snapshot of your system's security posture. You could run this daily and compare the reports to detect changes.
Exercise 6.2: Monitoring for Suspicious Activity
Now let's create a real-time monitoring script. This will watch for new processes and alert you when they start. This is a simplified version of what endpoint detection and response (EDR) tools do.
The Complete Script:
This script works as follows:
$previousProcesses = Get-Process- Takes a snapshot of current processeswhile ($true)- Creates an infinite loopStart-Sleep -Seconds 5- Waits 5 seconds between checksCompare-Object- Compares the old snapshot with a new oneforeach- Loops through each new processWhen a new process is detected, it prints a message with the time, name, and PID
Press Ctrl+C to stop the script
Copy and paste this script into PowerShell and run it. Then, while it's running, open an application—like Calculator or Notepad. You should see the script detect it!
Press Ctrl+C to stop the monitoring script.
In a real environment, you'd log these detections to a file and set up alerts for suspicious processes. This demonstrates the concept of continuous monitoring.
Module 7: Practical Scenario - Incident Response
Introduction
Now you're going to put everything together in a realistic scenario. Imagine you're a security analyst and you've received an alert about potential suspicious activity on a workstation. Your job is to investigate using PowerShell.
The Scenario
It's Monday morning. You receive an alert from your security monitoring system: 'Suspicious network activity detected on workstation WS-1234'. The alert indicates unusual outbound connections to an unknown IP address. You need to investigate immediately.
Investigation Step 1: Check for Unusual Processes
First, you need to see if there are any suspicious processes running. Look for processes without a company name and that have a file path—these are often indicators of malware.
Run this command. Look at the results. Do you see any processes running from unusual locations? Common malware locations include:
C:\Users[Username]\AppData\Local\Temp
C:\Users[Username]\Downloads
C:\ProgramData
Legitimate software is usually in C:\Program Files or C:\Windows\System32
What would you do if you found a suspicious process? You'd note the PID, the path, calculate its hash, and research it. You might also need to terminate it if it's confirmed malicious.
Investigation Step 2: Look for Unusual Network Connections
The alert mentioned unusual network activity. Find all established connections to external IP addresses—not local or private networks.
This filters out local connections (127.) and private network connections (192.168. and 10.*). What's left are connections to the internet.
Look at the RemoteAddress column. These are IP addresses your computer is communicating with right now. You'd investigate each one:
Look up the IP on whois databases to see who owns it
Check if it's on threat intelligence feeds
Determine if the process should be making these connections
For example, your browser connecting to Google is normal. But 'svchost.exe' connecting to an IP in a foreign country? That's suspicious.
Investigation Step 3: Check Recent Security Log Events
Check for recent failed authentication attempts. Multiple failures could indicate the attacker is trying to escalate privileges or move laterally.
This searches the 50 most recent Security events for failures.
Look for patterns. Multiple failed logons from the same account? That's suspicious. Failed attempts to access sensitive files? Also suspicious. In a real investigation, you'd correlate the timing of these events with the network activity alert.
Investigation Step 4: Look for Recently Created Files in Suspicious Locations
Malware often drops files in temporary directories. Check for recently created files in the Temp folder.
This finds files created in the last hour in your Temp folder.
Any unexpected executables or scripts here? In a real incident, you'd:
Calculate the hash of suspicious files
Submit them to VirusTotal or a malware sandbox
Preserve them as evidence
Delete them if confirmed malicious
Investigation Step 5: Document Your Findings
The final step in any investigation is documentation. Create an incident report with your findings.
This script creates a comprehensive incident report with all your findings. The filename includes the date and time so each report is unique. Copy, paste, and run this script.
Check your Desktop—you should see the incident report. Open it and review the contents. In a real incident, you'd share this with your team, your manager, and possibly law enforcement if it's serious enough.
Additional Resources
Microsoft PowerShell Documentation: https://docs.microsoft.com/powershell
PowerShell Gallery: https://www.powershellgallery.com (thousands of community scripts)
SANS PowerShell Cheat Sheet: Google 'SANS PowerShell Cheat Sheet' for a quick reference
Website entirely built with Powershell with tools, powershell games, etc: https://powershellforhackers.com/
Bonus Challenges
Challenge 1: Port Scanner Detection
Write a script that identifies processes listening on uncommon ports (outside the range 1-1024).
Challenge 2: User Activity Timeline
Create a script that generates a timeline of user logon/logoff events for the past week.
Challenge 3: File Integrity Checker
Create a script that calculates and stores hashes of important system files, then checks them periodically for changes.
Part 1: Create Baseline
Part 2: Check Integrity
Final Thoughts
Thank you for completing this PowerShell for Cybersecurity lab! You've taken an important step in your cybersecurity journey. PowerShell is a skill that will serve you throughout your career whether you become a security analyst, penetration tester, system administrator, or incident responder.
Remember: Practice makes perfect. Keep using these commands, build your own scripts, and challenge yourself. The lab materials are yours to keep - review them, share them with classmates, and use them as a reference.
Stay curious, stay ethical, and keep learning. Good luck in your cybersecurity careers!
Last updated
