Windows Reference
🛠️ Operations Tools
🖥️ Command Generator General
Help commands Stop a specific service by its name Start a specific service by its name Check available disk space on all drives Create a new local user account Delete a local user account List all running processes on the system Terminate a specific process by its name Get the system's IP configuration Test connectivity to a specific IP address or URL Read content from a text file Write content to a text file Copy a file to a new location Export data to a CSV file Import data from a CSV file Retrieve the most recent entries from the System event log Get detailed system information Manage registry values Display the current date and time List all drives available on the system Display the current working directory Change the current working directory to the root of C drive List all the processes currently running on the system Create a new directory called 'NewFolder' on the desktop Display a list of all installed programs on the system Empty the Recycle Bin Display network adapter configurations Show all listening ports on the system Find large files on the system Check the status of the Windows Firewall Retrieve detailed system information Output a list of environment variables Measure the execution time of a script block
// Display help for a specific cmdlet
Get-Help Get-Process # Displays help information for the 'Get-Process' command
Get-Help Get-Service
// List all available cmdlets
Get-Command
// Display help for a specific topic
Get-Help about_If
// Display help for a specific provider
Get-Help FileSystem
// Display help for a specific script
Get-Help C:\Scripts\MyScript.ps1
// Retrieve detailed information about PowerShell commands
Get-Command -Noun Service # Lists all commands that involve services
Get-Command -Verb Get # Lists all commands that use the 'Get' verb
Get-Command -Module Net* # Lists all commands from modules starting with 'Net'
// Creates a new local user with a specified password
$password = ConvertTo-SecureString 'Password123' -AsPlainText -Force
New-LocalUser -Name 'User1' -Password $password
// Tests network connectivity to www.example.com on port 80
Test-NetConnection -ComputerName 'www.example.com' -Port 80
// Exports object data to a CSV file without type information
$data | Export-Csv -Path 'C:\export.csv' -NoTypeInformation
// Retrieves the 10 most recent entries from the System event log
Get-EventLog -LogName System -Newest 10
// Retrieves detailed information about the computer system
Get-WmiObject -Class Win32_ComputerSystem
// Sets a registry key value
Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion' -Name 'Test' -Value 'Data'
// Creates a new directory on the desktop
New-Item -Path 'C:\Users\Public\Desktop\NewFolder' -ItemType Directory
// Gets all installed programs from the registry
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Select-Object DisplayName, DisplayVersion, Publisher
// Lists configuration details of all network adapters
Get-NetAdapter | Select-Object Name, Status, MacAddress, LinkSpeed
// Displays all TCP ports on which the system is listening
Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' }
// Finds files larger than 500MB in the C: drive
Get-ChildItem C:\ -Recurse | Where-Object { $_.Length -gt 500MB } | Select-Object FullName, Length
// Retrieves the status of the Windows Firewall
Get-NetFirewallProfile | Select-Object Name, Enabled
Create and use a custom object to store and display data Run a script block asynchronously with jobs Filter and process complex data with pipelining Utilize loops to manage multiple items effectively Perform operations on files based on conditions Use regex to match and replace text in file contents Automatically handle errors with try/catch blocks Use PowerShell to interact with the Windows API Schedule tasks to run at specific times using PowerShell Manipulate and manage network settings Manage Active Directory users and groups Generate and manage certificates Query and manage DNS settings Advanced file operations, such as creating zip files Work with JSON data Monitor real-time performance of system components Extract and analyze events from the Windows event logs Use transactions to manage registry changes safely Monitor and alert on file modifications in a directory Manage Windows Firewall rules Automate cleanup of temporary files Create and manage local groups and membership Retrieve and manipulate BIOS settings Advanced string manipulation with regex Perform bulk user operations in Active Directory Automatically install and update software packages Manage disk partitions and volumes Retrieve network adapter settings and statistics Control and manage remote desktop settings Automate the backup of event logs Create a detailed system health report Schedule tasks to automate routine operations Extract and analyze performance data Configure service accounts with specific permissions
// Creates a custom PSObject with properties
$customObject = New-Object PSObject -Property @{
Name = 'John Doe';
Age = 30;
Department = 'HR'
}
// Displays the custom object
$customObject
// Starts a background job that runs a script block
$job = Start-Job -ScriptBlock {
Get-Process | Where-Object {$_.CPU -gt 100}
}
// Gets the job results after completion
Receive-Job -Job $job
Remove-Job -Job $job
// Uses pipeline to filter and select properties from processes
Get-Process | Where-Object {$_.WorkingSet -gt 100MB} | Select-Object Name, ID, WorkingSet
// Loop through all services and restart if stopped
Get-Service | ForEach-Object {
if ($_.Status -eq 'Stopped') {
Start-Service $_.Name
}
}
// Deletes files older than 30 days in a specific directory
Get-ChildItem 'C:\OldFiles' | Where-Object {
$_.LastWriteTime -lt (Get-Date).AddDays(-30)
} | Remove-Item
// Replaces all occurrences of 'text' with 'info' in 'log.txt'
$content = Get-Content 'C:\log.txt'
$updatedContent = $content -replace 'text', 'info'
Set-Content -Path 'C:\log.txt' -Value $updatedContent
// Tries to execute a command and catches any exceptions
try {
Get-WmiObject -Class Win32_BIOS
} catch {
Write-Output 'An error occurred: $_'
}
// Uses Add-Type to access system functions through the Windows API
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show('Hello, World!')
// Creates a scheduled task to run a script at 7 AM daily
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-File C:\Scripts\DailyReport.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 7am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName 'DailyReport'
// Changes the IP address and subnet mask of a network adapter
$interface = Get-NetAdapter -Name 'Ethernet'
New-NetIPAddress -InterfaceAlias $interface.Name -IPAddress 192.168.1.100 -PrefixLength 24 -DefaultGateway 192.168.1.1
// Adds a user to a group in Active Directory
Add-ADGroupMember -Identity 'HRStaff' -Members 'JohnDoe'
// Creates a new self-signed certificate for code signing
$cert = New-SelfSignedCertificate -DnsName 'example.com' -CertStoreLocation 'cert:\LocalMachine\My'
$cert | Export-Certificate -FilePath 'C:\exampleCert.cer'
// Retrieves DNS server addresses for a specific adapter
Get-DnsClientServerAddress -InterfaceAlias 'Ethernet'
// Compresses a directory into a zip file
Compress-Archive -Path 'C:\Data' -DestinationPath 'C:\Backup.zip'
// Converts an object to JSON format and writes to a file
$obj = @{Name = 'John'; Age = 31}
$json = $obj | ConvertTo-Json
Set-Content -Path 'C:\user.json' -Value $json
// Uses Get-Counter to monitor CPU and memory usage
$counters = @('\Processor(_Total)\% Processor Time', '\Memory\Available MBytes')
Get-Counter -Counter $counters -SampleInterval 1 -MaxSamples 10
// Queries the Application log for errors that occurred in the past 24 hours
Get-EventLog -LogName Application -EntryType Error |
Where-Object {$_.TimeGenerated -gt (Get-Date).AddDays(-1)}
// Starts a transaction to modify registry values
Start-Transaction
Set-ItemProperty -Path 'HKLM:\Software\MyApp' -Name 'Setting1' -Value 'NewValue' -UseTransaction
Complete-Transaction
// Creates a file system watcher to monitor changes in 'C:\Data', '*.txt' -Property @{
IncludeSubdirectories = $true;
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}
// Register an action to be performed when a file is changed
Register-ObjectEvent $watcher 'Changed' -Action {
Write-Host 'A file was modified.'
}
// Adds a new inbound rule to allow TCP traffic on port 8080
New-NetFirewallRule -DisplayName 'Allow Port 8080' -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow
// Deletes files in the Temp folder older than 7 days
Get-ChildItem 'C:\Windows\Temp' |
Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-7) } |
Remove-Item -Force
// Creates a new local group 'Developers'
New-LocalGroup -Name 'Developers'
// Adds a user to the 'Developers' group
Add-LocalGroupMember -Group 'Developers' -Member 'User1'
// Retrieves BIOS information and displays serial number
$bios = Get-WmiObject Win32_BIOS
Write-Output 'BIOS Serial Number: ' + $bios.SerialNumber
// Finds and replaces phone number formats in a text string
$text = 'Call us at 123-456-7890'
$newText = $text -replace '\d{3}-\d{3}-\d{4}', '555-1234'
Write-Output $newText
// Disables all users in the 'Sales' department
Get-ADUser -Filter 'Department -eq "Sales"' |
Set-ADUser -Enabled $false
// Uses PowerShell to install or update a softwarepackage from a repository
Install-Package -Name 'Git' -Source 'PSGallery' -Force
// Initializes a new disk and creates a new volume
Initialize-Disk -Number 2 -PartitionStyle GPT
New-Partition -DiskNumber 2 -UseMaximumSize -AssignDriveLetter |
Format-Volume -FileSystem NTFS -NewFileSystemLabel 'NewVolume'
// Enables Remote Desktop on the machine
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Value 0
// Generates a system health report and saves it as an HTML file
$report = Get-WmiObject Win32_ComputerSystem | ConvertTo-Html
Set-Content -Path 'C:\SystemReport.html' -Value $report
// Creates a scheduled task to run a script every day at 7 AM
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-File "C:\Scripts\DailyJob.ps1"'
$trigger = New-ScheduledTaskTrigger -Daily -At 7am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName 'DailyTask' -Description 'Performs daily maintenance tasks'
Repeatedly test network connectivity to a server Use PowerShell remoting to execute commands on remote systems Implement error handling and logging for a robust script Automate system health checks and generate reports Create advanced functions with parameter validation Use PowerShell to interact with APIs for data retrieval Script complex file and directory operations, including permissions Implement advanced debugging techniques Automate and secure database queries and operations Manage and monitor Windows services in depth Automate the creation and management of Hyper-V virtual machines Configure advanced DNS settings using PowerShell Perform advanced event log queries using complex filters Manage and configure SSL/TLS settings across web services Optimize and configure system performance settings Automate the deployment and configuration of network printers Use PowerShell to manage API interactions with complex data parsing Script the automation of Windows Updates installations Implement complex file system monitoring with custom actions Control advanced user account properties Implement advanced auditing for security events Create a script to monitor and report system resource utilization Automate complex data backup operations Manage system restore points and recovery Advanced scripting for hardware configuration changes Script dynamic DNS updates in complex network environments Utilize PowerShell for advanced monitoring of log files Automate the management of network routes Implement conditional scripting based on system performance metrics Enhance security by automating the scanning and patching process
// Defines a function to repeatedly test connectivity
function Test-ConnectionRepeatedly {
param ([string]$computerName, [int]$count)
// Loop to perform the test multiple times
for ($i=0; $i -lt $count; $i++) {
Test-Connection -ComputerName $computerName
Start-Sleep -Seconds 10
}
}
// Calls the function with parameters
Test-ConnectionRepeatedly -computerName 'server01' -count 5
// Establishes a remote session and executes a command
$session = New-PSSession -ComputerName 'Server01'
Invoke-Command -Session $session -ScriptBlock {
Get-Service
}
Remove-PSSession -Session $session
// Example script with error handling and logging
try {
$result = Get-Item 'C:\NonExistentFile.txt'
} catch {
Write-Error 'An error occurred: $_'
Add-Content -Path 'C:\ErrorLog.txt' -Value ('Error on ' + (Get-Date) + ': ' + $_.Exception.Message)
} finally {
Write-Host 'Cleanup can go here'
}
// Performs a series of system health checks and compiles a report
$cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
$diskSpace = Get-PSDrive C | Select-Object Used, Free
$services = Get-Service | Where-Object {$_.Status -ne 'Running'}
$report = @{
'CPU Usage' = $cpuUsage.CounterSamples.CookedValue;
'Disk Space' = $diskSpace;
'Stopped Services' = $services
}
$report | ConvertTo-Html | Set-Content 'C:\SystemHealth.html'
// Defines a function with parameter validation
function Set-ServerFeature {
param (
[Parameter(Mandatory)]
[string]$FeatureName,
[ValidateSet('Enabled', 'Disabled')]
[string]$State
)
Write-Host "Setting $FeatureName to $State"
}
// Retrieves data from a REST API
$uri = 'https://api.example.com/data'
$response = Invoke-RestMethod -Uri $uri
$response.items
// Modifies filer permissions for a directory
$acl = Get-Acl 'C:\DataFolder'
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Domain\User1', 'FullControl', 'Allow')
$acl.SetAccessRule($rule)
Set-Acl -Path 'C:\DataFolder' -AclObject $acl
// Demonstrates the use of debugging features
Set-PSDebug -Trace 2
function Test-Debug {
[CmdletBinding()]
param($InputData)
Write-Verbose 'Processing data'
# Process data here
}
Write scripts that use conditional logic to manage system configurations
```powershell
// Script that adjusts system settings based on current conditions
$systemInfo = Get-ComputerInfo
if ($systemInfo.WindowsVersion -ge '10.0') {
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Session Manager\Memory Management' -Name 'ClearPageFileAtShutdown' -Value 1
} else {
Write-Output 'Older Windows version, no action taken'
}
// Runs a secure query against a SQL database
$connectionString = 'Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;'
$query = 'SELECT * FROM Users WHERE Active = 1'
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
$connection.Open()
$reader = $command.ExecuteReader()
while ($reader.Read()) {
[PSCustomObject]@{
Username = $reader['Username']
Status = $reader['Active']
}
}
$connection.Close()
// Checks and restarts a service if it's not running
$serviceName = 'WSearch'
$service = Get-Service -Name $serviceName
if ($service.Status -ne 'Running') {
Start-Service -Name $serviceName
Write-Output '$serviceName service started'
} else {
Write-Output '$serviceName is already running'
}
// Creates a new virtual machine with specified parameters
New-VM -Name 'TestVM' -MemoryStartupBytes 2GB -NewVHDPath 'D:\VMs\TestVM.vhdx' -NewVHDSizeBytes 40GB -Generation 2
// Sets network adapter to use a virtual switch
Add-VMNetworkAdapter -VMName 'TestVM' -SwitchName 'ExternalSwitch'
// Sets DNS client server addresses with primary and secondary DNS
Set-DnsClientServerAddress -InterfaceIndex (Get-NetAdapter).InterfaceIndex -ServerAddresses ('192.168.1.1', '8.8.8.8')
// Retrieves error events related to a specific application and sorts them by time
Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2; Provider Name='MyApp'} |
Sort-Object TimeCreated -Descending
// Modifies registry to enforce strong cryptography in .NET applications
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value 1
// Adjusts the visual effects for best performance
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects' -Name 'VisualFXSetting' -Value 2
// Adds a network printer and configures its port
Add-Printer -Name 'OfficePrinter' -DriverName 'HP Universal Printing PCL 6' -PortName 'IP_192.168.1.50'
Add-PrinterPort -Name 'IP_192.168.1.50' -PrinterHostAddress '192.168.1.50'
// Calls an API and parses the JSON response for specific data
$response = Invoke-RestMethod -Uri 'https://api.example.com/data'
$specificData = $response.data | Where-Object { $_.status -eq 'active' }
$specificData
// Installs all available Windows updates
Import-Module PSWindowsUpdate
Get-WindowsUpdate -AcceptAll -Install -AutoReboot
// Sets up a watcher on a folder to trigger actions on file changes
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\DataFolder'
$watcher.Filter = '*.txt'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
Register-ObjectEvent $watcher 'Changed' -Action {
Send-MailMessage -From 'server@example.com' -To 'admin@example.com' -Subject 'File Changed' -Body ('File changed: ' + $Event.SourceEventArgs.FullPath)
}
// Modifies user account settings to disable password expiration
Get-LocalUser -Name 'User1' | Set-LocalUser -PasswordNeverExpires $true
// Configures auditing policy for failed logon events
Auditpol /set /subcategory:'Logon' /failure:enable
// Script to monitor CPU and RAM usage and report via email if thresholds are exceeded
$cpu = Get-Counter '\Processor(_Total)\% Processor Time'.CounterSamples.CookedValue
$ram = Get-Counter '\Memory\Available MBytes'.CounterSamples.CookedValue
if ($cpu -gt 85 -or $ram -lt 300) {
$body = 'Alert: High CPU or low RAM on server.'
Send-MailMessage -From 'monitor@example.com' -To 'admin@example.com' -Subject 'Server Alert' -Body $body
}
// Backs up specified directories to a network share with logging
$source = 'C:\ImportantData'
$destination = '\\BackupServer\Share'
Copy-Item -Path $source -Destination $destination -Recurse -Verbose 4>&1 | Out-File 'C:\backup.log'
// Creates a system restore point
Checkpoint-Computer -Description 'PreUpgrade' -RestorePointType 'MODIFY_SETTINGS'
// Changes the system's power plan to high performance
$powerPlan = powercfg /list | Where-Object { $_ -like '*High performance*' }
$planGuid = $powerPlan -split '[()]' -like '*{*' | Out-String
powercfg /setactive $planGuid.Trim()
// Updates DNS records dynamically for a given IP and hostname
Add-DnsServerResourceRecordA -Name 'server01' -IPv4Address '192.168.1.101' -ZoneName 'example.com'
// Monitors log files and triggers alerts for specific patterns
$path = 'C:\Logs\*.*'
Get-Content $path -Tail 1 -Wait | Where-Object { $_ -match 'ERROR' } | ForEach-Object {
Write-Host 'Error found in log: ' $_
}
Events
List all event logs available on the system Display entries from the Application event log Query events based on specific event IDs Find error events across all logs Monitor and alert for specific events in real-time Export events to a CSV file for analysis Clear specific event logs. List event sources within a specific log Create a custom event log and source Write an event to a custom log Query event logs using XML filtering Remove an event source Retrieve events from remote computers Generate a report of specific events using custom formatting Track user logon and logoff activities Analyze system shutdown and restart events Monitor and alert for disk space issues Find application crash events Retrieve detailed information about service failures Automate daily event log reporting Script to archive and clear event logs monthly View events triggered by a specific user Display events related to USB device usage Script to monitor and report system performance issues
// Gets the most recent 10 entries from the Application log
Get-EventLog -LogName Application -Newest 10
// Retrieves events with ID 1000 from the System log
Get-EventLog -LogName System | Where-Object { $_.EventID -eq 1000 }
// Finds all error type events from all logs
Get-EventLog -LogName * | Where-Object { $_.EntryType -eq 'Error' }
// Sets up a watcher to monitor Application log for Error events and alerts
$query = '*[System[Level=2]]' // Level 2 is Error
$watcher = New-Object System.Diagnostics.Eventing.Reader.EventLogWatcher('Application', $query, $true)
Register-ObjectEvent $watcher 'EventRecordWritten' -Action {
Send-MailMessage -From 'server@example.com' -To 'admin@example.com' -Subject 'Error Event Detected' -Body ($Event.SourceEventArgs.EventRecord.FormatDescription())
}
// Exports security log events to a CSV file
Get-EventLog -LogName Security | Export-Csv 'C:\SecurityLog.csv'
// Lists all event sources from the Application log
Get-EventLog -LogName Application | Select-Object Source -Unique
// Creates a new event log 'CustomLog' with a new source 'CustomSource'
New-EventLog -LogName 'CustomLog' -Source 'CustomSource'
// Writes an informational event to the 'CustomLog'
Write-EventLog -LogName 'CustomLog' -Source 'CustomSource' -EntryType Information -EventID 1 -Message 'This is a test event.'
// Uses XML to query the Security log for audit failures
$xmlFilter = "<QueryList><Query Id='0' Path='Security'>
<Select Path='Security'>*[System[(EventID=4625)]]</Select>
</Query></QueryList>"
$events = Get-WinEvent -FilterXml $xmlFilter
$events
// Retrieves the Application log from a remote computer named 'Server01'
Get-EventLog -LogName Application -ComputerName 'Server01'
// Generates a report of Warning and Error events from the System log
$events = Get-EventLog -LogName System | Where-Object { $_.EntryType -match 'Warning|Error' }
$events | Format-Table TimeGenerated, Source, Message -AutoSize
// Tracks Event IDs 4624 (logon) and 4634 (logoff) from the Security log
Get-EventLog -LogName Security | Where-Object { $_.EventID -in 4624, 4634 } | Select-Object TimeGenerated, UserName, Message
// Analyzes shutdown (Event ID 1074) and restart events
Get-EventLog -LogName System | Where-Object { $_.EventID -eq 1074 }
Get-EventLog -LogName System | Where-Object { $_.EventID -in 1074, 1076 }
// Monitors for disk space related events and sends an alert if detected
$query = '*[System[Provider[@Name="disk"] and (EventID=11 or EventID=15)]]'
$watcher = New-Object System.Diagnostics.Eventing.Reader.EventLogWatcher('System', $query, $true)
Register-ObjectEvent $watcher 'EventRecordWritten' -Action {
Write-Host 'Disk issue detected: ' + $Event.SourceEventArgs.EventRecord.FormatDescription()
}
// Finds all application crash events (Event ID 1000) in the Application log
Get-EventLog -LogName Application | Where-Object { $_.EventID -eq 1000 }
// Retrieves events related to service failures
Get-WinEvent -FilterHashtable @{LogName='System'; ID=7031} | Select-Object TimeCreated, Message
// Automates the generation of a daily report of critical events
$yesterday = (Get-Date).AddDays(-1)
$events = Get-EventLog -LogName System -After $yesterday | Where-Object { $_.EntryType -eq 'Error' }
$report = $events | Format-Table TimeGenerated, Source, EventID, Message -AutoSize
$report | Out-File 'C:\DailyEventReport.txt'
// Archives and clears event logs monthly
$logs = Get-EventLog -List | Where-Object {$_.Entries.Count -gt 0}
foreach ($log in $logs) {
$fileName = 'C:\Logs\'+$log.Log+'_'+(Get-Date -Format 'yyyyMMdd')+'.evtx'
Export-EventLog -LogName $log.Log -Path $fileName
Clear-EventLog -LogName $log.Log
}
// Views all events triggered by the user 'JohnDoe'
Get-EventLog -LogName Security | Where-Object { $_.ReplacementStrings -contains 'JohnDoe' } | Select-Object TimeGenerated, EventID, Message
User Activity Event IDs: This group includes events related to user logon actions, session start, and terminations Security Incident Event IDs: Includes events that are critical for security auditing, such as unauthorized access and system changes Application Failure Event IDs: These events help in diagnosing application-related issues and failures System Performance and Reliability Event IDs: Includes events that are vital for monitoring system performance and stability issues Network Events and Activity Event IDs: Focuses on network-related events and security Directory Service Access and Replication Event IDs: Essential for monitoring Active Directory and replication services
4624 = 'An account was successfully logged on';
4625 = 'An account failed to log on';
4634 = 'An account was logged off';
4647 = 'User initiated logoff';
4672 = 'Special privileges assigned to new logon';
4800 = 'The workstation was locked';
4801 = 'The workstation was unlocked';
4802 = 'The screen saver was invoked';
4803 = 'The screen saver was dismissed';
1102 = 'The audit log was cleared';
4625 = 'An account failed to log on';
4648 = 'A logon was attempted using explicit credentials';
4720 = 'A user account was created';
4728 = 'A member was added to a security-enabled global group';
4732 = 'A member was added to a security-enabled local group';
4756 = 'A member was added to a security-enabled universal group';
4767 = 'A user account was unlocked';
4771 = 'Kerberos pre-authentication failed';
4776 = 'The computer attempted to validate the credentials for an account';
1000 = 'Application Error';
1001 = 'Application Hang';
1002 = 'Application Hang';
1026 = '.NET Runtime Error';
1033 = 'Application Crash';
11707 = 'Installation Completed Successfully';
11708 = 'Installation operation failed';
41 = 'System has rebooted without cleanly shutting down first';
100 = 'Windows is not performing optimally';
200 = 'System performance has degraded';
6008 = 'The previous system shutdown was unexpected';
6013 = 'System uptime';
Systems Administration, File Management, & Monitoring
Check the system uptime List all users on the system List all groups on the system Add a new local user Add a user to a group Remove a local user Disable a local user account Change a user's password Disable an AD user account Lookup AD users Enable Remote Desktop on the system Restart a service List all running services List services that start automatically but are currently stopped Create a new Scheduled Task Update all help files for PowerShell cmdlets Export a list of all installed programs to a CSV file Check disk space usage List all network adapters and their status Flush the DNS resolver cache Display all listening ports Get detailed system information including hardware and OS details Back up the registry Restore a registry from backup Monitor real-time CPU usage Check the status of a specific process Kill a process by ID Configure IP address on an adapter View all firewall rules Enable a firewall rule Backup all firewall rules to a file Restore firewall rules from a backup file Map a network drive Unmap a network drive
$password = ConvertTo-SecureString 'NewPassword123!' -AsPlainText -Force
Set-LocalUser -Name 'User1' -Password $password
# Match all three explicitly
Get-ADUser -Filter "SamAccountName -in ('testuser1','testuser2','testuser3')" |
Select-Object SamAccountName, Name
# Match users with SamAccountName containing 'testuser'
Get-ADUser -Filter "SamAccountName -like '*testuser*'" -Properties SamAccountName |
Select-Object SamAccountName, Name
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Value 0
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-NoProfile -WindowStyle Hidden -Command "& {Get-Process}"'
$trigger = New-ScheduledTaskTrigger -At 3am -Daily
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName 'DailyProcessCheck' -Description 'Checks running processes daily at 3 AM'
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher | Export-Csv -Path 'C:\InstalledPrograms.csv' -NoTypeInformation
Create a new text file Write text to a file Read text from a file Copy a file to another directory Move a file to another directory Delete a file Rename a file List all files in a directory List all files in a directory with a specific extension Find all files larger than 1MB in a directory Change the attributes of a file to read-only Create a zip file from a folder Extract a zip file Encrypt a file using Windows EFS Decrypt a file using Windows EFS Create a hard link to a file Create a symbolic link to a directory Monitor a directory for changes in real-time Retrieve file ownership information Change file ownership to a different user Set detailed file permissions for a user Batch change file extensions within a folder Calculate the total size of all files in a directory Find and delete temporary files older than 30 days Display detailed security descriptors for a file, including DACLs Automatically clean up old log files from a directory Generate a checksum for file integrity verification Search for files containing a specific string Restore a deleted file from shadow copy Automatically back up files when they are modified
Copy-Item -Path 'C:\Users\Public\Documents\example.txt' -Destination 'C:\Users\Public\Documents\Backup\'
Move-Item -Path 'C:\Users\Public\Documents\example.txt' -Destination 'C:\Users\Public\Documents\NewFolder\'
Compress-Archive -Path 'C:\Users\Public\Documents\Folder' -DestinationPath 'C:\Users\Public\Documents\Archive.zip'
Expand-Archive -Path 'C:\Users\Public\Documents\Archive.zip' -DestinationPath 'C:\Users\Public\Documents\Extracted'
New-Item -ItemType HardLink -Path 'C:\Users\Public\Documents\LinkToFile.txt' -Value 'C:\Users\Public\Documents\example.txt'
New-Item -ItemType SymbolicLink -Path 'C:\Users\Public\Documents\LinkToFolder' -Value 'C:\Users\Public\Documents\Folder'
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\Users\Public\Documents'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
Register-ObjectEvent $watcher 'Changed' -Action { Write-Host 'File changed: ' + $Event.SourceEventArgs.FullPath }
$acl = Get-Acl -Path 'C:\Users\Public\Documents\example.txt'
$newOwner = New-Object System.Security.Principal.NTAccount('DOMAIN', 'Username')
$acl.SetOwner($newOwner)
Set-Acl -Path 'C:\Users\Public\Documents\example.txt' -AclObject $acl
$acl = Get-Acl -Path 'C:\Users\Public\Documents\example.txt'
$permission = 'DOMAIN\User','FullControl','Allow'
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($permission)
$acl.SetAccessRule($accessRule)
Set-Acl -Path 'C:\Users\Public\Documents\example.txt' -AclObject $acl
Get-ChildItem -Path 'C:\Users\Public\Documents\' -Filter '*.txt' | Rename-Item -NewName { $_.Name -replace '.txt','.log' }
(Get-ChildItem -Path 'C:\Users\Public\Documents\' -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB
Get-ChildItem -Path 'C:\Windows\Temp\' -File | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-30) } | Remove-Item
$files = Get-ChildItem -Path 'C:\Logs' -Filter '*.log' | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-90) }
$files | Remove-Item
$shadow = Get-WmiObject Win32_ShadowCopy | Select-Object -First 1
Copy-Item -Path ($shadow.DeviceObject + '\Users\Public\Documents\example.txt') -Destination 'C:\Users\Public\Documents\RestoredExample.txt'
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\Users\Public\Documents'
$watcher.Filter = '*.txt'
$watcher.NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
$watcher.EnableRaisingEvents = $true
Register-ObjectEvent $watcher 'Changed' -Action {
$path = $Event.SourceEventArgs.FullPath
$backupPath = 'C:\Backup' + $path.Substring(2)
Copy-Item -Path $path -Destination $backupPath
Write-Host ('Backup of ' + $path + ' was created.')
}
Get basic system information View all currently running processes Monitor CPU utilization Check available disk space on all drives List all network adapters and their configuration Monitor network traffic statistics List all users and their last logon time Get event logs for system errors Retrieve services that failed to start Display system boot time View all scheduled tasks Check for any accounts with password expiry disabled Monitor changes to files in a specified directory List all installed applications Check system performance counters for memory usage Retrieve BIOS information List all active network connections Export firewall rules to a file View detailed logon events from the security log Monitor USB device connections Check for system time changes Retrieve details about the current power plan Log performance data to a file every minute Analyze disk usage by folder Generate a report of open files on the system Identify orphaned files and folders without a valid owner Find processes with high memory usage Track and log system reboots and shutdowns Monitor Windows Update installation events
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\Path\To\Directory'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
Register-ObjectEvent $watcher 'Changed' -Action { Write-Host ('File changed: ' + $Event.SourceEventArgs.FullPath) }
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion
Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4624]]"
Get-EventLog -LogName Security | Where-Object { $_.EventID -in 4624, 4625 }
Get-WinEvent -LogName Microsoft-Windows-DriverFrameworks-UserMode/Operational | Where-Object { $_.Id -in 2003, 2100 }
while ($true) {
Get-Counter '\Processor(_Total)\% Processor Time' | Out-File -Append -FilePath 'C:\PerfLogs\CpuUtil.log'
Start-Sleep -Seconds 60
}
Get-ChildItem -Path 'C:\Users\' -Recurse | Group-Object -Property Directory | Select-Object Name, @{Name='Files'; Expression={$_.Group | Measure-Object -Sum Length}}
User, Group, & File Management
Creating a new user account (GUI) Deleting a user account (GUI) Modifying user account properties (GUI) PowerShell examples for user management Resetting a user password (GUI) Enabling or disabling a user account (PowerShell) Auditing user account activities (GUI) Configuring Account Lockout Policy (PowerShell) Exporting and Importing User Accounts (PowerShell) Restricting user logon hours (PowerShell)
1. Open Control Panel by searching for it in the Start menu.
2. Navigate to User Accounts > Manage Accounts > Add a new user in PC settings.
3. Follow the prompts to set up a new account, choosing between a Microsoft or a local account.
4. Fill out the form with the user's information and click 'Finish' to create the account.
1. Open Control Panel and go to User Accounts > Manage Accounts.
2. Select the account you wish to delete.
3. Click 'Delete the account'.
4. Choose whether to keep or delete the user's files and confirm the deletion.
1. Access the Control Panel and open User Accounts > Manage Accounts.
2. Click on the user account you want to modify.
3. Select 'Change the account type' to switch between Standard and Administrator.
4. You can also choose 'Change the password' or manage other settings like user credentials.
// Using PowerShell to create a user account
New-LocalUser -Name "User1" -Description "Standard user account for User1" -NoPassword
// Using PowerShell to delete a user account
Remove-LocalUser -Name "User1"
// Changing a user's account type to Administrator
Add-LocalGroupMember -Group "Administrators" -Member "User1"
// Resetting a user's password
$Password = ConvertTo-SecureString "NewPassword123" -AsPlainText -Force
Set-LocalUser -Name "User1" -Password $Password
1. Navigate to Control Panel > User Accounts > Manage Accounts.
2. Select the user whose password needs to be reset.
3. Click 'Change the password'.
4. Enter the new password, confirm it, and then finalize by clicking 'Change password'.
// Disabling a user account
Disable-LocalUser -Name "User2"
// Enabling a user account
Enable-LocalUser -Name "User2"
1. Open Local Security Policy by searching for it in the Start menu.
2. Navigate to Local Policies > Audit Policy.
3. Double-click on 'Audit account logon events' and 'Audit logon events'.
4. Configure each policy by checking 'Success' and 'Failure' to enable comprehensive auditing.
5. Apply the changes and exit the Local Security Policy window.
// Viewing current Account Lockout Policy settings
Get-LocalSecurityPolicy -Policy "Account lockout duration", "Account lockout threshold"
// Setting the Account Lockout Threshold to 5 invalid logon attempts
Set-LocalSecurityPolicy -Policy "Account lockout threshold" -Value "5"
// Setting the Account Lockout Duration to 30 minutes
Set-LocalSecurityPolicy -Policy "Account lockout duration" -Value "30"
Creating a new group (GUI) Managing user groups (GUI) Adding users to a group (GUI) PowerShell examples for group management Managing group policies (GUI) Managing group memberships (PowerShell) Managing group properties (GUI) Removing a group (GUI) PowerShell examples for advanced group management Managing group policy assignments (GUI) Assigning Group Permissions (GUI) Group Policy Object (GPO) Creation and Management (GUI) Setting Group Quotas (GUI) Automating Group Membership Updates (PowerShell) Configuring Group Membership Expiration (PowerShell)
1. Open Computer Management by searching for it in the Start menu.
2. Navigate to Local Users and Groups > Groups.
3. Right-click on an empty area and select 'New Group'.
4. Fill out the group name and description, then click 'Create'.
1. Open the Computer Management tool by typing "Computer Management" in the Start menu and selecting it.
2. In the left pane, expand 'Local Users and Groups' and select 'Groups'.
3. Right-click 'Groups' and choose 'New Group...' to create a new user group.
4. Enter the name and description for the group, then add members by clicking 'Add...' and selecting the users.
5. Click 'Create' to finalize the group creation.
1. Open Computer Management and go to Local Users and Groups > Groups.
2. Double-click on the group you want to modify.
3. Click 'Add' and enter the name of the user you want to add to the group.
4. Click 'Check Names' to verify the user, then click 'OK' to add them.
// Creating a new group
New-LocalGroup -Name "Group1" -Description "New group for specific users"
// Adding a user to a group
Add-LocalGroupMember -Group "Group1" -Member "User1"
// Removing a user from a group
Remove-LocalGroupMember -Group "Group1" -Member "User1"
1. Open Local Group Policy Editor by searching for it in the Start menu.
2. Navigate to Computer Configuration > Windows Settings > Security Settings > Local Policies.
3. Here you can configure various group policies related to user rights, security options, and more.
// Listing all members of a group
Get-LocalGroupMember -Group "Administrators"
// Listing all groups a user is a member of
Get-LocalGroup -Member "User1"
1. Open Computer Management.
2. Navigate to 'Local Users and Groups' > 'Groups'.
3. Right-click the group whose properties you want to manage and select 'Properties'.
4. In the properties dialog, you can change the group description and manage its members.
1. Open Computer Management.
2. Navigate to 'Local Users and Groups' > 'Groups'.
3. Right-click the group you wish to delete and select 'Delete'.
4. Confirm the deletion when prompted to remove the group permanently.
// Modifying a group description
Set-LocalGroup -Name "Group1" -Description "Updated description for Group1"
// Deleting a group
Remove-LocalGroup -Name "Group1"
1. Press Win + R, type 'gpedit.msc', and press Enter to open Group Policy Editor.
2. Navigate to 'User Configuration' or 'Computer Configuration'.
3. Drill down to the settings you want to configure for groups.
4. Double-click a setting to modify its properties, apply it to specific groups using the 'Security Filtering' section.
1. Open Computer Management by searching for it in the Start menu.
2. Navigate to Local Users and Groups > Groups.
3. Right-click on the group you wish to modify and select 'Properties'.
4. Go to the 'Group Policy' tab, click 'Add' to assign new permissions or modify existing ones.
5. Select the permissions you want to assign and apply the changes.
1. Press Win + R, type 'gpmc.msc', and press Enter to open the Group Policy Management Console.
2. Right-click on the domain or organizational unit where you want to create a GPO and select 'Create a GPO in this domain, and Link it here'.
3. Enter a name for the new GPO and click 'OK'.
4. Right-click on the newly created GPO and select 'Edit' to configure its policies.
5. Navigate through the policy settings to configure as needed and apply the changes.
1. Open File Explorer and navigate to the drive or folder where you want to set quotas.
2. Right-click on the drive/folder, select 'Properties', then go to the 'Quota' tab.
3. Click 'Show Quota Settings', then 'Enable quota management'.
4. Set the disk space limits for the group and specify warning levels.
5. Apply the settings to manage disk usage by the group.
// Automatically adding users to a group based on criteria
Get-LocalUser | Where-Object { $_.Description -like "*criteria*" } | ForEach-Object { Add-LocalGroupMember -Group "Group1" -Member $_.Name }
// Automatically removing users from a group based on criteria
Get-LocalUser | Where-Object { $_.Description -notlike "*criteria*" } | ForEach-Object { Remove-LocalGroupMember -Group "Group1" -Member $_.Name }
Creating and managing folders (GUI) Searching for files and folders (GUI) Setting file attributes (GUI) PowerShell examples for file management Managing file permissions (GUI) File compression and decompression (GUI) Advanced File Searching (GUI) File Version History Management (GUI) Restoring Default File Associations (GUI) Automating File Backup (PowerShell) Batch File Renaming (PowerShell)
1. Open File Explorer.
2. Navigate to the location where you want to create a new folder.
3. Right-click in the empty space, select 'New' > 'Folder'.
4. Enter the name for the folder and press Enter.
1. Open File Explorer.
2. Use the search box in the upper right corner to type the name of the file or folder you're searching for.
3. Press Enter to display the search results.
1. Right-click on a file or folder and select 'Properties'.
2. In the 'Attributes' section, you can set attributes such as 'Read-only' or 'Hidden'.
3. Click 'Apply' and then 'OK' to save the changes.
// Creating a new folder
New-Item -Path 'C:\NewFolder' -ItemType Directory
// Changing file attributes to read-only
Set-ItemProperty -Path 'C:\NewFolder\file.txt' -Name IsReadOnly -Value $true
1. Right-click on a file or folder and select 'Properties'.
2. Go to the 'Security' tab.
3. Click 'Edit' to modify the permissions or 'Add' to grant new user or group permissions.
4. Configure the permissions and click 'OK' to apply.
1. To compress a file, right-click it and select 'Send to' > 'Compressed (zipped) folder'.
2. To decompress, right-click the compressed folder and select 'Extract All...', then follow the prompts.
1. Open File Explorer.
2. In the search box, type advanced search operators like 'size:>10MB' to find files larger than 10 MB.
3. You can also use 'date:>=01/01/2022' to find files modified after January 1, 2022.
4. Press Enter and review the filtered search results.
1. Right-click on the file for which you want to manage versions and select 'Restore previous versions'.
2. A list of available file versions will appear. You can open, copy, or restore these as needed.
3. Select the version you want to restore and click 'Restore' to replace the current version with the selected one.
1. Open Settings by pressing Win + I.
2. Navigate to Apps > Default apps.
3. Scroll down and click 'Reset' under 'Reset to the Microsoft recommended defaults'.
4. This will restore all file type associations to their default settings.
System Maintenance & Monitoring
Viewing disk partitions (GUI) Formatting a drive (GUI) Creating and managing virtual hard disks (VHD) (GUI) PowerShell examples for disk management Implementing Disk Quotas (GUI) Resizing a Partition (GUI) Checking Disk Health and Errors (GUI) Automating Disk Cleanup (PowerShell) Monitoring Disk Performance (PowerShell) Converting a Disk from MBR to GPT (GUI) Recovering Lost Partitions (GUI)
1. Press Win + X and select 'Disk Management'.
2. The Disk Management window shows all connected disks and their partitions.
3. Right-click a partition to view properties or to perform tasks like shrink, extend, or change drive letters.
1. Open Disk Management.
2. Right-click on the drive or partition you want to format.
3. Select 'Format' from the context menu.
4. Choose the file system and allocation unit size, then proceed by clicking 'OK'.
5. Confirm the operation, understanding that this will erase all data on the drive.
1. In Disk Management, go to the 'Action' menu and select 'Create VHD'.
2. Set the location, size, and format for the VHD, then click 'OK' to create.
3. Once created, initialize and format the VHD as you would with a physical disk.
// Creating a new VHD
New-VHD -Path "C:\VHDs\MyDisk.vhdx" -SizeBytes 20GB -Dynamic
// Initializing a disk in PowerShell
Initialize-Disk -Number 2 -PartitionStyle GPT
// Creating a new partition
New-Partition -DiskNumber 2 -UseMaximumSize -AssignDriveLetter
1. Open File Explorer and right-click on the drive you want to manage.
2. Select 'Properties' and navigate to the 'Quota' tab.
3. Click 'Show Quota Settings' and then 'Enable quota management'.
4. Set the disk space limit and warning level for users and apply the settings.
1. Open Disk Management by pressing Win + X and selecting 'Disk Management'.
2. Right-click on the partition you wish to resize and select 'Shrink Volume...' to reduce its size, or 'Extend Volume...' to increase its size.
3. Enter the amount to shrink or extend the partition and click 'Shrink' or 'Next' to proceed.
4. Follow the prompts to complete the resizing.
1. Open 'This PC' in File Explorer, right-click the drive you want to check, and select 'Properties'.
2. Go to the 'Tools' tab and click on 'Check' under the Error checking section.
3. If the tool finds any errors, follow the prompts to repair them.
// Displaying disk read/write statistics
Get-Counter -Counter "\LogicalDisk(C:)\Disk Reads/sec", "\LogicalDisk(C:)\Disk Writes/sec"
1. Back up all data on the disk as this process will erase all contents.
2. Open Disk Management, right-click the disk and select 'Convert to GPT Disk'.
3. Confirm the operation to convert the disk format.
1. Open Disk Management.
2. Look for a disk marked as 'Unknown' or 'Not Initialized'.
3. Right-click on the disk and choose 'Initialize Disk' or 'Online' if it’s offline.
4. If a lost partition appears as unallocated space, right-click it and select 'New Simple Volume...' to begin the recovery process.
Viewing and analyzing event logs (GUI) Clearing event logs (GUI) Creating and managing custom views (GUI) PowerShell examples for event log management Monitoring real-time events (PowerShell) Automating log analysis (PowerShell) Configuring log properties (GUI) Setting up event subscriptions (GUI) Detecting Failed Logon Attempts (PowerShell) Automating Alerts for Suspicious Activities (PowerShell) Monitoring for Unusual Application Installations (PowerShell) Correlating Logon Events with Network Activity (PowerShell) Setting up Continuous Monitoring and Reporting (PowerShell)
1. Press Win + R, type 'eventvwr.msc', and press Enter.
2. Navigate through the log categories to view application, security, system, or other logs.
3. Use the 'Filter Current Log...' option on the right to filter logs based on criteria such as event level, keywords, or date.
1. In Event Viewer, right-click on a log (e.g., Application, System) and select 'Clear Log...'.
2. You can either clear the log directly or save and clear the log where it prompts.
1. In Event Viewer, right-click on 'Custom Views' and select 'Create Custom View...'.
2. Specify filters and conditions to create a view that focuses on specific events of interest.
3. Name and save the view for quick access in the future.
// Exporting an event log
Get-EventLog -LogName Application -Newest 50 | Export-Csv -Path 'C:\eventlog.csv'
// Clearing an event log using PowerShell
Clear-EventLog -LogName Application
// Using PowerShell to monitor real-time events
Get-WinEvent -LogName System -MaxEvents 100 | Where-Object { $_.LevelDisplayName -eq 'Error' }
// Automatically analyze logs for specific events
Get-EventLog -LogName System | Where-Object { $_.EntryType -eq 'Error' } | Export-Csv -Path 'C:\system_errors.csv'
1. Open Event Viewer and right-click on any log under 'Windows Logs'.
2. Select 'Properties' to open the log properties window.
3. Adjust settings such as maximum log size and when to overwrite old events.
4. Apply changes and close the properties window.
1. In Event Viewer, expand 'Subscriptions' and right-click 'Create Subscription...'.
2. Follow the wizard to specify the events to collect, the event source computers, and the destination log.
3. Adjust advanced settings such as the delivery optimization and event data to include.
4. Name the subscription and finish setup to start receiving events from other computers.
// PowerShell script to detect failed logon attempts and export the details
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625} | Select-Object TimeCreated, Message | Export-Csv -Path 'C:\failed_logons.csv'
// Script to monitor specific security events and send an email alert
$events = Get-EventLog -LogName Security -Newest 50 | Where-Object {$_.EventID -eq 4673 -or $_.EventID -eq 4688}
if ($events) {
Send-MailMessage -From 'security@company.com' -To 'alert@company.com' -Subject 'Suspicious Activity Detected' -Body 'Please review the attached events.' -Attachments 'C:\events.csv' -SmtpServer 'smtp.company.com'
}
// Tracking installation of new applications via event logs
Get-WinEvent -FilterHashtable @{LogName='Application'; ID=11707} | Where-Object { $_.Message -match 'Installed: Application Name' } | Select-Object TimeCreated, Message
// Correlating logon events with subsequent network activity from the same user
$logons = Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4624}
$networkEvents = Get-WinEvent -FilterHashtable @{LogName='Security'; ID=5156}
$logons | ForEach-Object {
$logonTime = $_.TimeCreated
$logonUser = $_.Properties[5].Value
$relatedNetworkActivity = $networkEvents | Where-Object { $_.Properties[1].Value -eq $logonUser -and $_.TimeCreated -gt $logonTime }
[PSCustomObject]@{
User = $logonUser
LogonTime = $logonTime
RelatedActivity = $relatedNetworkActivity
}
}
// Configuring a scheduled task to monitor critical event logs and generate reports
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-File "C:\Scripts\LogMonitor.ps1"'
$Trigger = New-ScheduledTaskTrigger -AtLogon
$Principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -Action $Action -Trigger $Trigger -Principal $Principal -TaskName "Log Monitoring Task" -Description "Monitors critical event logs and generates security reports"
Using Task Manager for performance monitoring (GUI) Using Performance Monitor to track detailed system metrics (GUI) PowerShell commands for performance monitoring Advanced real-time performance analysis (PowerShell) Detecting high CPU utilization processes (PowerShell) Analyzing network bandwidth usage (PowerShell) Monitoring disk response times (PowerShell) Setting up alerts for performance thresholds (PowerShell)
1. Press Ctrl + Shift + Esc to open Task Manager.
2. Click the 'Performance' tab to view CPU, memory, disk, and network usage.
3. For more details, click on 'Open Resource Monitor' at the bottom.
1. Press Win + R, type 'perfmon.msc', and press Enter.
2. Expand 'Monitoring Tools' and click on 'Performance Monitor'.
3. Click 'Add' to select and add counters like CPU, Disk, Network, Memory for detailed monitoring.
// Listing system performance information
Get-Counter -Counter "\Processor(_Total)\% Processor Time", "\Memory\Available MBytes"
// Capturing performance data over time
Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 10
// Monitoring system latency and process thread details
Get-Counter -Counter "\System\Context Switches/sec", "\Process(_Total)\Thread Count" -SampleInterval 1 -MaxSamples 30
// Identifying processes that are consuming more than 80% CPU
Get-WmiObject Win32_PerfFormattedData_PerfProc_Process | Where-Object { $_.PercentProcessorTime -gt 80 } | Select-Object Name, IDProcess, PercentProcessorTime
// Displaying current network bandwidth usage by process
Get-NetAdapterStatistics | Select-Object Name, ReceivedBytes, SentBytes
// Checking average disk queue length to gauge disk performance issues
Get-Counter "\PhysicalDisk(_Total)\Avg. Disk Queue Length" -Continuous
// Setting up a task to alert when memory usage exceeds a certain threshold
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-File "C:\Scripts\AlertHighMemory.ps1"'
$Trigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "High Memory Alert"
Managing Windows services through Services app (GUI) PowerShell examples for managing services Monitoring service status changes (PowerShell) Automatically restarting critical services (PowerShell) Configuring service dependencies (GUI) Enforcing service security policies (PowerShell) Implementing service monitoring and alerting (PowerShell)
1. Press Win + R, type 'services.msc', and press Enter.
2. Scroll through the list to find the service you want to manage.
3. Right-click the service and choose 'Start', 'Stop', 'Pause', 'Resume', or 'Restart'.
4. For further configurations, select 'Properties' and adjust settings like startup type or logon details.
// Starting a service
Start-Service -Name "wuauserv"
// Stopping a service
Stop-Service -Name "wuauserv"
// Changing service startup type
Set-Service -Name "wuauserv" -StartupType Disabled
// Script to log any changes in service status
Register-WmiEvent -Query "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_Service' AND TargetInstance.State != PreviousInstance.State" -Action {
$service = $Event.SourceEventArgs.NewEvent.TargetInstance
Add-Content -Path "C:\ServiceLogs.txt" -Value "Service $service.Name changed status from $($service.PreviousInstance.State) to $($service.State) at $(Get-Date)"
}
// Script to monitor and restart a service if it stops
$serviceName = 'wuauserv'
$service = Get-Service -Name $serviceName
if ($service.Status -ne 'Running') {
Start-Service -Name $serviceName
Write-Host "$serviceName service was restarted."
}
1. Open Services by pressing Win + R, typing 'services.msc', and pressing Enter.
2. Right-click on the service you want to configure and select 'Properties'.
3. Go to the 'Dependencies' tab to view or change which services start before your service.
4. Use this information to ensure proper service startup order and resolve dependency issues.
// Script to modify the logon user of a service and set its permissions
$serviceName = 'wuauserv'
Set-Service -Name $serviceName -Credential (Get-Credential)
$acl = Get-Acl -Path "HKLM:\System\CurrentControlSet\Services\$serviceName"
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ("Domain\User", "FullControl", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path "HKLM:\System\CurrentControlSet\Services\$serviceName" -AclObject $acl
// Script to monitor services and send email alerts on failure
$servicesToMonitor = @("wuauserv", "bits")
foreach ($service in $servicesToMonitor) {
$status = Get-Service -Name $service
if ($status.Status -ne 'Running') {
Send-MailMessage -From "admin@example.com" -To "alerts@example.com" -Subject "$service is not running" -Body "The $service service has stopped on $(hostname). Please check immediately."
}
}
Creating and managing scheduled tasks (GUI) PowerShell commands for scheduled tasks Configuring task triggers and actions (PowerShell) Clearing temporary files with a scheduled task (PowerShell) Monitoring system uptime and logging to a file (PowerShell) Automating critical file backups (PowerShell) Setting up event log monitoring and alerts (PowerShell)
1. Press Win + R, type 'taskschd.msc', and press Enter.
2. In the Task Scheduler Library, click 'Create Basic Task...' to start the wizard.
3. Follow the wizard to define the task's trigger, action, and other properties.
4. For more advanced options, use 'Create Task...' to access additional configurations like conditions and settings.
// Creating a new scheduled task
$action = New-ScheduledTaskAction -Execute 'Notepad.exe'
$trigger = New-ScheduledTaskTrigger -AtLogon
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "OpenNotepadAtLogon"
// Retrieving scheduled tasks
Get-ScheduledTask | Where-Object {$_.State -eq 'Ready'}
// Creating a scheduled task to scan for malware
$malwareScanAction = New-ScheduledTaskAction -Execute 'C:\Program Files\MalwareScanner\scanner.exe' -Argument '-scan -auto'
$malwareScanTrigger = New-ScheduledTaskTrigger -Daily -At 03:00AM
Register-ScheduledTask -Action $malwareScanAction -Trigger $malwareScanTrigger -TaskName "DailyMalwareScan"
// Setting up a task to clear temporary files every week
$tempCleanAction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-Command "Remove-Item C:\Temp\* -Recurse -Force"'
$tempCleanTrigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 02:00AM
Register-ScheduledTask -Action $tempCleanAction -Trigger $tempCleanTrigger -TaskName "WeeklyTempCleanup"
// Monitoring system uptime and logging to a file
$uptimeAction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-Command "Get-Uptime | Out-File C:\Logs\Uptime.log -Append"'
$uptimeTrigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -Action $uptimeAction -Trigger $uptimeTrigger -TaskName "LogSystemUptime"
// Backing up critical files to a network location daily
$backupAction = New-ScheduledTaskAction -Execute 'Robocopy.exe' -Argument 'C:\CriticalFiles \\NetworkLocation\Backup /MIR'
$backupTrigger = New-ScheduledTaskTrigger -Daily -At 01:00AM
Register-ScheduledTask -Action $backupAction -Trigger $backupTrigger -TaskName "DailyNetworkBackup"
// Monitoring event logs for specific critical events and alerting via email
$eventAlertAction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-Command "Get-WinEvent -FilterHashtable @{LogName=\'Security\'; ID=4625} | Send-MailMessage -From alert@example.com -To admin@example.com -Subject \'Critical Security Event Detected\' -Body \'A critical security event has occurred.\'"'
$eventAlertTrigger = New-ScheduledTaskTrigger -AtLogon
Register-ScheduledTask -Action $eventAlertAction -Trigger $eventAlertTrigger -TaskName "SecurityEventAlert"
Introduction to Backup and Recovery Creating system restore points (GUI) Using Windows Backup to create backups (GUI) PowerShell commands for backup operations (PowerShell) Automating system restore point creation (PowerShell) Incremental backup using PowerShell Recovering data from system restore points (GUI) Restoring files from Windows Backup (GUI) Backup to network location with encryption (PowerShell) Scheduled cleanup of old backups (PowerShell) System image creation for disaster recovery (GUI)
Backup and Recovery tools in Windows help ensure your data is safe from hardware failures, malware attacks, and accidental deletions.
1. Press Win + R, type 'SystemPropertiesProtection', and press Enter.
2. In the System Properties window, click 'Create' under the System Protection tab.
3. Name the restore point and click 'Create' to start the process.
1. Open Control Panel, go to 'System and Security' > 'Backup and Restore (Windows 7)'.
2. Click on 'Set up backup' and follow the wizard to select backup destination and the files or directories you want to backup.
3. Schedule the backup frequency according to your needs.
// Creating a backup using wbAdmin
wbAdmin start backup -backupTarget:E: -include:C: -allCritical -quiet
// Automatically creating a system restore point daily
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-Command "Checkpoint-Computer -Description \'Daily Restore Point\' -RestorePointType \'MODIFY_SETTINGS\'"'
$Trigger = New-ScheduledTaskTrigger -Daily -At '3AM'
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "DailySystemRestorePoint"
// Creating incremental backups of critical directories
$source = "C:\ImportantData"
$destination = "D:\Backup\ImportantData"
$timestamp = Get-Date -Format 'yyyyMMddHHmm'
robocopy $source $destination /mir /zb /eta /log:"D:\Backup\Logs\$timestamp.txt"
1. Navigate to 'Control Panel' > 'System' > 'System Protection'.
2. Click 'System Restore...' and follow the prompts to choose a restore point.
3. Select the restore point that corresponds to a date before the issue occurred and proceed with the restoration.
1. Open Control Panel and go to 'System and Security' > 'Backup and Restore (Windows 7)'.
2. Click 'Restore my files' and follow the wizard to select the files or directories you want to restore.
3. Choose the location to restore the files to and complete the restoration process.
// Backing up to a network location with AES 256-bit encryption
$backupPath = "\\NetworkShare\Backups"
$credential = Get-Credential -Message "Enter Credentials for Network Share"
$secureBackup = @{
Path = $backupPath
Credential = $credential
EncryptionAlgorithm = "AES256"
}
Backup-WindowsImage -Create -Destination $secureBackup.Path -User $secureBackup.Credential -EncryptionAlgorithm $secureBackup.EncryptionAlgorithm
// Schedule a monthly task to delete backups older than 90 days
$Action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c "Del /S /Q D:\Backup\*.*"'
$Trigger = New-ScheduledTaskTrigger -Monthly -DaysOfMonth 1 -At '4AM'
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "CleanupOldBackups"
1. Press Win + R, type 'sdclt.exe', and press Enter to open Backup and Restore (Windows 7).
2. Click on 'Create a system image' on the left panel.
3. Choose the backup location, select the drives to include in the backup, and start the backup process.
4. This creates a full system image that can be used to restore the entire system in case of a failure.
Security & Access Controls
Introduction to Windows Firewall Configuring Windows Firewall settings (GUI) PowerShell examples for firewall management Managing firewall profiles (GUI) Configuring firewall logging (GUI) PowerShell commands for firewall logging Automatically blocking high-risk ports Enabling logging of dropped packets Configuring firewall rules for specific applications
Windows Firewall helps protect your computer by preventing unauthorized users from gaining access to your computer through the Internet or a network.
1. Open Control Panel, select 'System and Security', then 'Windows Defender Firewall'.
2. Click on 'Allow an app or feature through Windows Defender Firewall' to modify settings for specific applications.
3. Use 'Advanced settings' to create inbound and outbound rules for finer control over network traffic.
// Creating a new inbound rule to allow TCP traffic on port 80
New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
// Disabling a firewall rule
Set-NetFirewallRule -DisplayName "Allow HTTP" -Enabled False
1. Open Windows Defender Firewall settings in Control Panel.
2. Click on 'Advanced settings' to access the Windows Defender Firewall with Advanced Security console.
3. Configure settings for domain, private, and public profiles to control network traffic based on location.
1. In the Windows Defender Firewall with Advanced Security console, right-click on 'Windows Defender Firewall with Advanced Security' and select 'Properties'.
2. Go to the 'Domain Profile', 'Private Profile', or 'Public Profile' tab to enable logging and adjust log settings.
3. Choose log file location, size limits, and whether to log successful connections.
// Enabling firewall logging for dropped packets
Set-NetFirewallProfile -Profile Domain,Public,Private -LogBlocked True
// Checking firewall log settings
Get-NetFirewallProfile | Select-Object Name, LogBlocked
// Automatically blocks incoming connections on high-risk ports such as Telnet.
New-NetFirewallRule -DisplayName "Block Telnet" -Direction Inbound -Protocol TCP -LocalPort 23 -Action Block
Introduction to Windows Registry Editing the registry (GUI) PowerShell commands for registry tasks (PowerShell) Enforcing a desktop wallpaper via the registry (PowerShell) Disabling USB storage to enhance security (PowerShell)
The Windows Registry is a database that stores low-level settings for the operating system and for applications that opt to use the registry. Handle with care.
1. Press Win + R, type 'regedit', and press Enter to open Registry Editor.
2. Navigate through the hierarchy to find the key you want to modify.
3. Right-click on a key to modify it or create a new key/value pair.
4. Always back up the registry before making changes.
// Adding a new registry key
New-Item -Path "HKCU:\Software\MyNewKey"
// Setting a registry value
Set-ItemProperty -Path "HKCU:\Software\MyNewKey" -Name "SettingName" -Value "MyValue"
// Sets a specific desktop wallpaper and prevents users from changing it.
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "Wallpaper" -Value "C:\Path\To\Wallpaper.jpg"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "WallpaperStyle" -Value 2
Introduction to Security Policies Configuring security policies (GUI) PowerShell examples for security policy management Enforcing password complexity requirements (PowerShell) Configuring audit policies (GUI) Managing user rights assignments (PowerShell) Security Policies: Enforcing password history Security Policies: Setting account lockout duration Security Policies: Configuring audit policies Security Policies: Enforcing password complexity
Security policies are crucial for defining security settings for a computer or network. Administrators use them to set password policies, account lockout policies, and audit policies.
1. Press Win + R, type 'secpol.msc', and press Enter to open Local Security Policy.
2. Navigate to Account Policies or Local Policies to adjust settings as needed.
3. Apply settings to user rights assignments and security options according to your organization's security requirements.
// Setting password policy
Set-LocalUserPasswordPolicy -PasswordHistoryCount 10 -MaximumPasswordAge 90 -MinimumPasswordLength 8
// Configuring account lockout policy
Set-LocalAccountLockoutPolicy -LockoutDuration 30 -LockoutThreshold 5 -ResetLockoutCounterAfter 30
// Enforces password complexity requirements for user accounts
Set-LocalSecurityPolicy -UserRights "SeDenyNetworkLogonRight" -Add "Authenticated Users"
1. Open Local Security Policy by running 'secpol.msc'.
2. Navigate to 'Advanced Audit Policy Configuration' under 'Security Settings'.
3. Configure audit policies for account logon events, account management, object access, and more.
// Granting a user the right to log on locally
Add-LocalGroupMember -Group "Administrators" -Member "Domain\User"
// Revoking the right to log on locally
Remove-LocalGroupMember -Group "Administrators" -Member "Domain\User"
// Uses Local Security Policy to enforce a password history to prevent users from reusing recent passwords.
secedit /export /cfg "C:\secconfig.cfg"
((Get-Content -Path "C:\secconfig.cfg" -Raw) -replace "PasswordHistorySize = 0", "PasswordHistorySize = 24") | Set-Content -Path "C:\secconfig.cfg"
secedit /configure /db "C:\Windows\security\local.sdb" /cfg "C:\secconfig.cfg" /areas SECURITYPOLICY
// Configures the account lockout duration to 30 minutes after a specified number of failed login attempts.
secedit /export /cfg "C:\secconfig.cfg"
((Get-Content -Path "C:\secconfig.cfg" -Raw) -replace "LockoutDuration = 0", "LockoutDuration = 30") | Set-Content -Path "C:\secconfig.cfg"
secedit /configure /db "C:\Windows\security\local.sdb" /cfg "C:\secconfig.cfg" /areas SECURITYPOLICY
// Modifies audit policies to track successful and failed logon attempts.
Auditpol /set /subcategory:"Logon" /success:enable /failure:enable
// Enforces password complexity requirements to enhance security.
secedit /export /cfg "C:\secconfig.cfg"
((Get-Content -Path "C:\secconfig.cfg" -Raw) -replace "PasswordComplexity = 0", "PasswordComplexity = 1") | Set-Content -Path "C:\secconfig.cfg"
secedit /configure /db "C:\Windows\security\local.sdb" /cfg "C:\secconfig.cfg" /areas SECURITYPOLICY
Introduction to User Access Control Configuring UAC settings (GUI) Automating UAC configuration via PowerShell Disabling UAC prompts for specific applications (PowerShell) Logging UAC prompts to audit unauthorized access attempts (PowerShell) Automatically adjusting UAC settings based on network location (PowerShell) Enhancing security by enforcing UAC for standard users Configuring UAC to prevent bypass using secure desktop
User Access Control (UAC) helps prevent unauthorized changes to your operating system by requiring administrative privileges for certain actions.
1. Open Control Panel, go to 'User Accounts', then 'Change User Account Control settings'.
2. Move the slider to choose when to be notified about changes to your computer.
3. Click 'OK' to save your settings. You may need to provide administrative credentials.
// Sets the UAC level to always notify
Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 1
Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 2
// Using Task Scheduler to bypass UAC prompts for specific applications
$action = New-ScheduledTaskAction -Execute 'Path\to\Application.exe'
$principal = New-ScheduledTaskPrincipal -UserId 'DOMAIN\User' -LogonType S4U -RunLevel Highest
$trigger = New-ScheduledTaskTrigger -AtLogon
Register-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -TaskName "RunAppWithoutUAC" -Description "Runs an app without UAC prompts"
// Configuring Group Policy to log all UAC prompts
Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name EnableUIADesktopToggle -Value 1
// Increases UAC security level when connected to public networks
$networkProfile = Get-NetConnectionProfile | Select-Object -ExpandProperty NetworkCategory
if ($networkProfile -eq 'Public') {
Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 2
} else {
Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0
}
Network Connectivity
Using Test-NetConnection to test connectivity, trace route, and perform detailed diagnostics Using ping to check network connectivity and measure latency Using tracert to trace the route packets take to a network host Using pathping to combine features of ping and tracert Using nmap for network exploration and security auditing Using telnet to test TCP connections to specific ports
// Tests basic TCP connectivity to www.example.com on port 80
Test-NetConnection -ComputerName www.example.com -Port 80
// Performs a trace route to www.example.com
Test-NetConnection -ComputerName www.example.com -TraceRoute
// Tests connectivity and provides detailed diagnostic information
Test-NetConnection -ComputerName www.example.com -InformationLevel Detailed
// Checks connectivity to www.example.com with a specific source address
Test-NetConnection -ComputerName www.example.com -Source '192.168.1.2'
// Verifies if ICMP Echo Request messages (pings) are allowed
Test-NetConnection -ComputerName www.example.com -CommonTCPPort HTTP
// Sends 4 echo requests to www.example.com
ping www.example.com
// Sends a ping with the specified number of echo requests
ping -n 10 www.example.com
// Sends a ping with larger packets
ping -l 128 www.example.com
// Pings the host until stopped
ping -t www.example.com
// Specifies a timeout (in milliseconds) for each reply
ping -w 500 www.example.com
// Traces the route to www.example.com
tracert www.example.com
// Traces the route and bypasses the DNS resolution for each hop
tracert -d www.example.com
// Specifies the maximum number of hops in the route search
tracert -h 30 www.example.com
// Traces the route using IPv6 addresses
tracert -6 www.example.com
// Traces the route and uses large packets
tracert -l 100 www.example.com
// Combines the features of ping and tracert to www.example.com
pathping www.example.com
// Specifies the number of pings per hop
pathping -q 10 www.example.com
// Specifies the timeout for each ping
pathping -w 5000 www.example.com
// Specifies the number of hops to trace
pathping -h 25 www.example.com
// Performs the pathping without resolving addresses to names
pathping -n www.example.com
// Scans the host for open TCP ports
nmap -p 1-65535 www.example.com
// Performs a fast scan
nmap -F www.example.com
// Detects OS and services
nmap -A www.example.com
// Scans using a specific network interface
nmap --interface eth0 www.example.com
// Outputs the scan in XML format
nmap -oX scan_results.xml www.example.com
Basic DNS querying using nslookup Using nslookup to query all records associated with a domain Using nslookup to check delegation and server information Using PowerShell to perform DNS lookups Using dig (Windows Subsystem for Linux or third-party tool) for advanced DNS queries Using ipconfig to flush and display DNS resolver cache
// Queries the IP address for www.example.com
nslookup www.example.com
// Uses a specific DNS server to query the IP address for www.example.com
nslookup www.example.com 8.8.8.8
// Queries the MX records for example.com
nslookup -query=mx example.com
// Queries the SOA record for example.com
nslookup -type=soa example.com
// Performs a reverse DNS lookup for an IP address
nslookup 192.168.1.1
// Queries all records for example.com
// Queries all records for example.com
nslookup -query=any example.com
// Enters interactive mode with nslookup
nslookup
> set type=any
> example.com
> exit
// Checks DNS server details and zone delegation for example.com
nslookup -type=ns example.com
// Uses nslookup in debug mode to get detailed information
nslookup -debug example.com
// Performs a DNS lookup using PowerShell
Resolve-DnsName www.example.com
// Retrieves MX records using PowerShell
Resolve-DnsName -Type MX example.com
// Retrieves TXT records for domain verification
Resolve-DnsName -Type TXT example.com
// Performs a detailed DNS lookup including DNSSEC details
Resolve-DnsName -Name example.com -DnssecOk
// Retrieves all DNS records associated with the domain
Resolve-DnsName -Type ALL example.com
// Performs a basic DNS query using dig
dig www.example.com
// Queries a specific type of record with dig
dig example.com MX
// Performs a reverse DNS lookup using dig
dig -x 192.168.1.1
// Uses dig to trace the path of the DNS query
dig +trace www.example.com
// Performs a DNS query specifying a particular DNS server
dig @8.8.8.8 www.example.com
Basic usage of curl to make HTTP requests Using curl to handle cookies and sessions Testing HTTPS connections with curl Using curl to upload files to a server Using curl to download files Using PowerShell's Invoke-WebRequest as an alternative to curl for HTTP requests Using PowerShell's Invoke-RestMethod for API interaction
// Makes a simple GET request to a web page
curl http://www.example.com
// Uses curl to make a GET request and display headers
curl -I http://www.example.com
// Makes a POST request with curl
curl -d 'login=username&password=password' -X POST http://www.example.com/login
// Sends a DELETE request using curl
curl -X DELETE http://www.example.com/resource
// Makes a GET request with headers using curl
curl -H 'Accept: application/json' -H 'Content-Type: application/json' http://www.example.com/api
// Saves cookies received during a session to a file
curl -c cookies.txt http://www.example.com
// Uses a cookie file for subsequent requests
curl -b cookies.txt http://www.example.com
// Makes a request using both cookie save and load
curl -b cookies.txt -c new_cookies.txt http://www.example.com
// Accesses an HTTPS site without verifying the SSL certificate
curl -k https://www.example.com
// Makes a secure HTTPS request verifying the SSL certificate
curl --cacert path/to/certfile https://www.example.com
// Uploads a file using POST
curl -F 'file=@path/to/localfile' http://www.example.com/upload
// Uploads a file with PUT
curl -T path/to/localfile http://www.example.com/destination
// Downloads a file and saves it locally
curl -o localfilename http://www.example.com/remotefile
// Downloads a file with the original filename
curl -O http://www.example.com/remotefilename
// Makes a basic GET request
$response = Invoke-WebRequest -Uri http://www.example.com
// Posts data to a web service
$postData = @{username='user'; password='pass'}
$response = Invoke-WebRequest -Uri http://www.example.com/login -Method Post -Body $postData
// Captures and displays headers of a response
$response.Headers
// Calls a RESTful API to get JSON data
$result = Invoke-RestMethod -Uri http://www.example.com/api/data -Method Get
// Sends data to a RESTful API using POST
$body = @{id=123; value='abc'} | ConvertTo-Json
$result = Invoke-RestMethod -Uri http://www.example.com/api/post -ContentType 'application/json' -Method Post -Body $body
Viewing installed SSL certificates in the local machine store Finding certificates that are about to expire Exporting a certificate to a file Importing a certificate into the local machine store Checking SSL certificate details on a website using PowerShell Verifying the SSL chain of a certificate Using OpenSSL to convert a certificate from DER to PEM format Using OpenSSL to verify a certificate against a CA Using certutil to dump certificate information Using certutil to repair a certificate store Creating a self-signed certificate using PowerShell Using certreq to request certificate installation Using PowerShell to list certificates with a specific key usage Using PowerShell to remove an expired certificate Checking SSL/TLS versions supported by a server using Test-SSL
// Lists all certificates in the LocalMachine store
Get-ChildItem -Path Cert:\LocalMachine\My
// Lists certificates with details
Get-ChildItem -Path Cert:\LocalMachine\My | Format-List -Property *
// Finds certificates expiring in the next 90 days
$threshold = (Get-Date).AddDays(90)
$certs = Get-ChildItem -Path Cert:\LocalMachine\My
$expiringCerts = $certs | Where-Object { $_.NotAfter -lt $threshold }
$expiringCerts
// Exports a certificate to a .cer file
$cert = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Subject -like '*example.com*' }
Export-Certificate -Cert $cert -FilePath 'C:\example.cer'
// Imports a certificate from a file
Import-Certificate -FilePath 'C:\example.cer' -CertStoreLocation Cert:\LocalMachine\My
// Retrieves SSL certificate details from a website
$request = [Net.HttpWebRequest]::Create('https://www.example.com')
$request.ServicePoint | Select-Object Certificate -ExpandProperty Certificate
// Verifies the certificate chain for a given cert
$cert = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Subject -like '*example.com*' }
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($cert)
// Converts a DER format certificate to PEM
openssl x509 -inform der -in certificate.der -out certificate.pem
// Creates a self-signed certificate
New-SelfSignedCertificate -DnsName 'example.com' -CertStoreLocation 'cert:\LocalMachine\My'
// Requests certificate installation from a CA
certreq -submit -attrib "CertificateTemplate:WebServer" requestfile.inf
// Lists certificates that are valid for server authentication
$certs = Get-ChildItem -Path Cert:\LocalMachine\My
$serverAuthCerts = $certs | Where-Object { $_.Extensions | Where-Object { $_.Oid.FriendlyName -eq 'Key Usage' -and $_.KeyUsages -match 'KeyEncipherment' } }
$serverAuthCerts
Network Configuration
Viewing all network adapters using PowerShell Enabling a network adapter using PowerShell Disabling a network adapter using PowerShell Renaming a network adapter using PowerShell Changing the IP address of an adapter using PowerShell Viewing network adapter properties using the GUI Configuring IP settings via GUI Resetting network settings using Command Prompt Viewing and modifying firewall settings using PowerShell Configuring WiFi settings using GUI Configuring network profiles using PowerShell Managing network routes using Command Prompt Monitoring network traffic using PowerShell Changing DNS settings using the GUI Troubleshooting network issues using PowerShell Setting up bandwidth control using Command Prompt
// Lists all network adapters with status
Get-NetAdapter | Select-Object Name, Status, InterfaceDescription
// Renames a network adapter named 'Ethernet' to 'Local Area Connection'
Rename-NetAdapter -Name 'Ethernet' -NewName 'Local Area Connection'
// Renames a network adapter from 'Ethernet' to 'Primary Ethernet'
Rename-NetAdapter -Name 'Ethernet' -NewName 'Primary Ethernet'
// Sets a static IP address
New-NetIPAddress -InterfaceAlias 'Ethernet' -IPAddress 192.168.1.100 -PrefixLength 24 -DefaultGateway 192.168.1.1
// Sets DNS server addresses
Set-DnsClientServerAddress -InterfaceAlias 'Ethernet' -ServerAddresses ('8.8.8.8', '8.8.4.4')
// Steps to view properties of a network adapter
Control Panel > Network and Internet > Network and Sharing Center > Change adapter settings
> Right-click an adapter > Status > Details
// Steps to configure IP settings using GUI
Control Panel > Network and Internet > Network and Sharing Center > Change adapter settings
> Right-click an adapter > Properties > Internet Protocol Version 4 (TCP/IPv4) or Internet Protocol Version 6 (TCP/IPv6)
> Properties > Use the following IP address > Enter IP address, Subnet mask, and Default gateway > OK
// Resets TCP/IP stack to installation defaults
netsh int ip reset
// Flushes DNS resolver cache
ipconfig /flushdns
// Resets Winsock Catalog
netsh winsock reset
// Lists all active firewall rules
Get-NetFirewallRule -Enabled True
// Disable a specific firewall rule
Set-NetFirewallRule -DisplayName 'Rule Name' -Enabled False
// Steps to connect to a WiFi network using GUI
Click the network icon on the taskbar > Select the network SSID > Click Connect
> Enter the network security key > OK
// Sets the network location to private
Get-NetConnectionProfile -InterfaceAlias 'Ethernet' | Set-NetConnectionProfile -NetworkCategory Private
// Adds a static IP route to the routing table
route add 192.168.2.0 mask 255.255.255.0 192.168.1.1
// Deletes a route from the routing table
route delete 192.168.2.0
// Captures and displays packets from a specified interface
netsh trace start capture=yes EthernetInterfaceName=Ethernet
netsh trace stop
// Steps to change DNS server address using GUI
Control Panel > Network and Internet > Network and Sharing Center > Change adapter settings
> Right-click an adapter > Properties > Internet Protocol Version 4 (TCP/IPv4) or Version 6 (TCP/IPv6)
> Properties > Use the following DNS server addresses > Enter Preferred DNS server and Alternate DNS server > OK
Enabling and disabling the Windows Firewall using PowerShell Adding a new inbound firewall rule using PowerShell Configuring firewall to allow an application using PowerShell Removing a firewall rule using PowerShell Modifying an existing firewall rule using PowerShell Enabling and disabling firewall rules using the GUI Creating an outbound rule to block a specific port using the GUI Allowing a program through the firewall using the GUI Viewing active firewall rules using PowerShell Exporting and importing firewall rules using PowerShell Checking firewall status for all profiles using PowerShell Setting firewall profiles (Private, Public, Domain) using PowerShell Logging dropped packets and successful connections using PowerShell Configuring firewall to prevent all outbound connections by default using the GUI Creating advanced firewall rules to handle complex scenarios using PowerShell
// Enables Windows Firewall
Set-NetFirewallProfile -All -Enabled True
// Disables Windows Firewall
Set-NetFirewallProfile -All -Enabled False
// Adds an inbound rule to allow TCP traffic on port 80
New-NetFirewallRule -DisplayName 'Allow HTTP Inbound' -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
// Allows an application through the firewall
New-NetFirewallRule -DisplayName 'Allow MyApp' -Program 'C:\Program Files\MyApp\app.exe' -Action Allow
// Removes a firewall rule named 'Allow HTTP Inbound'
Remove-NetFirewallRule -DisplayName 'Allow HTTP Inbound'
// Modifies an existing rule to change the local port
Set-NetFirewallRule -DisplayName 'Allow HTTP Inbound' -LocalPort 8080
// Steps to enable/disable firewall rules using GUI
Control Panel > System and Security > Windows Defender Firewall > Advanced Settings
> Inbound Rules or Outbound Rules > Right-click a rule > Enable Rule or Disable Rule
// Steps to block a specific port using GUI
Control Panel > System and Security > Windows Defender Firewall > Advanced Settings > Outbound Rules
> New Rule > Port > Specify TCP or UDP and the port number > Block the connection > Finish
// Steps to allow a program through the firewall using GUI
Control Panel > System and Security > Windows Defender Firewall > Allow an app or feature through Windows Defender Firewall
> Change settings > Allow another app... > Browse to the program > Add > OK
// Displays all active firewall rules
Get-NetFirewallRule -Enabled True | Format-Table DisplayName, Direction, Action
// Exports all firewall rules to a file
netsh advfirewall export "C:\firewallrules.wfw"
// Imports firewall rules from a file
netsh advfirewall import "C:\firewallrules.wfw"
// Sets the firewall profile to private and enables it
Set-NetFirewallProfile -Profile Private -Enabled True
// Disables the public firewall profile
Set-NetFirewallProfile -Profile Public -Enabled False
// Enables logging for dropped packets
Set-NetFirewallProfile -Profile Domain -LogDroppedPackets True
// Enables logging for successful connections
Set-NetFirewallProfile -Profile Domain -LogAllowedConnections True
// Steps to set the firewall to block all outbound connections by default using GUI
Control Panel > System and Security > Windows Defender Firewall > Advanced Settings > Windows Defender Firewall Properties
> Outbound connections > Block > OK
// Creates a rule to allow inbound FTP traffic on port 21
New-NetFirewallRule -DisplayName 'FTP Inbound' -Direction Inbound -Protocol TCP -LocalPort 21 -Action Allow
// Creates a rule to block outbound traffic to a specific IP range
New-NetFirewallRule -DisplayName 'Block Outbound to 192.168.1.0/24' -Direction Outbound -RemoteAddress 192.168.1.0/24 -Action Block
Monitoring live network traffic using PowerShell Using Performance Monitor to track network performance Using Wireshark for detailed network packet analysis Using the netstat command to view active connections Configuring Data Collector Set in Performance Monitor for extended monitoring Using Resource Monitor to view network activity Using PowerShell to audit network sessions Monitoring DNS queries and responses on your network Using the pathping command for network path analysis Analyzing network interface performance counters using PowerShell Using TcpView to monitor network connections in real-time Monitoring bandwidth usage using PowerShell Logging packet drops and network errors using Event Viewer Using nmap to scan your network for open ports and service detection Configuring SNMP for network device monitoring Using Netsh to monitor and log network traffic Using BgInfo to display network configuration on desktop Using Microsoft Message Analyzer for advanced network diagnostics Checking network adapter errors using PowerShell Using Advanced IP Scanner to analyze network hosts
// Captures live network traffic from a specific adapter
Get-NetAdapter | Where-Object { $_.Name -eq 'Ethernet' } | Get-NetAdapterStatistics
// Monitors TCP connections in real-time
Get-NetTCPConnection | Format-Table -Property LocalAddress, LocalPort, RemoteAddress, RemotePort, State -AutoSize
// Steps to set up Performance Monitor for network tracking
Start > Type 'Performance Monitor' > Open Performance Monitor > Add counters > Select 'Network Interface'
> Choose counters like Bytes Total/sec, Current Bandwidth > Add > OK
// Guide to capture network packets using Wireshark
Download and install Wireshark > Open Wireshark > Select the network interface
> Click 'Start Capturing Packets' > Apply display filters for specific analysis, e.g., 'ip.addr == 192.168.1.1'
// Displays all active TCP connections
netstat -an | findstr 'ESTABLISHED'
// Shows all listening ports
netstat -an | findstr 'LISTEN'
// Steps to create and start a Data Collector Set
Performance Monitor > Data Collector Sets > User Defined > New > Data Collector Set
> Define the set and add desired counters > Schedule and start collection
// Steps to access and use Resource Monitor for network monitoring
Press Win + R > Type 'resmon' and press Enter > Click on the 'Network' tab to see network activity
// Retrieves detailed information about active network sessions
Get-SmbSession | Format-List -Property *
// Using PowerShell to monitor DNS client events
Get-WinEvent -LogName 'Microsoft-Windows-DNS-Client/Operational' | Where-Object { $_.Id -eq 3008 }
// Collects and displays performance data for network interfaces
$NICs = Get-Counter -Counter '\Network Interface(*)\Bytes Total/sec'
$NICs.CounterSamples | Format-Table -AutoSize
// Steps to use TcpView for real-time network monitoring
Download TcpView from Sysinternals > Run the tool > Observe dynamic display of endpoints and connections
// Measures bandwidth usage per interface
$interfaces = Get-NetAdapterStatistics
foreach ($interface in $interfaces) {
Write-Output "Interface: $($interface.Name)`tReceived: $($interface.BytesReceivedPersec)`tSent: $($interface.BytesSentPersec)"
}
// Viewing network error logs in Event Viewer
Event Viewer > Windows Logs > System > Filter current log > Event sources > Network
// Guide to configure SNMP via PowerShell
Install-WindowsFeature -Name SNMP-Service -IncludeAllSubFeature -IncludeManagementTools
// Configuring SNMP community string
cmd /c 'echo SNMP_COMMUNITY_NAME public > snmp.txt'
cmd /c 'reg import snmp.txt'
// Configures netsh to capture traffic
netsh trace start capture=yes tracefile=C:\network_trace.etl
// Stops the trace
netsh trace stop
// Steps to configure BgInfo to show network settings on desktop
Download BgInfo from Sysinternals > Configure BgInfo to display desired network parameters on desktop >
Apply and set it to run at startup
// Steps to use Microsoft Message Analyzer
Download and install Microsoft Message Analyzer > Open tool and start a new session to capture traffic >
Analyze and view detailed network communications