PowerShell
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 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
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}}