Skip to content

One-Liners

Note

Collection of useful PowerShell one-liners for quick copy/paste in your daily work.

Overview

This is a curated collection of battle-tested PowerShell one-liners organized by task. Each command is ready to copy and paste with minimal modification. Perfect for quick reference when you need to get something done fast.

How to Use This Page

  • Copy the command that matches your need
  • Replace placeholder values (like paths, names, etc.)
  • Run directly in PowerShell
  • Most commands work in both PowerShell 5.1 and 7+

File Operations

Find Files

# Find files larger than 100MB
Get-ChildItem -Path C:\* -Recurse -File | Where-Object {$_.Length -gt 100MB}

# Find files modified in last 24 hours
Get-ChildItem -Path C:\Data -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddHours(-24)}

# Find files older than 30 days
Get-ChildItem -Path C:\Logs -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)}

# Find empty files
Get-ChildItem -Path C:\Temp -Recurse -File | Where-Object {$_.Length -eq 0}

# Find duplicate file names
Get-ChildItem -Path C:\Documents -Recurse -File | Group-Object Name | Where-Object {$_.Count -gt 1}

# Find files containing specific text
Select-String -Path C:\Logs\*.log -Pattern "error" -List | Select-Object Path

# Count files by extension
Get-ChildItem -Path C:\Data -Recurse -File | Group-Object Extension | Sort-Object Count -Descending

File Management

# Delete files older than 30 days
Get-ChildItem -Path C:\Temp -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item -Force

# Copy files modified today
Get-ChildItem -Path C:\Source -Recurse | Where-Object {$_.LastWriteTime.Date -eq (Get-Date).Date} | Copy-Item -Destination C:\Backup

# Rename all .txt files to .log
Get-ChildItem -Path C:\Logs -Filter *.txt | Rename-Item -NewName {$_.Name -replace '\.txt$','.log'}

# Calculate total size of directory in GB
(Get-ChildItem -Path C:\Data -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1GB

# Create backup with timestamp
Copy-Item -Path C:\Config.xml -Destination "C:\Config_$(Get-Date -Format 'yyyyMMdd_HHmmss').xml"

# Delete empty folders
Get-ChildItem -Path C:\Temp -Recurse -Directory | Where-Object {$_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0} | Remove-Item -Force

File Content

# Get first 10 lines of file
Get-Content -Path C:\Logs\app.log -TotalCount 10

# Get last 20 lines of file
Get-Content -Path C:\Logs\app.log -Tail 20

# Count lines in a file
(Get-Content -Path C:\Data\file.txt).Count

# Find and replace in file
(Get-Content C:\Config.txt) -replace 'oldtext','newtext' | Set-Content C:\Config.txt

# Merge multiple text files
Get-Content C:\Logs\*.log | Set-Content C:\Logs\merged.log

# Read CSV and filter
Import-Csv C:\Data\users.csv | Where-Object {$_.Department -eq "IT"}

# Convert CSV to JSON
Import-Csv C:\Data\data.csv | ConvertTo-Json | Out-File C:\Data\data.json

Compress & Extract

# Compress a single file
Compress-Archive -Path C:\Data\report.pdf -DestinationPath C:\Archives\report.zip

# Compress multiple files
Compress-Archive -Path C:\Logs\*.log -DestinationPath C:\Archives\logs.zip

# Compress entire directory
Compress-Archive -Path C:\Projects\MyApp -DestinationPath C:\Backups\MyApp.zip

# Compress multiple directories and files
Compress-Archive -Path C:\Data\*, C:\Logs\*, C:\Config.xml -DestinationPath C:\Backup.zip

# Add files to existing archive (update)
Compress-Archive -Path C:\NewData\*.csv -DestinationPath C:\Archive.zip -Update

# Create archive with compression level
Compress-Archive -Path C:\Data -DestinationPath C:\Data.zip -CompressionLevel Optimal

# Compress with timestamp in filename
Compress-Archive -Path C:\Logs -DestinationPath "C:\Archives\Logs_$(Get-Date -Format 'yyyyMMdd_HHmmss').zip"

# Extract archive
Expand-Archive -Path C:\Archive.zip -DestinationPath C:\Extracted

# Extract archive (overwrite existing)
Expand-Archive -Path C:\Backup.zip -DestinationPath C:\Restore -Force

# Compress folder excluding certain files
Get-ChildItem -Path C:\Data -Recurse | Where-Object {$_.Extension -ne ".tmp"} | Compress-Archive -DestinationPath C:\Data.zip

# Create daily backup archive
Compress-Archive -Path C:\ImportantData -DestinationPath "C:\Backups\Backup_$(Get-Date -Format 'yyyy-MM-dd').zip" -CompressionLevel Fastest

System Information

General System Info

# Computer name
$env:COMPUTERNAME

# Current user
$env:USERNAME

# OS version
(Get-CimInstance Win32_OperatingSystem).Caption

# System uptime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime

# PowerShell version
$PSVersionTable.PSVersion

# Get IP address
(Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.IPAddress -notlike "127.*"}).IPAddress

# Get all environment variables
Get-ChildItem Env: | Sort-Object Name

# Disk space free on C:
Get-PSDrive C | Select-Object Used,Free

Hardware Info

# CPU info
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors

# Memory info (GB)
[math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)

# Available RAM (GB)
[math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 2)

# Disk space summary
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{N='UsedGB';E={[math]::Round($_.Used/1GB,2)}}, @{N='FreeGB';E={[math]::Round($_.Free/1GB,2)}}

# Serial number
(Get-CimInstance Win32_BIOS).SerialNumber

# Get all installed updates
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10

Process & Service Management

Processes

# Top 10 processes by memory
Get-Process | Sort-Object WS -Descending | Select-Object -First 10 Name, @{N='MemoryMB';E={[math]::Round($_.WS/1MB,2)}}

# Top 10 processes by CPU
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU

# Kill all instances of a process
Get-Process -Name notepad | Stop-Process -Force

# Check if process is running
Get-Process -Name "explorer" -ErrorAction SilentlyContinue | Select-Object -First 1

# Start process and wait for exit
Start-Process -FilePath "notepad.exe" -Wait

# Count running processes
(Get-Process).Count

Services

# List all running services
Get-Service | Where-Object {$_.Status -eq "Running"}

# List stopped services
Get-Service | Where-Object {$_.Status -eq "Stopped"}

# Restart a service
Restart-Service -Name "Spooler" -Force

# Stop multiple services
"Service1","Service2" | ForEach-Object {Stop-Service -Name $_ -Force}

# Get service startup type
Get-Service -Name "Spooler" | Select-Object Name, StartType, Status

# Services that are set to Auto but not running
Get-Service | Where-Object {$_.StartType -eq "Automatic" -and $_.Status -ne "Running"}

Network Operations

Connectivity

# Ping a host
Test-Connection -ComputerName google.com -Count 4

# Quick ping (returns true/false)
Test-Connection -ComputerName server01 -Count 1 -Quiet

# Test port connectivity
Test-NetConnection -ComputerName server01 -Port 80

# Get public IP address
(Invoke-WebRequest -Uri "https://api.ipify.org").Content

# Test multiple hosts
"server01","server02","server03" | ForEach-Object {Test-Connection -ComputerName $_ -Count 1 -Quiet}

# DNS lookup
Resolve-DnsName google.com

# Show all network adapters
Get-NetAdapter | Select-Object Name, Status, MacAddress, LinkSpeed

Web Requests

# Download file
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "C:\Downloads\file.zip"

# Get HTTP status code
(Invoke-WebRequest -Uri "https://google.com").StatusCode

# Get website content
(Invoke-WebRequest -Uri "https://example.com").Content

# REST API GET request
Invoke-RestMethod -Uri "https://api.github.com/users/octocat" -Method Get

# REST API POST with JSON
$body = @{name="test"; value="123"} | ConvertTo-Json
Invoke-RestMethod -Uri "https://api.example.com/data" -Method Post -Body $body -ContentType "application/json"

# Test URL accessibility
try {Invoke-WebRequest -Uri "https://example.com" -UseBasicParsing -ErrorAction Stop; "Available"} catch {"Unavailable"}

String & Text Manipulation

String Operations

# Convert string to uppercase
"hello world".ToUpper()

# Convert string to lowercase
"HELLO WORLD".ToLower()

# Split string by delimiter
"apple,banana,cherry" -split ','

# Join array into string
"apple","banana","cherry" -join ', '

# Remove whitespace
"  hello world  ".Trim()

# Replace text
"hello world" -replace 'world','PowerShell'

# Check if string contains text
"hello world" -like "*world*"

# Extract substring
"PowerShell".Substring(0,5)

# String length
"PowerShell".Length

Text Processing

# Count lines containing pattern
(Select-String -Path C:\Logs\app.log -Pattern "error").Count

# Extract unique lines from file
Get-Content C:\Data\file.txt | Sort-Object -Unique

# Sort file contents
Get-Content C:\Data\file.txt | Sort-Object | Set-Content C:\Data\sorted.txt

# Find lines not matching pattern
Get-Content C:\Logs\app.log | Where-Object {$_ -notmatch "debug"}

# Extract email addresses from text
Select-String -Path C:\Data\*.txt -Pattern "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" -AllMatches

# Count word occurrences
(Get-Content C:\file.txt | Out-String) -split '\s+' | Group-Object | Sort-Object Count -Descending

Date & Time Operations

# Current date and time
Get-Date

# Current date only
(Get-Date).Date

# Format date as string
Get-Date -Format "yyyy-MM-dd HH:mm:ss"

# Format: yyyyMMdd
Get-Date -Format "yyyyMMdd"

# Add 7 days to current date
(Get-Date).AddDays(7)

# Subtract 30 days
(Get-Date).AddDays(-30)

# Get first day of current month
Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0

# Get last day of current month
(Get-Date -Day 1).AddMonths(1).AddDays(-1)

# Calculate days between dates
(New-TimeSpan -Start (Get-Date "2025-01-01") -End (Get-Date)).Days

# Convert Unix timestamp
[DateTimeOffset]::FromUnixTimeSeconds(1640000000).DateTime

User & Security

User Accounts

# List local users
Get-LocalUser

# Check if user exists
Get-LocalUser -Name "jsmith" -ErrorAction SilentlyContinue

# List enabled local users
Get-LocalUser | Where-Object {$_.Enabled -eq $true}

# List local administrators
Get-LocalGroupMember -Group "Administrators"

# Current user's groups
whoami /groups

# Get domain users (requires AD module)
Get-ADUser -Filter * | Select-Object Name, SamAccountName, Enabled

Credentials

# Prompt for credentials
$cred = Get-Credential

# Create credential object
$password = ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $password)

# Export encrypted credential
$cred.Password | ConvertFrom-SecureString | Out-File C:\cred.txt

# Import encrypted credential
$password = Get-Content C:\cred.txt | ConvertTo-SecureString

Array & Object Manipulation

Arrays

# Create array
$array = 1,2,3,4,5

# Array length
$array.Count

# Add to array (creates new array)
$array += 6

# Join array elements
$array -join ','

# Filter array
$array | Where-Object {$_ -gt 3}

# Get unique values
$array | Sort-Object -Unique

# Check if array contains value
$array -contains 3

# Reverse array
[array]::Reverse($array)

Objects

# Create custom object
[PSCustomObject]@{Name="John"; Age=30; City="NYC"}

# Select specific properties
Get-Process | Select-Object Name, CPU, WS

# Add calculated property
Get-Process | Select-Object Name, @{N='MemoryMB';E={$_.WS/1MB}}

# Sort objects
Get-Process | Sort-Object WS -Descending

# Group objects
Get-Service | Group-Object Status

# Filter objects
Get-Process | Where-Object {$_.CPU -gt 10}

# Measure objects
Get-ChildItem C:\Temp -File | Measure-Object -Property Length -Sum -Average

Registry Operations

# Read registry value
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" -Name "ProgramFilesDir"

# Check if registry key exists
Test-Path "HKLM:\SOFTWARE\MyApp"

# Create registry key
New-Item -Path "HKLM:\SOFTWARE\MyApp" -Force

# Set registry value
Set-ItemProperty -Path "HKLM:\SOFTWARE\MyApp" -Name "Setting" -Value "Value"

# Delete registry value
Remove-ItemProperty -Path "HKLM:\SOFTWARE\MyApp" -Name "Setting"

# Get all values in key
Get-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" | Select-Object -ExpandProperty Property

Event Logs

# Get last 10 application errors
Get-EventLog -LogName Application -EntryType Error -Newest 10

# Get errors from last 24 hours
Get-EventLog -LogName System -EntryType Error -After (Get-Date).AddHours(-24)

# Count events by type
Get-EventLog -LogName System -Newest 1000 | Group-Object EntryType

# Find events by source
Get-EventLog -LogName Application -Source "Application Error"

# Modern event log query (PowerShell 3.0+)
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-1)}

# Export event log
Get-EventLog -LogName System -Newest 100 | Export-Csv C:\Logs\events.csv -NoTypeInformation

Performance & Monitoring

# Measure command execution time
Measure-Command {Get-ChildItem C:\ -Recurse}

# Monitor folder size over time
while($true) {Get-ChildItem C:\Logs -Recurse | Measure-Object -Property Length -Sum | Select-Object @{N='Date';E={Get-Date}},@{N='SizeGB';E={$_.Sum/1GB}}; Start-Sleep 60}

# Get CPU usage percentage
(Get-CimInstance Win32_Processor).LoadPercentage

# Monitor process memory usage
Get-Process -Name "chrome" | Select-Object Name, @{N='MemoryGB';E={$_.WS/1GB}}

# List processes using more than 100MB
Get-Process | Where-Object {$_.WS -gt 100MB} | Sort-Object WS -Descending

# Disk I/O statistics
Get-Counter '\PhysicalDisk(_Total)\Disk Reads/sec','\PhysicalDisk(_Total)\Disk Writes/sec'

Miscellaneous

Quick Tasks

# Generate random password
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 16 | ForEach-Object {[char]$_})

# Create GUID
[guid]::NewGuid()

# Get Windows product key (requires admin)
(Get-WmiObject -Query 'select * from SoftwareLicensingService').OA3xOriginalProductKey

# Clear recycle bin
Clear-RecycleBin -Force

# Empty temp folder
Remove-Item -Path $env:TEMP\* -Recurse -Force -ErrorAction SilentlyContinue

# Get installed programs
Get-Package | Select-Object Name, Version

# Check Windows version
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer

# Show PATH environment variable (each entry on new line)
$env:Path -split ';'

Data Conversion

# JSON to PSObject
$json = '{"name":"John","age":30}' | ConvertFrom-Json
$json.name  # "John"

# PSObject to JSON (pretty-printed by default)
@{name="John"; age=30} | ConvertTo-Json

# Compact JSON (single line)
@{name="John"; age=30} | ConvertTo-Json -Compress

# Read JSON from file
Get-Content C:\config.json -Raw | ConvertFrom-Json

# Save JSON to file
@{server="db01"; port=5432} | ConvertTo-Json | Out-File C:\settings.json

# JSON with increased depth (for nested objects)
$complex = @{L1=@{L2=@{L3="value"}}}
$complex | ConvertTo-Json -Depth 5

# XML to PSObject
[xml]$xml = Get-Content C:\data.xml

# CSV to JSON
Import-Csv C:\data.csv | ConvertTo-Json | Out-File C:\data.json

# Base64 encode string
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Hello"))

# Base64 decode string
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("SGVsbG8="))

# Base64 encode file
$bytes = [System.IO.File]::ReadAllBytes("C:\file.txt")
[Convert]::ToBase64String($bytes)

# Base64 decode to file
$base64 = "U29tZSBkYXRh"
$bytes = [Convert]::FromBase64String($base64)
[System.IO.File]::WriteAllBytes("C:\decoded.txt", $bytes)

API Interactions

# Simple GET request
Invoke-RestMethod -Uri "https://api.github.com/users/octocat"

# GET with query parameters
$params = @{page=1; per_page=50}
Invoke-RestMethod -Uri "https://api.example.com/users" -Body $params

# POST with JSON body
$body = @{name="John"; email="john@example.com"} | ConvertTo-Json
Invoke-RestMethod -Uri "https://api.example.com/users" -Method Post -Body $body -ContentType "application/json"

# API call with authentication (Bearer token)
$headers = @{Authorization="Bearer your-token-here"}
Invoke-RestMethod -Uri "https://api.example.com/data" -Headers $headers

# API call with API key
$headers = @{"X-API-Key"="your-api-key"}
Invoke-RestMethod -Uri "https://api.example.com/data" -Headers $headers

# PUT request (update)
$body = @{name="Updated Name"} | ConvertTo-Json
Invoke-RestMethod -Uri "https://api.example.com/users/123" -Method Put -Body $body -ContentType "application/json"

# DELETE request
Invoke-RestMethod -Uri "https://api.example.com/users/123" -Method Delete

# Download file from API
Invoke-RestMethod -Uri "https://api.example.com/files/report.pdf" -OutFile "C:\Downloads\report.pdf"

# Check HTTP status code
$response = Invoke-WebRequest -Uri "https://api.example.com/health"
$response.StatusCode  # 200

# Handle API errors
try { Invoke-RestMethod -Uri "https://api.example.com/data" } catch { Write-Error "API Error: $_" }

Tips for Using One-Liners

Chain Commands with Semicolons

# Run multiple commands in sequence
Get-Date; Get-Location; whoami

Use Backticks for Line Continuation

# Break long one-liner across multiple lines
Get-ChildItem -Path C:\Logs `
-Filter *.log `
-Recurse | Where-Object {$_.Length -gt 10MB}

Save Frequent One-Liners as Functions

# Add to your PowerShell profile
function Get-DiskSpace {
Get-PSDrive -PSProvider FileSystem |
Select-Object Name,
    @{N='UsedGB';E={[math]::Round($_.Used/1GB,2)}},
    @{N='FreeGB';E={[math]::Round($_.Free/1GB,2)}}
}

Be Careful with -Force

# -Force can be dangerous - always test first!
# BAD - Could delete important files
Get-ChildItem C:\ -Recurse | Remove-Item -Force

# GOOD - Test with -WhatIf first
Get-ChildItem C:\Temp -Recurse | Remove-Item -Force -WhatIf

Some Commands Require Admin Rights

# These require elevated PowerShell
# - Registry edits in HKLM
# - Service management
# - System event logs
# - Installing software
# - Modifying system files

Additional Resources