Skip to content

Latest commit

 

History

History
237 lines (158 loc) · 12.9 KB

File metadata and controls

237 lines (158 loc) · 12.9 KB

PowerShell IT Support Toolkit — Command Reference

1. Introduction

This document serves as a practical PowerShell command reference for the PowerShell IT Support Toolkit. The commands detailed here are primarily diagnostic, administrative, and troubleshooting-oriented, providing the foundation for the toolkit's automated scripts.

While executing these commands directly in a PowerShell console provides granular control and immediate feedback, using the corresponding toolkit scripts (such as Get-SystemInfo.ps1 or Get-Processes.ps1) ensures that output is consistently formatted, errors are safely isolated, and actions are properly logged according to project standards.

WARNING: Administrative commands that modify system state, delete files, or terminate processes must be executed with extreme care. Always validate paths and target objects before performing destructive actions.


2. PowerShell Basics

Understanding the PowerShell environment is crucial for effective troubleshooting.

  • $PSVersionTable: Displays the current PowerShell version and environment details. Useful for diagnosing script compatibility issues.
  • Get-Command: Lists available commands, functions, and aliases on the system.
  • Get-Help: Retrieves syntax, detailed explanations, and examples for PowerShell commands.
  • Get-Member: Inspects the properties and methods of an object. Critical for understanding what data is available in the pipeline.
  • Select-Object: Selects specific properties of an object or limits the number of returned objects (e.g., -First 10).
  • Where-Object: Filters objects from the pipeline based on specific property values or conditions.
  • Sort-Object: Sorts pipeline objects by one or more property values.
  • Format-Table: Formats output as a human-readable table in the console.

3. System Information

Gathering core system information is usually the first step in diagnosing OS-level issues.

  • Get-ComputerInfo: Retrieves comprehensive system and hardware information.
  • Get-CimInstance Win32_OperatingSystem: Queries WMI/CIM for precise operating system details, including build numbers and last boot time.
  • $env:COMPUTERNAME: Immediately returns the local computer's hostname.
  • $env:USERNAME: Returns the name of the currently logged-in user running the console.
  • $env:USERPROFILE: Returns the absolute path to the current user's profile directory.

4. Running Processes

Investigating system performance relies heavily on process enumeration.

  • Get-Process: Lists all running processes accessible to the current user context.
  • Get-Process -Name <Name>: Retrieves specific processes by their executable name.
  • Get-Process -Id <PID>: Retrieves a single process by its unique Process ID.
  • Get-Process | Sort-Object CPU -Descending: Sorts processes to identify those consuming the most CPU resources.
  • Get-Process | Get-Member: Inspects available process properties, such as .WorkingSet (memory) or .Description.

CAUTION: While diagnostic commands like Get-Process are safe, administrative commands like Stop-Process are highly destructive. Never blindly terminate critical system processes to resolve performance issues.


5. Windows Services

Managing and diagnosing background services is a core IT Support function.

  • Get-Service: Lists all services registered on the system.
  • Get-Service -Name <Name>: Retrieves the status of a specific service.
  • Get-Service | Where-Object Status -eq 'Running': Filters the list to show only currently running services.
  • Get-Service | Sort-Object DisplayName: Alphabetizes services for easier human reading.

CAUTION: Administrative actions such as Start-Service, Stop-Service, and Restart-Service modify system state. Stopping a service with unknown dependencies can crash critical applications or disconnect network sessions.


6. Storage and Disk Management

Investigating storage exhaustion and logical drives.

  • Get-PSDrive -PSProvider FileSystem: Lists all mounted filesystem drives and their free/used capacity.
  • Get-CimInstance Win32_LogicalDisk: Queries detailed hardware-level logical disk properties.
  • Get-ChildItem: Lists files and directories in a specified path.
  • Get-Item: Retrieves the object properties of a specific file or directory.
  • Measure-Object -Property Length -Sum: Calculates the total size of files piped to it.

CAUTION: Remove-Item is a destructive command. When deleting files, always target explicit files or strictly controlled temporary directories. Never execute recursive deletions against system roots (C:\) or critical application folders.


7. Temporary File Cleanup

Safely recovering disk space by purging temporary files requires precise scoping and enumeration.

  • $env:TEMP: Points to the current user's temporary directory.
  • [System.IO.Path]::GetTempPath(): A safe .NET method to resolve the temp directory.
  • Get-ChildItem -Path $env:TEMP -Recurse -File: Recursively enumerates all files within the temp folder.
  • File Age Filtering: Use Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } to identify files older than a week.
  • Remove-Item -Force -ErrorAction SilentlyContinue: Deletes the files, silently bypassing locked/inaccessible files currently in use by applications.

Safety Principle: Enumeration and inspection must always happen before deletion. Furthermore, cleanup scripts must delete the contents of a directory, never the target directory itself.


8. Networking and Connectivity

These commands bridge native Windows executables and modern PowerShell cmdlets for network diagnostics.

Basic Network Configuration

  • Get-NetIPConfiguration: Retrieves comprehensive IP, DNS, and Gateway configurations.
  • Get-NetIPAddress: Lists specific IPv4/IPv6 addresses assigned to interfaces.
  • Get-NetAdapter: Displays physical and virtual network adapters and their link status.

Connectivity Testing

  • Test-Connection: The PowerShell native equivalent of Ping (ICMP).
  • Test-NetConnection: Tests TCP port connectivity (e.g., to a specific website or server on port 443).

DNS Troubleshooting

  • Resolve-DnsName: Resolves a hostname to an IP address, providing detailed DNS record information.
  • Clear-DnsClientCache: Flushes the local DNS resolver cache to fix stale records.

Routing

  • Get-NetRoute: Displays the local IP routing table.

Useful Native Windows Commands

While PowerShell cmdlets return objects, traditional native executables remain highly effective for rapid diagnostics:

  • ipconfig /all: Quickly dumps all TCP/IP configurations.
  • ping <target>: Rapid ICMP reachability testing.
  • tracert <target>: Traces the hop-by-hop route to a destination.
  • nslookup <target>: Queries external DNS servers directly.

9. Event Logs

Extracting actionable intelligence from Windows Event Logs.

  • Get-WinEvent -ListLog *: Lists all available event logs on the system.
  • Get-WinEvent -LogName System -MaxEvents 50: Retrieves the 50 most recent events from the System log.
  • Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2}: Efficiently filters the Application log for Error-level events.
  • Where-Object Id -eq 1000: Filters a pipeline of events for a specific Event ID (e.g., application crashes).

NOTE: Always use -MaxEvents or -FilterHashtable when querying event logs. Querying large logs without limits is computationally expensive and can hang the console.


10. User and Account Information

Read-only diagnostic commands for identifying identity and access.

  • $env:USERNAME: Quickly identifies the logged-in user.
  • [System.Security.Principal.WindowsIdentity]::GetCurrent(): Retrieves the exact security context running the current PowerShell host.
  • Get-LocalUser: Lists all user accounts local to the machine.
  • Get-LocalGroupMember -Group "Administrators": Lists accounts with local administrative rights.

NOTE: These commands are strictly for read-only information gathering to assist in permissions troubleshooting.


11. File and Directory Operations

Handling the filesystem safely and predictably.

  • Get-ChildItem -Recurse: Deeply enumerates directory trees.
  • Test-Path: Returns $true or $false depending on whether a path exists. Always use this before accessing files.
  • Resolve-Path: Expands relative paths or wildcards into absolute paths.
  • Join-Path: Safely concatenates directory and file strings using correct backslashes.

BEST PRACTICE: Use -LiteralPath instead of -Path when supplying exact filesystem paths. This prevents PowerShell from accidentally interpreting bracket characters [] in directory names as wildcard regex syntax.


12. System Diagnostics

Holistic commands used to isolate OS-level anomalies.

  • CPU/Memory: Get-Process | Sort-Object WorkingSet -Descending
  • Disk Health: Get-CimInstance Win32_LogicalDisk | Where-Object FreeSpace -lt 5GB
  • Network: Test-NetConnection -ComputerName google.com -InformationLevel Detailed
  • Boot Info: Get-CimInstance Win32_OperatingSystem | Select-Object LastBootUpTime

13. Output, Filtering, and Reporting

Understanding how to manipulate data flows in PowerShell.

  • Data Transformation: Use the Pipeline (|), Where-Object, and Select-Object to mold raw data into useful structures. ForEach-Object is used to iterate over pipeline items.
  • Structured Exports: Always use structured objects ([PSCustomObject]) when exporting data. Use Export-Csv or ConvertTo-Json / Out-File to save data programmatically so it can be parsed later.
  • Display Formatting: Use Format-Table or Format-List only for human-readable console presentation. Never attempt to export or parse the output of a Format-* cmdlet.

14. Error Handling

Building reliable scripts requires understanding failure states.

  • $ErrorActionPreference: A global variable dictating how PowerShell reacts to non-terminating errors (e.g., 'Stop', 'Continue', 'SilentlyContinue').
  • -ErrorAction: A per-cmdlet override for handling specific command failures gracefully.
  • try / catch / finally: The standard structural block for handling terminating exceptions.
  • throw: Explicitly generates a terminating exception.
  • $?: A boolean indicating if the last PowerShell command succeeded.
  • $LASTEXITCODE: An integer indicating the exit code of the last executed native executable (e.g., ping.exe). Crucial for monitoring child-process execution failures in orchestrator scripts.

15. Administrative Privileges

Understanding security contexts.

  • Elevation: Scripts that interact with global services, protected registry keys, or system processes require an elevated Administrator context.
  • Principle of Least Privilege: Do not request elevation unnecessarily.
  • Partial Success: When running administrative actions against bulk objects (e.g., clearing multiple temp folders), handle permission denied errors gracefully. Never report complete success if some folders failed due to locked files.

16. Safe Command Execution

Adhere to this safe execution workflow during all IT support operations:

Inspect → Validate → Execute → Verify → Report

  • Validate paths meticulously before initiating destructive operations.
  • Prefer read-only inspection commands before making changes.
  • Use the -WhatIf switch on destructive commands (like Remove-Item or Stop-Service) to preview actions without committing them.
  • Avoid blindly using -Force unless you fully understand why the default operation is being blocked.
  • Never blindly terminate critical processes or modify services without understanding their system dependencies.

17. Command Quick Reference

Category Command Primary Use Risk
System Get-CimInstance Win32_OperatingSystem Retrieves OS version, build, and uptime. Read-only
Processes Get-Process Lists currently running processes. Read-only
Processes Stop-Process Terminates a running process. Potentially destructive
Services Get-Service Checks the status of Windows services. Read-only
Services Restart-Service Reboots a background service. Administrative
Storage Get-PSDrive Checks drive mappings and capacity. Read-only
Temp Cleanup Remove-Item -Path $env:TEMP\* -Recurse Clears local temporary files. Potentially destructive
Networking Get-NetIPConfiguration Inspects local IPv4/IPv6 and DNS settings. Read-only
DNS Resolve-DnsName Validates DNS resolution for a hostname. Read-only
Event Logs Get-WinEvent -LogName System Queries historical system events and errors. Read-only
Files Test-Path -LiteralPath <Path> Safely verifies if a file/folder exists. Read-only
Accounts Get-LocalUser Inspects local user accounts. Read-only
Reporting ConvertTo-Json Serializes structured objects to JSON format. Read-only