CMD and PowerShell Teams

The list of Windows command (cmd) and PowerShell cmdlet with arguments and category filter.

158 out of 158 teams show
core (cmd) modern (powershell) security
Audit Problems Pentest
CommandCategoryLevelDescriptionMain arguments
dir Files core List directory content with attributes and sizes /a show files with all attributes
/s resource into subdirectories
/b bare format - filenames only
/o sort order (n=name s=size d=date)
/p
/q display owner
cd / chdir Files core Change current working directory cd .. move up one level
cd \ go to drive root
cd /d D:
cd (from arches) print current directory
copy Files core Copy one or more files to another location /y over
/-y prompt before over
/b binary copy
/a ASCII copy
/v verify copy after write
xcopy Files core Extended copy of files and directory tracks /s copy non-empty subdirs
/e copy all subdirs (including empirical)
/i assume destination is directory
/h copy hidden and system files
/y over
/d copy only newer files
/eclude skip patterns from file
robocopy Files modern Robust file copy - mirror, purpose, multi-thread /mirror tree (delete extra at dest)
/e copy subdirs including empty
/z restartable mode
/mt:N multi-threaded copy (default 8)
/r:
/w:
/log:file write log to file
/xo exclude older files
/eta
move Files core Move or rename files and directories /y over
/-y delay on overwrite
move file new rename file
move *.txt D:\arc match move
del / erase Files core Delete files permanently (not to Recycle Bin) /p prompt beforee each delete
/f force delete read-only
/s course subdirectories
/q quot (from prompt) for wildcards
/a filter by repeltes (h, s, r, a)
mkdir / md Files core Create one or more directories mkdir a\b\c created nested pah in one call
md "My Folder"
rmdir / rd Files core Remove an empirical directory or sole tree /s remove directory and all content
/q quot mode (no confirmation)
rd dir remove empy directory only
mklink Files core Create symbolic links, hard links, or challenges /d directory symbolic link
/h hard link (file only)
/j directory junction
mklink link target default fileymlink
attrib Files core Display or change file contributions (R H S A) +r / -r set/clear read-only
+h / -h set/clear hidden
+s / -s set/clear system
/s apply pursuantly
/d also process folders
Get-ChildItem Files modern PowerShell - list filesystem (or register) items with rich properties -Path target pat
-Refund enumerate subdirectories
-Filter fast filesystem-level filter
- Force including hidden/system items
-File / -Directory type filter
-Hidden hidden items only
Copy-Item Files modern PowerShell - copy files, directories, or register items -Path / -Destination source and target
-Refund copy entire
- Force over
-Exclude pattern to skip
-Filter fast provider filter
-PassThru emit crowded object
Remove-Item Files modern PowerShell - delete files, folders, register keys -Refund delete subtree
- Force delete read-only/hidden
- Include / -Exclude patch filters
- Confirm prompt before
-WhatIf dry-run preview only
where Files core Locate executables in PATH where program find first match in PATH
/r dir refund from directory
/q quot
/f quota returned path
/t show size and timing
assoc / ftype Files core Display or modify file extension associations and command handlers assoc list all associations
assoc .txt show association for ext
assoc .txt=txtfile set association
ftype list all file types
ftype txtfile=notepad
Test-Path Files modern Power -Path target pah
-PathType Leaf/Container/ Any
- IsValid check syntax only
- IsAbsolute absolute path check
-OlderThan / -NewerThan time predicate
type Text core Display the contents of a text file on the password type file.txt print file
type a.txt b.txt concatenate
type *.log prints files + content
more Text core Display output one screen at a time (pager) /c clear screen before before each page
/s squeeze multiple blank lines
+N start at line N
Space next page ENTER next line
findstr Text core Search for text patches in files /i case-intensive match
/r treat strings as regular expressions
/s course subdirectories
/n prefix output with line numbers
/v print lines that do NOT match
/c:"phrase' literary multi-word search
/g:
find Text core Search for a literal text string in files /i case-intensive
/v invert
/c count matching lines
/n show line numbers
fc Text core Compare two files and show differences /a
/b binary compare
/n show line numbers (text)
/u Unicode compare
/w ignore whitespace
comp Text core Byte-by-byte file comparison /a display differences as characters
/l show line numbers of differences
/n=N compare first N lines only
/c case-intensive
sort Text core Short lines from /r reverse short order
/+N start at Column N
/m N use N megabytes of memory
/o file write output to file
Select-String Text modern PowerShell - regex search across files (grep equivalent) - Pattern regex to match
-Path / -LiteralPath files to search
- CaseSensitive exact case
-Context A,B N lines before/after
-NotMatch invert
-List one match per file only
-AllMatches all matches per line
Get-Content Text modern PowerShell - read file content (cat/tail/head equivalent) - TotalCount N first N lines (head)
-Tail N last N lines
-Wait follow file (tail-f)
-Encoding UTF8, ASCII, Unicode
-Raw read as single string
-Stream read alternate data stream
Set-Content Text modern PowerShell - write or reply file content with given string -Path target file
-Value content to write
-Encoding UTF8, ASCII, UTF8BOM
- Force over
-NoNewline do not append CRLF
ConvertFrom-Json / ConvertTo-Json Text modern PowerShell - parse JSON into objects and back to text ConvertFrom-Json string → object
-Depth N nesting deep (default 2)
ConvertTo-Json object → string
-Compress from whitespace
-AsHashtable parse into hashtable
doskey Text core Recall and edit command history; defined command macros (cmd.exe) /history print command history
/listsize=N history buffer size
name=command define macro a.k.a
/macros list all macros
/macrofile=fileload macros from file
clip Text core Pipe stdout into the Windows clipboard echo hello √ clip copy text to clipboard
dir
type file √ clip copy file content
tasklist Processes core Display all running processes with PID and memory /v verbose (user, status)
/svc show services in each process
/fi apply filter (e.g. "imagename eq chromium.exe")
/fo output format (table, csv, list)
/m show DLLs loved by process
taskkill Processes core Terminate a running process by PID or name /pid N terminate by process ID
/im name.exe terminate by image
/f force termate (from graceful close)
/t also terminate child processes
/fi apply filter (e.g. "status eq not responding")
start Processes core Start a separate window to run a program or command /b start without new window
/
/min/ /max start minimized/maximized
/d path starting directory
/finity N CPU affinity mask
start "
Get-Process Processes modern PowerShell - retrieve process objects with rich properties - ed
-Id N filter by PID
-IncludeUser show owner (admin)
-Module show loved modules
-FileVersionInfo show exe version
√ Sort-Object CPU -Desc top by CPU
Stop-Process Processes modern PowerShell - terminate one or more processes -Id N Terminate by PID
- name
- Force skip confirmation
-PassThru issue termed object
- Confirm prompt beforee kit
Start-Process Processes modern PowerShell - Launch program with detailed control -FilePath external to run
- ArgumentsList command-line argument
-Verb RunAs Elevated (UAC prompt)
-WindowStyle Hidden/Minimized
-Wait block
-RedirectStandardOutput capture stdout
Wait-Process Processes modern PowerShell - block until one or more processes apart - %1
-Id N wait for PID
-Timeout N give up after N seconds
-ErrorAction Silently
Get-Service Processes modern PowerShell - list and inspect Windows services - filter
-Display filter
-Status Running, Stopped, Paused
- Include / -Exclude patch filter
-RequiredServices show scholarships
Procmon (Sysinternals) Processes modern Real-time file, register, network, and process activity monitor /AcceptEula skip EULA prompt
/Quiet start tracking immediately
/BackingFile log to file
/Load
/Terminate stop running instance
shutdown Processes core Shut down, restart, or log off the local or remote computer /s shut down
/r restart
/l log off
/g shutdown + restart apps
/t
/m \host target remote host
/c "msg" comment shown to users
/f force close apps
/a abort pending shutdown
logoff Processes core End a user session (local or terminal services) sesionid log off specific session
/server:
/v verbose
note: combination with quser to find session ID
Restart-Computer Processes modern PowerShell - reboot one or more computers (local or remote) -Computer host1,host2
- Force force shutdown despite locked sessions
-Credential alternative credentials
-Wait -For PowerShell wait until WinRM up
-Delay N retry interval
- Protocol DCOM/WSMan
Stop-Computer Processes modern PowerShell - power off one or more computers -Computer host
- Force force
-Credential alternative credentials
-WsmanAuthentication Default/Basic/Kerberos
Invoke-Command Processes modern Power -Computer host1,host2
-ScriptBlock { }
-FilePath script.ps1
-Credential alternative credentials
-AsJob run as background job
-ThrottleLimit N
Enter-PSSession Processes modern Power -Computer host
-Credential alternative credentials
- Authentication Kerberos/CredSSP
-Configuration name
- UseSSL WinRM over HTTPS
Exit-PSSession leave session
sc System core Control and query the Windows Service Control Manager query list services and status
queryex include PID and flags
start / stop control service
config change start type or path
create name bin
delete remove service
systeminfo System core Display detailed configuration of the local system /s host query remote computer
/u user authentication as user
/fo output format (table, csv, list)
/nh suppress heads (csv/table)
ver System core Display the Windows version string ver print OS version
hostname System core Print the computer NetBIOS hostname hostname prints current hostname
set System core Display, set, or remove environment variables set VAR=value set in current session
set VAR=remove from session
set list all variations
set /p VAR=Prompt: read from user
set/a Var=2*3 aarithmetic evaluation
setx System core Persistently set environment variables (user or machine) setx Var value set for current user
/m set system-wide (admin)
/s host set on remote computer
/k regkey read from register
note:
wmic System core Windows Management Instrumentation command-line (legacy) os get capture,version
cpu get name
logicaldisk get size,freespace,caption
process where name='chrome.exe' get processid
computer get utility,model
note: WMIC is depreciated and not installed by default since Windows 11 24H2 - use Get-CimInstance
Get-CimInstance System modern PowerShell - query WMI/CIM objects (WMIC replacement) -Class WMI class (Win32 *)
-Filter WQL filter
-Property return only listed benefits
-Computer query remote system
- alternate
Get-ComputerInfo System modern PowerShell - retrieve consolidated system information object -Property * show all properties
Os* filter to OS-related properties
Bios* BIOS/firmware info
Cs* computer system info
Set-Service System modern PowerShell - configure a Windows service - service to modify
-Status Running/Stopped
-StartupType Automatic/Manual
- set service description
-Display set display
schtasks System core Task Scheduler CLI /create defined new scheduled task
/run trigger immediately
/end stop running task
/query list all tasks
/delemove task
/sc schedule type (DAILY, ONLOGON, ONSTART)
/tn
git System modern Distributed version control - track and collaborate on code status
log-oneline--graph compact history
diff HEAD changes since last committee
stash push/pop hatche and restore changes
rebase -i interactive squash/reorderer
bisect start/good/bad find bug committee
blame show line-by-line authority
winget System modern Windows Package Manager - install, upgrade, remove apps search
install id install package
upgrade --all update all packages
list show installed packages
uninstall id remove package
source add add
export/import reproduce setup
choco System modern Chocolatey - community Windows package manager install pkg -y install warmly
upgrade all -y update all packages
list --local-only installed packages
uninstall pkg -y remove package
pin add -n=pkg freeze version
feature enabled -n enabled feature
gpupdate System core Refresh Group Policy settings on the local computer /force again all settings
/target:usera
/wait:
/logoff log off if needed by policies
/boot reboot if needed by policies
/sync synchronous
reg System core Read, write, import, export, and company Windows Registry entities query KEY /s returnable list
query KEY /v VALUE
add KEY /v name /t REG SZ / d
delete KEY /v name / f
export KEY file.reg
import file.reg
save KEY file.hiv raw hive
load HKLM\Tmp file.hiv
regedit System core Registry Editor - GUI for browsing and modifying the register regedit open GUI
regedit /s file.reg silently applicable .reg
/e file.reg HKLM\path export branch
note: prefer 'reg' for scripting
msiexec System core Install, uninstall, or repair MSI/MSP packages i pkg.msi install
/x pkg.msi uninstall
/qn silent (from UI)
/qb basic UI
/norestart do not auto-reboot
/l*v log.txt verbose login
ALLUSERS=1 machine-wide
TRANSFORMS= applicable .mst
sfc System core System File Checker - scan and repair protected OS files /scannow scan and repair all system files
/verifyly scan without repair
/scanfile=path check single file
/offbootdir / /offwindir offline image scan
note:
dism System core Employment Image Service and Management - online and image service /Online target running OS
/Image:
/Cleanup-Image /RestoreHealth Repair
/Get-Features list features
/Enable-Feature /Feature
/Get-Packages list installed updates
/Add-Driver /Driver:path
/Export-Image export WIM
bcdedit System core Boot Configuration Data store editor - boot loader configuration /enum list boot entries
/default {GUID} set default OS
/timeout
/set {GUID} description "name"
/copy {GUID} /d "copy"
/export file back up BCD
/import file repairer BCD
note:
driverquery System core List installed device drivers and their properties /v verbose
/si signed driver info
/fo output format (table, list, csv)
/nh suppress heads
/s host /u user remote query
pnputil System core Manage driver packages in the driver store /enum-drivers list staged drivers
/add-driver in addition and install
/delete-driver oem##.inf /uninstall
/scan-doses rescan for new devices
/disable-device / /enable-device
/restart-device
powercfg System core Query and configure power plans, sweep, hibernation, battery /list list power schemes
/setactive GUID
/h on
/lastwake show last wake source
/devicequery wake armed who can wake
/batteryreport HTML battery report
/energy power efficiency audit
/requests active power requests
net share / net use System core Manage SMB shares and folderd network drives net share list local shares
net share name=C:
/grant:user, read
net use Z:
net use Z:
/user:
/persistent:yes
net start / net stop System core Start or stop a Windows service net start list running services
net start name start service
next
note:
Restart-Service / Start-Service / Stop-Service System modern PowerShell - lifecycle control for Windows services - %1
- Force override grants
-PassThru issue resulting object
- Confirm prompt before
-WhatIf dry-run preview
Get-HotFix System modern PowerShell - list installed Windows updates (KB articles) -Id KB#######
-Computer host remote
- Hotfix/Update/Security
InstalledOn by date
Get-ItemProperty System modern PowerShell - read property values (e.g. history values) -Path HKLM:\Software\name
- value
Set-ItemProperty write value
New-ItemProperty created value
Remove-ItemProperty delete value
Get-WindowsFeature / Install-WindowsFeature System modern PowerShell - Server Manager - management rules and features (Windows Server) Get-Windows
- Web-Server filter
Install-Windows
-IncludeManagementTools
-IncludeAllSubFeature
-Restart reboot if needed
Uninstall-WindowsFeature remove
icacls Rights core Display, modification, and back up NTFS access control players (ACLs) /grant user:perm grant permission (F, M, RX, R, W)
/deny user:perm explicit deny
/remove user remove all ACEs for user
/t resource into subdirectories
/c continue on machines
/inheritance:e/d/r enable/disable/reset
/save file back up ACLs
/restore file restore ACLs
takeown Rights core Take ownership of a file or bear (typically as admin) /f file target file or directory
/r returnive
/d Y/N default answer for prompt
/a give ownership to Administrator group
/skipsl skipymlinks
runas Rights core Run a program under a different user account /user: DOMAIN\user specify user
/profile load user profile
/savecred save criticals in Vault
/neonly remote-only criticals
/noprofile from profile (faster)
net user Rights core Manage local user accounts (create, modify, delete, list) net user list all local accounts
net
net user name pass /
/delete remove user
/active:yes
/passwordchg:yes
net localgroup Rights core Manage local groups and their members net localgroup list groups
net localgroup Administrator list members
Administrator user /add add to group
/delete remove from group
group /add create new group
whoami Rights core Display current user, SID, groups, and primileges /user show username and SID
/groups group members
/priv enabled privileges
/all show everything
/fo output format (table, csv, list)
/upn show UPN form
/login show logon ID
cipher Rights core Manage EFS encryption and safely wipe free disk space /e encrypt files
/d decrypt files
/s:dir resource directory
/w:dir wipe delegated data on volume
/k create new EFS key for user
/u update encrypted files with new key
Get-Acl / Set-Acl Rights modern PowerShell - read or write security descriptor of files, folders, register Get-Acl path retrieve ACL object
Set-Acl path -AclObject only ACL
-Audit also include audit ACEs
"Format-List inspection entities"
$acl.SetAccessRule() add ACE programmatically
net user /domain Rights core Query and manage thought user accounts (joined to AD) net user name /
/domain query domain controller
/add /domain create domain account (admin)
note: required AD-joined machine
gpresult Rights core Display applied Group Policy (RSoP) for user and computer /r summary report
/v verbose
/z super-verbose
/h file.html HTML report
/scope user
/user name
auditpol Rights modern View and configuration /get / category:* show current policy
/set /sub category:
/list /subcategory:* list all categories
/backup /file:audit.csv export policy
/restor /file:audit.csv import policy
/clear clear audit policy
Get-LocalUser / New-LocalUser Rights modern PowerShell - management local user accounts (modern net user replacement) Get-LocalUser list local accounts
- name
New-LocalUser -Name -Password (Read-Host -AsSecure)
Set-LocalUser modifiy account
Remove-LocalUser delete account
Enable-LocalUser/Disable-LocalUser
Add-LocalGroupMember -Group Administrator -Member name
Get-ADUser (RSAT) Rights modern PowerShell - query Active Directory user objects (requires RSAT) - Identity sam by SAMAccount
-Filter 'Enabled-eq $true'
-SearchBase 'OU=Sales,DC=...'
-Properties * return all responses
-Server dc.example target DC
Set-ADUser modifications
Unlock-ADaccount
Add-ADGroupMember (RSAT) Rights modern PowerShell - management Active Directory group membership - Identity Group
- Members user1,user2
Remove-ADGroup
Get-DGroup
-Refoursive flatten nested groups
Get-DGroup -Filter * enumerate groups
klist Rights core View and purge Kerberos ticket klist list current ticket
ticket service ticket
tgt Ticket Granting Ticket
purge delete all ticket
purge bind purge bindings
sessions list logo sessions
-li 0x3e7 computer session
ipconfig Network core Display TCP/IP configuration for all network adapters /all show full info incl. MAC, DNS, DHCP
/release [adapter] release DHCP please
/new [adapter] request new DHCP please
/flushdns clear DNA
/displaydns show
/registerdns re-register with DNA
netstat Network core Display TCP/UDP connections, placing ports, and statistics -a all communications and documentation
-n numeric addresses (from DNA)
-o show PID downing connection
-b show existing name (admin)
-r selectable
-s protocol statistics
-p tcp·udp protocol filter
ping Network core Test host reachability using ICMP echo -n N number of echo requests
-l N payload size
-t ping continuous
-i N set IP TTL
-w ms timeout
-4 / -6 force IPv4 or IPv6
tracert Network core Track the network path packages take to a host -d do not resolve hostnames
-h N max hops
-w ms timeout per probe
-4 / -6 force IPv4 or IPv6
trackert host default track
pathping Network core Combine trackout with per-hop package loss statistics -n of
-h N max hops
-q N quests per hop
-w ms timeout
-p ms wait between pings
-4 / -6 force protocol
nslookup Network core Interactive and non-interactive DNA lookup nslookup host basic lookup
nslookup host server
set type=MX change queue type
set type=
-debug show full response
route Network core Display and modify the IP setting table print show
add destin mask gw add static route
delete destin remove route
change dest modifiy route
-p make route persistent
-4 / -6 IPv4 or IPv6 table
arp Network core Display and modify the ARP cache (IP↔MAC Mappings) -a show ARP table
-d ip delete entry
-s ip mac add static entry
-N iface filter by interface
netsh Network core Configuration network interfaces, firewall, WLAN, and more interface ip show config view IP settings
wlan show profiles list brings Wi-Fi
wlan show profile
advfirewall set all profiles state on
int tcp show global TCP tuning
winsock set set set Winsock catalog
Test-NetConnection Network modern PowerShell - port reachability, traceroute, ping diagnostics -Computer host target
-Port N test specific TCP port
-TraceRoute show route hops
- CommonTCPPort HTTP/HTTPS/RDP
-InformationLevel Detailed full output
tnc host -p 443 shorthand
Get-NetIPAddress Network modern PowerShell - retrieve IP address configuration objects -InterfaceAlias name filter by adapter
-AddressFamily IPv4 / IPv6
-PrefixOrigin Dhcp/Manual
-SkipAsSource filter source preference
√ Format-Table tabular view
ssh (OpenSSH) Network modern Secure Shell client - remote login, exec, port forwarding -i identity (private key) file
-p N remote port
-L local port forwarding
-R remote port forwarding
-J jump
-N do not execute remote command
-v verbose debug output
Resolve-DnsName Network modern PowerShell - query DNA records with full record-type support -Type A/AAAA/MX/TXT/ANY
-Server ip use specific residual
-DnsOnly clip Hosts file
-NoHostFile note static hosts
-LlmnrFallback also try LLMNR
nbtstat Network core Display NetBIOS over TCP/IP statistics and name cache -a host remote
-A ip remote name table by IP
-n local name
-c NetBIOS name cache
-r resolved names
-R purge and reload from LMHOSTS
-S sessions table
nltest Network core Test and configuration NETLOGON, domain trusts, and DC discovery /dsgetdc:DOMAIN locale DC for domain
/sc query:DOMAIN query secure channel
/sc reset:DOMAIN reset secure channel
/domain trust list trust relations
/dclist:DOMAIN list DCs in domain
/parentdomain show preliminary thought
netsh advfirewall Network core Configure Windows Defender Firewall - roules, profiles, login set all profiles
firewall add rule name=R protocol=TCP dir=in localport=8080 action=allow
firewall
firewall delete rule name=R
monitor show contacts
set loging filename file.log
set output policy
New-NetFirewallRule Network modern PowerShell - create Windows Firewall rules -Display name
-Direction Inbound/Outbound
-Action Alllow/Block
- Protocol TCP/UDP/ICMPv4
-LocalPort N
- RemoteAddress ip/subnet
-Profile Domain/Private/Public
Get-NetFirewallRule/Remove-NetFirewallRule
curl Transmission core Transfer data over HTTP, HTTPS, FTP, and many other protons -o write output to file
-X HTTP method (GET POST PUT...)
-H add request header
-d POST body data
-L follow redirects
-k skip TLS verification
--retry N rtry on transient file
-u user:pass basic auth
--form multipart/form-data
-s silent (from progress)
Invoke-WebRequest Transmission modern PowerShell - HTTP client return parsed response object - Uri target URL
- Matthew GET/POST/PUT/DELET
- Headers {mm/ yyyy}
- Body request body
-OutFile save response to file
- UseBasicParsing from IE engine
-SkipCertificateCheck denore TLS error
-Credential pass PSCredential
Invoke-RestMethod Transmission modern PowerShell - HTTP client for REST APIs (parses JSON/XML) - Uri endpoint
- Matthew HTTP verb
- Headers request heads
- Body body (auto-series JSON if hashtable)
-ContentType set content-type
- Authentication Bearer -Token modern auth
"ConvertTo-Json perspective result
bitsadmin Transmission core Background Intelligent Transfer Service - resumable downloads (legacy) /transfer name url file download URL to file
/list show active jobs
/cancel jobid abort job
/info jobid /verbose job state
note:
Start-BitsTransfer Transmission modern PowerShell - resumable background HTTP/HTTPS/SMB transfer -Source url source URL
- Destination path target file
- Asynchronous non-blocking job
-Priority Foreground/High/Normal/Low
- Authentication Basic/NTLM/Negoitate
- RetryInterval N seconds between retries
scp (OpenSSH) Transmission core Securely copy files between hosts over SSH -r resource copy of directories
-P N specified remote port
-i identity (private key) file
-p prevent timesteps and fashion
-v verbose debug output
sftp (OpenSSH) Transmission core Interactive secure file transfer over SSH -P N specify port
-i identity file
get / put download / upload file
ls / lls list remote / local files
mget / mput match transfer
perfmon Monitoring core Performance Monitor - real-time and recorded counterparties (GUI/CLI) perfmon open Performance Monitor
perfmon /res open Resource Monitor
perfmon /rel open Relief Monitor
perfmon /report generation System Diagnostic report
typeperf Monitoring core Sample performance counters and write to stdout or CSV "\Processor( Total)\% Processor Time"
-sc N sample count
-si N sample interval (seconds)
-f csv/tsv/bin output format
-o file write to file
-cf file read counter list from file
-q list all counters
Get-Counter Monitoring modern PowerShell - single performance counters with rich objects - Counter "\path' counter path
-SampleInterval N seconds between samples
-MaxSamples N number
- Continuous sample until Ctrl+C
-Computer remote host
-ListSet * enumerate counter sets
Get-EventLog Monitoring modern PowerShell - read classic Windows event window (legacy API) -Log Application/System/Security
-Newest N most recent N entities
-EntryType Error/Warning/Information
-Source name filter by source
- After / -Belore time range
note: supersed by Get-WinEvent
Get-WinEvent Monitoring modern PowerShell - read modern (ETW) Windows event windows with XPath/XML filters -Log Microsoft-Windows* / Security
-FilterHashtable @{LogName='Security'; Id=4625}
-MaxEvents N cap output
-Oldest oldest first
-FilterXPath X
-ListLog * enumerate window
wevtutil Monitoring core Windows Event Log command-line utility el
qe Security /c:10 /rd:tree /f:text query
cl Security Clear log
gli Security log info
epl Security file.evtx export log
sl Log
resmon Monitoring core Resource Monitor - GUI for CPU, memory, disk, network in real time resmon launch GUI
note: Drill down per-process I/O and network connections
Get-NetTCPConnection Monitoring modern PowerShell - list active TCP connections (modern netstat) -State Listen/Established
-LocalPort N filter by local port
- RemoteAddress ip filter by remote IP
-OwningProcess PID filter by process
Id
Sysmon (Sysinternals) Monitoring modern System Monitor - rich endpoint telemetry into Event Log -i config.xml install with config
-c config.xml update running config
-u force uninstall
-h sha256,imphash set hash algorithms
-n log network connections
note: events appeared in Microsoft-Windows-Sysmon/Oporal
quser / query user Monitoring core Display interactive and RDP user sessions on local or remote host quser list sessions on local
quser /server:host remote host
note:
qwinsta / rwinsta Monitoring core Query and reset terminal services (RDP) sessions qwinsta list sessions
qwinsta /server:host
rwinsta sessionid set session
rwinsta /server:host id
note: equivalent to 'query session'
diskpart Discs core Manage disc, partitions, and volumes (scriptable disc utility) list disk / partition / volume
select disk N
clean wipe partition table
create partition primary
format fs=ntfs quick
assign letter=X
extend / shrink desired = N
note:
chkdsk Discs core Check disk for filesystem machines and bad sections /f fix filesystem error
/r also locale bad sectors
/x force dismount before scan
/scan online scan (NTFS)
/spotfix targeted fix on next boot
/b re-evaluate bad clusters (with /r)
fsutil Discs core Filesystem utility for advanced MMFS, USN, links, and quotes fsinfo drives list drives
volume diskfree C: free/total bytes
behind the set tunnel
usn USN journal management
hardlink create create hard link
file createnew name N creation N-byte file
format Discs core Format a disk volume with a filesystem /fs:NTFS-FAT32-exFAT filesystem type
/q quick format
/v:
/a:
/l large FRS (NTFS)
/p:
mountvol Discs core Mount or unmount a volume at a drive letter or MMFS bear mountvol list mounted volumes
mountvol X: \\? \Volume{GUID}\mount
mountvol X: /d unmount drive
/r remove orphaned points
/n / /e disabled/enable auto-mount
Get-Disk Discs modern PowerShell - retrieve physical disk objects and health -Number N filter by disk number
-Friendly name
Initialize-Disk -PartitionStyle GPT
√ Set-Disk - IsOffline $false
HealthStatus disk health summary
Get-Volume Discs modern PowerShell - retrieve volumes with size, filesystem, health -DriveLetter C
-FileSystem MMFs/ReFS/FAT32
-FileSystemLabel name
- OfflineScanAndFix
√ Optimize-Volume - Defrag
New-Partition / Format-Volume Discs modern Power New-Partition - DiskNumber N - UseMaximumSize
-DriveLetter X assign letter
- AssignDriveLetter auto-assign
Format-Volume -FileSystem MMFS
-NewFileSystemLabel label
- Confirm:
defrag Discs core Analyze and Defragment Volumes Defragment drive
/a analysis only
/o optimal (defrag + slab consolidated)
/l retrim SSD
/x free-space consolidation
/v verbose output
convert Discs core Convert FAT/FAT32 volume to MMFs in-place C: /fs:ntfs basic conversion
/v verbose
/cvtarea:file reserve MFT space
/nosecurity no security descriptors
/x force dismount first
note: one-way; cannot convert to FAT
vssadmin Discs core Manage Volume Shadow Copies and storage providers list shadows show all snapshots
list shadowstorage storage location
create shadow / for=C:
delete shadows / for=C: /oldest
resize shadowstorage /on=C: /maxsize=10GB
list writers list VSS writers
Get-PhysicalDisk Discs modern PowerShell - retrieve physical disc objects (Storage Spacesera) -Friendly name
-MediaType SSD/HDD/SCM
-HealthStatus Healthy/Warning
√ Get-StoragePool Associated Pool
Reset-PhysicalDisk brand back online
tar Archives core Built-in BSD tar - create/extract archives (.tar, .tar.gz, .zip) -c create archive
-x extract archive
-f file archive filename
-z gzip filter
-v verbose listing
-t list content without extracting
--strip-compponents N strip pat level
note: built into Windows 10 1803+
compact Archives core View and change MMFS file compression /c compress files
/u uncompress files
/s course subdirectories
/a display hidden/system files
(i)
/exe:LZX√XPRESS algorithm choice
expand Archives core Expand pressed CAB/MSU/cabinet archives -r rename expanded files
-i ignore directory structure
-f:* files to expand (childcards)
-d display content only
source most basic expansion
Compress-Archive Archives modern PowerShell - create or append to .zip archives -Path files/dir to include
- DestinationPath file.zip
-Update add/update entities
- Force over
-CompressionLevel Fastest/Optimal
Expand-Archive Archives modern PowerShell - extract .zip archive contents -Path file.zip
- DestinationPath dir
- Force over
-PassThru emit extracted items
7z (7-Zip CLI) Archives modern 7-Zip - high-ratio compression with 7z, zip, tar, gz support a archive. 7z files added to archive
x archive. 7z extract protecting paths
e archive. 7z extract flat
l archive. 7z list content
t archive. 7z test integrity
-p set password
-mx=9 max compression
-mhe=on encrypt heads
nmap Intrusion test security Network Scanner - host discovery, port scan, service detection -sV detect service versions
-sC run default NSE scripts
-O enable OS fingerprinting
-p specific port range (e.g. 1-65535)
-A aggressive: OS+version+scripts+traceroute
--script run specific NSE script
-oN / -oX output to file
-Pn slip host discovery (size up)
-sS SYN stealth scan (admin)
certutil Intrusion test security Certificate Services tool - inspection certs, hash files, base64 encode -hashfile file SHA256 hash a file
-encode in out base64 encode
-decode in out base64 decode
-store -enterprise Root list Root certs
-verify -urlfech cert.cer
-dump inspection certificate
note: also used by actors as LOLBin
openssl Intrusion test security TLS/SSL toolkit - certificates, keys, entry, and testing s client -connect host:443 test TLS
x509 -in cert.pem -text inspect cert
genrsa -out key.pem 4096 generate RSA key
req -new generation CSR
enc -aes-256-cbc encrypt/decrypt
verify -CAfile validate chain
speak benchmark ciphers
ssh-keygen Intrusion test security Generation, management, and convert SSH authentication keys -t ed25519 modern key type (recommended)
-b 4096 bit length (for RWA)
-C 'comment' add identifying comment
-f file output file path
-p change or remove
-l print
gpg Intrusion test security GNU Privacy Guard for Windows - encrypt, sign, verify --gen-key generic key pair
-e -r recipient encrypt file
--decrypt decrypt .gpg file
-s create detailed signature
--verify verify signature file
--armo ASCII-armored output
--export / --import key management
PsExec (Sysinternals) Intrusion test security Executive processes on remote systems with full I/O resolution \\host -u user -p pass cmd
-s run as SYSTEM
-i interactive (show GUI)
-d do not wait for process
-c copy local exe to remote
-h elevated token
note:
mimikatz Intrusion test security Windows critical extraction toolkit (RED TEAM / LAB ONLY) privacy::debug aquire SeDebug
sekirlsa::logonpasswords dump LSASS creds
lsadump:
kerberos::
note: blocked by Defender; LAB USE ONLY
legal:
hashcat Intrusion test security GPU-qualified password hash cracking tool -m hash type (1000=NTLM, 13100=Kerberos TGS)
-a image mode (0=dict, 3=bruteforce)
-w workload profile (12.2006,4)
-r rules applicable rules file
--show show already cracked hashes
--status live progress update
john (JtR) Intrusion test security CPU-based password hash cracker with auto-detection --wordlist dictionary file path
--rolls apply mangling rules
--format=ntlm specific hash type
--show display cracked passwords
--fork N parallel processes
note: Cygwin or native Win64 built
Defender (Set-MpPreference) Intrusion test security PowerShell - configure Microsoft Defender Antivirus Get-Mp
Set-MpPreference -DisableRealtimeMonitoring
Add-MpPreference -ExclusionPath path
Start-MpScan -ScanType QuickScan/FullScan
Update-Mp
Get-MpThreat
docker Containers modern Build, ship, and run application containers (Docker Desktop) run -d run container detached
run --rm auto-remove on exit
exec -it open shell in running container
window -f follow container log stream
inspect detailed JSON metadata
ps -a list all containers
building -t building image with tag
network ls / inspection management networks
volume ls/inspect manage volumes
system usage
kubectl Containers modern CLI to manage Cubanetes clusters and jobs get pot/svc/nodes list resources
describe pod
applicable -f manifest.yaml employment/update
exec -it pod -- powershell shell into pod
window -f pod follow log stream
top node / top pod resource use
rollout status/undo employment control
port-ward forward local port to pod
config use-text
podman Containers modern Rootless daemonless OCI engine - Windows port via WSL run --rm auto-remove after exit
--user 1000 run as non-root UID
--pod attach to pod group
-v single mount host volume
generale kube export as Kubernetes Yaml
play kube run from Cubanettes YAML
helm Containers modern Cubanettes package manager for tempered chart employments install release
upgrade --install upsert employment
rollback release
list show all requested releases
value
repo add / update management chart repos
template tender manifests locally
wsl Containers modern Windows Subsystem for Linux - run Linux distros and containers --list --verbose show distros and state
--install -d Ubuntu install distro
--set-default name
--set-version name 2 Switch to WSL2
--shutdown stop all distros
--export / --import backup/restore
note: required for Docker Desktop on Windows

System audit

The checks are grouped by the auditor's questions: what happened, who has access, what starts by itself, what is exposed to the network, whether the system is updated and protected and whether the configuration matches recommendations. All commands only read and change nothing. Run PowerShell as Administrator. If Get-WinEvent answers "No events were found", there are no matching events in the log. Save the output as a baseline - in the next audit, changes against it stand out more than the values themselves.

How an audit runs from planning to the report is explained in the security audit guide.

Logs and sign-ins

  • What is logged at all

    auditpol /get /category:*

    What to look for: No Auditing for Logon/Logoff, Account Management, Policy Change or Detailed Tracking means those events will not be in the log, and the checks below will find nothing. Recommended: Success and Failure.

  • Failed logons (4625)

    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddDays(-1)} | ForEach-Object { $_.Properties[19].Value } | Group-Object | Sort-Object Count -Descending

    What to look for: The result is grouped by source address. Hundreds of attempts from one address are password guessing, many addresses with one username are password spraying.

  • Successful remote logons (4624)

    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624; StartTime=(Get-Date).AddDays(-1)} | Where-Object { $_.Properties[8].Value -in 3, 10 } | Select-Object TimeCreated, @{n='User'; e={$_.Properties[5].Value}}, @{n='IP'; e={$_.Properties[18].Value}}

    What to look for: Type 10 is RDP, type 3 is a network logon (shared folders, remote management). Look for accounts and addresses that should not connect, and logons at night.

  • Account and group changes

    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4720,4726,4732,4738} -MaxEvents 50 | Format-List TimeCreated, Id, Message

    What to look for: 4720 - account created, 4726 - deleted, 4738 - changed, 4732 - account added to a local group (e.g. Administrators). Every change should match a known request.

  • New services (7045)

    Get-WinEvent -FilterHashtable @{LogName='System'; Id=7045} -MaxEvents 30 | Format-List TimeCreated, Message

    What to look for: A new service is a common trace of persistence and remote execution (PsExec, for example, creates one). Suspicious: a path in Temp or ProgramData and a command line with powershell -enc.

  • Cleared logs (1102, 104)

    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=1102}Get-WinEvent -FilterHashtable @{LogName='System'; Id=104}

    What to look for: 1102 - security log cleared, 104 - another log cleared. Outside planned maintenance, this almost always means covering tracks.

  • PowerShell script blocks (4104)

    Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} -MaxEvents 50 | Format-List TimeCreated, Message

    What to look for: Shows the content of executed scripts, including those decoded from -EncodedCommand. Suspicious: DownloadString, IEX, FromBase64String, AMSI bypass. Full logging is enabled by the Turn on PowerShell Script Block Logging group policy, without it only suspicious blocks are recorded.

  • Log size and retention

    Get-WinEvent -ListLog Security, System, 'Microsoft-Windows-PowerShell/Operational' | Format-Table LogName, MaximumSizeInBytes, RecordCount, LogMode

    What to look for: The default 20 MB security log on a busy server is overwritten in days or even hours. An investigation needs weeks, so increase the size or forward logs to a central system (SIEM).

Accounts and privileges

  • Local accounts

    Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, PasswordRequired

    What to look for: Enabled accounts nobody uses and accounts with PasswordRequired False. The built-in Guest account must be disabled.

  • Administrators

    Get-LocalGroupMember -SID S-1-5-32-544

    What to look for: S-1-5-32-544 is the Administrators group in any Windows language. Every member needs a justification, use a standard account for daily work.

  • Password and lockout policy

    net accounts

    What to look for: Lockout threshold Never means passwords can be guessed without limit. A minimum password length below 12 characters is weak.

  • User rights assignments

    secedit /export /cfg $env:TEMP\secpol.inf /areas USER_RIGHTSSelect-String -Path $env:TEMP\secpol.inf -Pattern 'SeDebugPrivilege|SeBackupPrivilege|SeRemoteInteractiveLogonRight'

    What to look for: SeDebugPrivilege and SeBackupPrivilege allow reading other processes' memory and any file, so they should be held only by administrators (*S-1-5-32-544). SeRemoteInteractiveLogonRight controls who may log in over RDP.

Autostart and scheduled tasks

  • Run keys in the registry

    Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run', 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'

    What to look for: Programs that start at logon. Suspicious: a path in AppData or Temp, a random name, powershell or mshta on the command line.

  • Scheduled tasks outside Microsoft

    Get-ScheduledTask | Where-Object TaskPath -notlike '\Microsoft\*' | Select-Object TaskName, TaskPath, State(Get-ScheduledTask -TaskName <nosaukums>).Actions

    What to look for: Every task should have a known purpose. The second command shows what the task runs - a script in a user folder or an encoded PowerShell command must be investigated.

  • Auto-start services outside the Windows folder

    Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.PathName -notmatch '\\Windows\\' } | Select-Object Name, PathName, StartName

    What to look for: Services from Program Files are usually installed programs. A path to a user folder or Temp, and a path with spaces but no quotes (unquoted service path), must be investigated.

  • All autostart locations in one list

    autorunsc -accepteula -a * -c -h -s -m > autoruns.csv

    What to look for: Sysinternals Autoruns checks more than a hundred autostart locations. The -m flag hides Microsoft entries and -s verifies signatures - an unsigned entry is the first thing to look at.

Services

  • Running services

    Get-Service | Where-Object Status -eq 'Running' | Sort-Object DisplayName | Select-Object Name, DisplayName, StartType

    What to look for: Every service should have a known purpose. Third-party remote access tools (TeamViewer, AnyDesk) that nobody owns up to are a finding.

  • Automatic but stopped

    Get-CimInstance Win32_Service -Filter "StartMode='Auto' AND State<>'Running'" | Select-Object Name, State, ExitCode

    What to look for: Some services start delayed or on a trigger, so stopped is not an error by itself. A non-zero ExitCode means a crash - especially important for Defender, logging and backup services.

  • Which account a service runs as

    Get-CimInstance Win32_Service | Select-Object Name, StartName, State | Sort-Object StartName

    What to look for: LocalSystem has the broadest rights. A service running as a domain administrator leaves that account's credentials on every machine where it runs.

  • Which service holds a port

    Get-NetTCPConnection -LocalPort <ports> -State Listen | ForEach-Object { Get-CimInstance Win32_Service -Filter "ProcessId=$($_.OwningProcess)" } | Select-Object Name, PathName

    What to look for: A port with no service means a process started some other way - check its path and signature.

Network exposure

  • Listening ports

    Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, @{n='Process'; e={(Get-Process -Id $_.OwningProcess).ProcessName}} | Sort-Object LocalPort

    What to look for: 0.0.0.0 or :: means the port is reachable from the network. RDP (3389), SMB (445) and WinRM (5985, 5986) must not be open to the internet.

  • Firewall profiles

    Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, LogBlocked

    What to look for: All three profiles should be enabled, and incoming traffic blocked by default (NotConfigured means Block). LogBlocked False means blocked connections are not visible anywhere.

  • Shared folders and SMBv1

    Get-SmbShareGet-SmbServerConfiguration | Select-Object EnableSMB1Protocol

    What to look for: Shares nobody knows about. SMBv1 must be disabled - it was exploited by WannaCry (MS17-010).

  • Remote Desktop (RDP)

    Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnectionsGet-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name UserAuthentication

    What to look for: The value fDenyTSConnections 0 means RDP is enabled. If it is needed, UserAuthentication should be 1 (NLA - authentication before the session is created).

Integrity and updates

  • Latest updates

    Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10

    What to look for: If the latest update is older than a month, the system has publicly known vulnerabilities. Get-HotFix does not show everything, for example Defender and driver updates.

  • Microsoft Defender status and exclusions

    Get-MpComputerStatus | Select-Object AMServiceEnabled, RealTimeProtectionEnabled, AntivirusSignatureLastUpdatedGet-MpPreference | Select-Object ExclusionPath, ExclusionProcessGet-MpThreatDetection

    What to look for: Real-time protection should be on and signatures no older than a day or two. Attackers often add their own folder to the exclusions. Get-MpThreatDetection also shows past detections the user may have missed.

  • Disk encryption

    Get-BitLockerVolume | Select-Object MountPoint, VolumeStatus, ProtectionStatus

    What to look for: ProtectionStatus Off on a laptop means a stolen disk can be read without a password.

  • System file integrity

    sfc /verifyonly

    What to look for: Checks protected system files without repairing anything. Findings are in the log C:\Windows\Logs\CBS\CBS.log.

  • Unsigned executables in user folders

    sigcheck -accepteula -u -e -s C:\Users

    What to look for: Sysinternals Sigcheck lists executables without a digital signature. An unsigned program in a user folder is not proof, but it is the first thing to check.

Configuration

  • Applied Group Policy

    gpresult /h $env:TEMP\gpresult.html

    What to look for: The report shows which policies, from which object, are actually in effect. If an expected policy is not there, it does not apply to this computer.

  • LSASS protection and Credential Guard

    Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -Name RunAsPPL -ErrorAction SilentlyContinue(Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard).SecurityServicesRunning

    What to look for: RunAsPPL 1 or 2 protects the LSASS process against reading passwords from memory (e.g. with mimikatz). A SecurityServicesRunning value of 1 means Credential Guard is running.

  • Legacy authentication protocols

    Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -Name LmCompatibilityLevel -ErrorAction SilentlyContinueGet-ItemProperty 'HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient' -Name EnableMulticast -ErrorAction SilentlyContinue

    What to look for: LmCompatibilityLevel 5 allows NTLMv2 only. EnableMulticast 0 disables LLMNR, which an attacker on the local network uses to capture password hashes. If the value is missing, the default applies and LLMNR is enabled.

Troubleshooting

Start with two questions: what changed, and does the problem affect one user or everyone. Then work up the layers from the bottom - interface and address, route, DNS and only then the service. The commands only read the state, the note says what to change.

Network

  • Is the interface up with an address and a gateway

    Get-NetAdapter | Select-Object Name, Status, LinkSpeedGet-NetIPConfigurationipconfig /all

    What to do: Status Disconnected means there is no link. A 169.254.x.x address means DHCP did not answer, and without an IPv4DefaultGateway the computer reaches only its own subnet.

  • Are the target and port reachable

    Test-NetConnection <mērķis>Test-NetConnection <mērķis> -Port 443

    What to do: PingSucceeded False but TcpTestSucceeded True means only ping is blocked. Both False - the problem is in the network or a firewall. If ping answers but TCP does not, nothing listens on the port or the target's firewall blocks it.

  • Where the path breaks

    tracert -d <mērķis>Get-NetRoute -DestinationPrefix 0.0.0.0/0

    What to do: The last answering hop shows how far the packet gets. Several default routes (for example a VPN) can send traffic the wrong way - the one with the lowest RouteMetric wins.

  • Is the firewall blocking

    Get-NetConnectionProfile | Select-Object Name, InterfaceAlias, NetworkCategoryGet-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundActionGet-NetFirewallRule -Enabled True -Direction Inbound | Where-Object Action -eq 'Block' | Select-Object DisplayName

    What to do: The Public profile restricts inbound connections the most, and a domain network detected as Public is a common culprit. Enable the needed rule rather than turning off the firewall.

  • Proxy server

    netsh winhttp show proxyGet-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | Select-Object ProxyEnable, ProxyServer, AutoConfigURL

    What to do: The browser uses the user's proxy settings, while services and Windows Update use WinHTTP. If the browser works but a service or updates do not (or the other way round), these two settings differ.

DNS

  • Which DNS server is in use

    Get-DnsClientServerAddress -AddressFamily IPv4

    What to do: If the server is wrong or unreachable, domains are not found even though the network works. A domain-joined computer must point DNS to the domain controllers, not a public server - otherwise sign-in and group policy fail.

  • What the DNS server answers

    Resolve-DnsName <domēns> -NoHostsFileResolve-DnsName <domēns> -Server 1.1.1.1

    What to do: DNS_ERROR_RCODE_NAME_ERROR means the domain does not exist, DNS_ERROR_RCODE_SERVER_FAILURE that the server could not answer. If the public server answers but the local one does not, the fault is in local DNS. A public server does not know internal domains, so a difference there is normal.

  • Cache, hosts file and VPN rules

    Get-DnsClientCache | Select-Object -First 20Get-Content $env:windir\System32\drivers\etc\hostsGet-DnsClientNrptPolicy

    What to do: A stale entry in the cache or hosts file overrides DNS, ipconfig /flushdns clears the cache. NRPT rules (VPN, DirectAccess) send specific domains to another server - if only some domains fail, look there.

Services

  • State, start type and dependencies

    Get-Service <serviss> | Select-Object Name, Status, StartTypeGet-Service <serviss> -RequiredServicessc.exe qc <serviss>

    What to do: sc.exe qc shows the account and executable path - a wrong path or an expired service account password are the most common causes. If one of the RequiredServices is stopped, the service fails with error 1068.

  • Service Control Manager errors

    Get-WinEvent -FilterHashtable @{LogName='System'; ProviderName='Service Control Manager'; Level=2} -MaxEvents 20 | Format-List TimeCreated, Id, Message

    What to do: 7000 - failed to start, 7009 - timeout, 7023 and 7024 - the service stopped with an error, 7031 and 7034 - crash. The message contains a Windows error code that net helpmsg <code> explains.

  • Application crash

    Get-WinEvent -FilterHashtable @{LogName='Application'; Id=1000,1026} -MaxEvents 10 | Format-List TimeCreated, Message

    What to do: 1000 names the crashed module (DLL), 1026 the .NET exception. It shows whether the fault is in the application or a shared library.

Disk and file system

  • Is the disk full

    Get-Volume | Select-Object DriveLetter, FileSystemLabel, SizeRemaining, Size

    What to do: Less than 10% free space on the system disk slows updates and can stop them.

  • What takes up the space

    Get-ChildItem C:\ -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object { [pscustomobject]@{Folder=$_.FullName; GB=[math]::Round((Get-ChildItem $_.FullName -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum/1GB,1)} } | Sort-Object GB -Descending | Select-Object -First 10

    What to do: Common culprits: WinSxS, downloads, temporary files. Clean up with Disk Cleanup or Storage Sense, not by deleting system folders.

  • Is the disk healthy

    Get-PhysicalDisk | Select-Object FriendlyName, MediaType, HealthStatus, OperationalStatusGet-WinEvent -FilterHashtable @{LogName='System'; ProviderName='disk'; Id=7,51,153} -MaxEvents 20 | Format-List TimeCreated, Id, Messagechkdsk C: /scan

    What to do: A HealthStatus other than Healthy and events 7 (bad block), 51 or 153 (retried I/O) are a sign of damage - back up first. chkdsk /scan only checks and does not stop the system.

Performance

  • What loads the CPU

    Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, Id, CPU

    What to do: The CPU column is total processor time since start, not current load - compare two readings or look at Get-Counter.

  • What takes up memory

    Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{n='MB'; e={[math]::Round($_.WorkingSet64/1MB)}}

    What to do: A process whose memory grows for hours may be a leak. Restart it and watch whether it repeats.

  • Current load

    Get-Counter '\Processor(_Total)\% Processor Time', '\Memory\Available MBytes', '\PhysicalDisk(_Total)\Avg. Disk sec/Transfer' -SampleInterval 2 -MaxSamples 3

    What to do: An average disk response time above 0.02 s (20 ms) for long with low CPU means the system is waiting for the disk. On a localized Windows the counter names are translated - if the command cannot find them, Get-Counter -ListSet * shows the names.

Boot and updates

  • Unexpected shutdown

    Get-WinEvent -FilterHashtable @{LogName='System'; Id=41,6008} -MaxEvents 10 | Format-List TimeCreated, Id, Message

    What to do: 41 (Kernel-Power) means the system shut down uncleanly but does not name the cause itself. If its BugcheckCode is 0, it was a power loss, overheating or a hard freeze, if not 0 - a blue screen.

  • Blue screen (BSOD)

    Get-WinEvent -FilterHashtable @{LogName='System'; Id=1001; ProviderName='Microsoft-Windows-WER-SystemErrorReporting'} -MaxEvents 5 | Format-List TimeCreated, MessageGet-ChildItem C:\Windows\Minidump -ErrorAction SilentlyContinue

    What to do: The message contains the BugCheck code. A repeated code after a driver update points to that driver.

  • What slows down boot

    Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Diagnostics-Performance/Operational'; Id=100} -MaxEvents 5 | Format-List TimeCreated, MessageGet-CimInstance Win32_StartupCommand | Select-Object Name, Command, Location

    What to do: Event 100 shows the boot duration, 101 and onwards name the applications, drivers and services that slowed it down. Disable auto-start programs in Task Manager (Startup apps).

  • What was installed recently

    Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10Get-WinEvent -FilterHashtable @{LogName='System'; ProviderName='Microsoft-Windows-WindowsUpdateClient'} -MaxEvents 10 | Format-List TimeCreated, MessageTest-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'

    What to do: If the problem began after an update, this list names the candidate. True from the last command means an update is waiting for a restart. Uninstall it via Settings - Windows Update - Update history.

  • Are system files corrupted

    sfc /verifyonlyDISM /Online /Cleanup-Image /ScanHealth

    What to do: Corrupted system files after a failed update cause odd errors. If the check finds them, run DISM /RestoreHealth first, then sfc /scannow (both need administrator rights).

Access and time

  • Why Access denied

    Get-Acl <ceļš> | Format-List Owner, AccessToStringwhoami /groups

    What to do: A Deny entry overrides an Allow. If a group was added recently, the user must sign in again for it to take effect.

  • Account locked or password expired

    net user <lietotājs> /domainGet-WinEvent -FilterHashtable @{LogName='Security'; Id=4740} -MaxEvents 10 | Format-List TimeCreated, Message

    What to do: net user /domain shows whether the account is active and when the password expires (without /domain for a local account). Event 4740 is written on the domain controller, not the user's computer, and names the computer that locked the account - often an old password on a mapped drive, a scheduled task or a phone.

  • Trust relationship with the domain

    nltest /sc_query:<domēns>nltest /dsgetdc:<domēns>

    What to do: The message The trust relationship between this workstation and the primary domain failed means the computer account password no longer matches the domain. nltest shows whether the secure channel works and which domain controller the computer finds. Repair with Test-ComputerSecureChannel -Repair or by rejoining the domain.

  • Is the time correct

    w32tm /query /statusw32tm /query /source

    What to do: A time skew over 5 minutes breaks Kerberos domain sign-in and TLS. In a domain the source should be the domain controller.

Penetration testing

Penetration testing checks defences from an attacker's point of view. The section follows the stages: reconnaissance, web surface, TLS, passwords and availability resilience. Every entry carries its defence alongside - a penetration test is only worth doing if the findings get fixed. The tools usually run from the tester's machine (often Kali Linux), so they are the same for both systems.

The attack surface and how to reduce it is explained in the attack surface guide.

This section is for educational purposes. Use these methods ONLY against systems you own or have written permission to test. Unauthorised scanning and testing is a criminal offence. Replace <target> with your own test system.

Reconnaissance and port scanning

  • Host and open-port discovery

    nmap -sn 10.0.0.0/24nmap -sV -p- <mērķis>

    Defence: Every open port is an entry point. Close unused services, bind management and databases to 127.0.0.1, and put anything exposed to the internet behind a firewall. The same view is in the network area of the system audit.

  • Service and version detection

    nmap -sV --script=banner <mērķis>whatweb <url>

    Defence: A version tells the attacker which public vulnerability to look up. Remove version-revealing headers (Server, X-Powered-By) and keep services patched.

  • DNS and zone transfer

    dig AXFR @<ns> <domēns>dnsrecon -d <domēns>

    Defence: An open zone transfer hands over the entire internal name list. Deny AXFR to unauthorised peers and keep internal hosts out of public DNS.

Web applications

  • Scanning for known vulnerabilities

    nuclei -u <url>nikto -h <url>

    Defence: Scanners look for publicly known vulnerabilities and misconfiguration. Defence: a web application firewall (WAF) in front, input validation on the server, and regular patching.

  • Probing for hidden files and paths

    ffuf -w <wordlist> -u <url>/FUZZgobuster dir -u <url> -w <wordlist>

    Defence: The attacker tries to find .env, .git and backups. Never put secrets under the webroot, and reject these paths at the web server edge before they reach the application.

  • Intercepting proxy (Burp, ZAP)

    # Burp Suite / OWASP ZAP - manuāla pieprasījumu pārtveršanazap-baseline.py -t <url>

    Defence: An intercepting proxy shows that client-side checks can be bypassed. Enforce every gate on the SERVER, not only in the browser, and use CSRF tokens and ownership checks.

TLS and encryption

  • TLS configuration check

    testssl.sh <host>:443sslscan <host>

    Defence: Disable protocols below TLS 1.2 and weak ciphers, enable HSTS. An obsolete protocol is a slow but sure path to a man-in-the-middle attack.

  • Certificate check

    openssl s_client -connect <host>:443 -servername <host>

    Defence: Check that the certificate is valid, not expired and matches the domain. Automate renewal so it does not expire silently.

Password and hash auditing

  • Hash strength audit (on your own hashes)

    hashcat -m <režīms> hashes.txt <wordlist>john --wordlist=<wordlist> hashes.txt

    Defence: Run it against YOUR OWN extracted hashes to see how fast weak passwords fall. Defence: a strong, slow hashing algorithm, sufficiently long passwords, and account lockout after failed attempts.

  • Login resilience against guessing

    # autorizēts tests pret SAVU pieteikšanās galapunktunmap -p 80,443 --script http-brute <mērķis>

    Defence: Rate limiting and account lockout make direct guessing unprofitable. Against distributed guessing from many addresses you need a reputation layer that blocks addresses by their behaviour elsewhere.

Availability resilience (DoS)

  • Slow HTTP resilience (Slowloris class)

    slowhttptest -c 500 -H -u <url>

    Defence: Slowloris holds connections open with slowly sent headers. Defence: request timeouts and a per-IP concurrent connection limit. Test ONLY your own test environment.

  • Load resilience

    ab -n 10000 -c 100 <url># vai slodzes ģenerators (wrk, Locust) - TIKAI pret savu vidi

    Defence: Measure how many requests per second the system can take. Defence: a cache for anonymous pages and rate limits; save the measured baseline and compare after every change.