PowerShell
PowerShell

File & Directory Operations

Create a new empty file

$New-Item <name> -ItemType File

Create a new directory

$New-Item <name> -ItemType Directory

Create a new directory (alias/function)

$mkdir <name>

Create nested directories, creating parents as needed

$New-Item -Path <path> -ItemType Directory -Force

Delete a file or empty directory

$Remove-Item <path>

Recursively delete a directory and all its contents

$Remove-Item <path> -Recurse

Forcefully delete a file without prompting

$Remove-Item <path> -Force

Forcefully and recursively delete a directory

$Remove-Item <path> -Recurse -Force

Delete a file with a confirmation prompt

$Remove-Item <path> -Confirm

Copy a file or directory to a new location

$Copy-Item <source> <destination>

Recursively copy a directory and its contents

$Copy-Item <source> <destination> -Recurse

Copy a file, overwriting the destination if it exists

$Copy-Item <source> <destination> -Force

Copy an item and return the new item object

$Copy-Item <source> <destination> -PassThru

Move or rename a file or directory

$Move-Item <source> <destination>

Forcefully move a file, overwriting the destination

$Move-Item <source> <destination> -Force

Rename a file or directory

$Rename-Item <path> <newname>

Check if a file, directory, or registry key exists

$Test-Path <path>

Check if a path is a file

$Test-Path <path> -PathType Leaf

Check if a path is a directory

$Test-Path <path> -PathType Container

Combine path components into a single path string

$Join-Path <parent> <child>

Return the parent directory of a path

$Split-Path <path>

Return only the filename from a path

$Split-Path <path> -Leaf

Resolve a path to its absolute form

$Resolve-Path <path>

Create a symbolic link pointing to a target

$New-Item -ItemType SymbolicLink -Path <link> -Target <target>

Create a hard link to a file

$New-Item -ItemType HardLink -Path <link> -Target <target>

Get a file or directory object at a specified path

$Get-Item <path>

Get the properties of an item at a specified path

$Get-ItemProperty <path>

File Viewing & Content

Read and display the contents of a file

$Get-Content <file>

Alias for Get-Content, reads a file's contents

$cat <file>

Read only the first <n> lines of a file

$Get-Content <file> -TotalCount <n>

Read only the last <n> lines of a file

$Get-Content <file> -Tail <n>

Follow a file for new content in real-time

$Get-Content <file> -Wait

Read a file using a specific character encoding

$Get-Content <file> -Encoding UTF8

Read a file as a single string instead of line by line

$Get-Content <file> -Raw

Write content to a file, replacing existing content

$Set-Content <file> <value>

Append content to the end of a file

$Add-Content <file> <value>

Delete the contents of a file without deleting the file

$Clear-Content <file>

Send output to a file (pipeline-friendly Set-Content)

$Out-File <file>

Append pipeline output to a file

$Out-File <file> -Append

Write a string to a file via the pipeline

$"<text>" | Out-File <file>

Display file content one page at a time

$More <file>

Open a file with its default associated application

$Invoke-Item <file>

Open a file in Notepad

$notepad <file>

Open a file in Visual Studio Code

$code <file>

Count the number of lines in a file

$Get-Content <file> | Measure-Object -Line

Count the number of words in a file

$Get-Content <file> | Measure-Object -Word

Count the number of characters in a file

$Get-Content <file> | Measure-Object -Character

Search & Filter

Recursively search for files matching a name pattern

$Get-ChildItem -Recurse -Filter <pattern>

Recursively include only files matching a pattern

$Get-ChildItem -Recurse -Include <pattern>

Recursively list items excluding files matching a pattern

$Get-ChildItem -Recurse -Exclude <pattern>

Search for a text pattern in a file

$Select-String <pattern> <file>

Search for a regex pattern in a file

$Select-String -Pattern <pattern> -Path <file>

Recursively search for a pattern in all files under a path

$Select-String -Pattern <pattern> -Path <path> -Recurse

Search for a pattern with case-sensitive matching

$Select-String -CaseSensitive <pattern> <file>

Print lines that do NOT match the pattern

$Select-String -NotMatch <pattern> <file>

Print only the names of files that contain matches

$Select-String -List <pattern> <file>

Display line numbers of matching results

$Select-String <pattern> <file> | Select-Object LineNumber

Filter pipeline objects using a wildcard pattern

$Where-Object { $_ -like '<pattern>' }

Filter pipeline objects using a regular expression

$Where-Object { $_ -match '<regex>' }

Filter pipeline objects by exact equality

$Where-Object { $_ -eq '<value>' }

Filter pipeline objects by non-equality

$Where-Object { $_ -ne '<value>' }

Filter pipeline objects greater than a value

$Where-Object { $_ -gt <value> }

Filter pipeline objects less than a value

$Where-Object { $_ -lt <value> }

Filter pipeline objects that contain a specific value

$Where-Object { $_ -contains '<value>' }

Search for modules in PowerShell Gallery

$Find-Module <pattern>

Search for commands matching a name pattern

$Get-Command <pattern>

Find all commands with a specific verb

$Get-Command -Verb <verb>

Find all commands with a specific noun

$Get-Command -Noun <noun>

List all commands from a specific module

$Get-Command -Module <module>

Text Processing & Output Formatting

Write text to the standard output stream

$Write-Output <text>

Write text directly to the console

$Write-Host <text>

Write colored text to the console

$Write-Host <text> -ForegroundColor <color>

Write a warning message to the warning stream

$Write-Warning <text>

Write an error message to the error stream

$Write-Error <text>

Write a verbose message (visible only with -Verbose)

$Write-Verbose <text>

Write a debug message (visible only with -Debug)

$Write-Debug <text>

Write informational output to the information stream

$Write-Information <text>

Display properties as a list, one property per line

$Format-List

Display output as a formatted table

$Format-Table

Display a table with auto-adjusted column widths

$Format-Table -AutoSize

Display only specific properties in a table

$Format-Table -Property <prop1>,<prop2>

Display values in a wide, multi-column layout

$Format-Wide

Display output in an interactive graphical grid view

$Out-GridView

Display a grid view and return selected rows to the pipeline

$Out-GridView -PassThru

Convert an object to a JSON-formatted string

$ConvertTo-Json

Convert an object to JSON with a specified nesting depth

$ConvertTo-Json -Depth <n>

Convert a JSON string into a PowerShell object

$ConvertFrom-Json <string>

Convert an object to a CSV-formatted string

$ConvertTo-Csv

Convert CSV data to PowerShell objects

$ConvertFrom-Csv

Convert an object to an HTML representation

$ConvertTo-Html

Convert an object to an XML representation

$ConvertTo-Xml

Export pipeline objects to a CSV file

$Export-Csv <file>

Import a CSV file and create objects from its rows

$Import-Csv <file>

Export objects to an XML file preserving type information

$Export-Clixml <file>

Import objects from a Clixml file

$Import-Clixml <file>

Select specific properties of objects from the pipeline

$Select-Object -Property <props>

Select only the first <n> objects from the pipeline

$Select-Object -First <n>

Select only the last <n> objects from the pipeline

$Select-Object -Last <n>

Select only unique objects from the pipeline

$Select-Object -Unique

Extract the value of a single property from objects

$Select-Object -ExpandProperty <prop>

Sort objects in the pipeline

$Sort-Object

Sort objects by a specific property

$Sort-Object -Property <prop>

Sort objects in descending order

$Sort-Object -Descending

Sort objects and remove duplicates

$Sort-Object -Unique

Group objects by the value of a specified property

$Group-Object -Property <prop>

Calculate numeric statistics on pipeline objects

$Measure-Object

Calculate the sum of a property across pipeline objects

$Measure-Object -Sum

Calculate the average of a property

$Measure-Object -Average

Find the maximum value of a property

$Measure-Object -Maximum

Find the minimum value of a property

$Measure-Object -Minimum

Send pipeline output to a file and continue the pipeline

$Tee-Object <file>

Process Management

List all currently running processes

$Get-Process

Get information about processes matching a name

$Get-Process <name>

Get information about a process by its ID

$Get-Process -Id <pid>

List processes sorted by CPU usage

$Get-Process | Sort-Object CPU -Descending

List processes sorted by memory usage

$Get-Process | Sort-Object WorkingSet -Descending

Start a new process

$Start-Process <program>

Start a process with specific arguments

$Start-Process <program> -ArgumentList <args>

Start a process and wait for it to finish

$Start-Process <program> -Wait

Start a process with elevated administrator privileges

$Start-Process <program> -Verb RunAs

Start a process without showing a window

$Start-Process <program> -WindowStyle Hidden

Start a process and redirect its output to a file

$Start-Process <program> -RedirectStandardOutput <file>

Stop all processes with the specified name

$Stop-Process <name>

Stop a specific process by its ID

$Stop-Process -Id <pid>

Forcefully terminate a process

$Stop-Process <name> -Force

Wait for a process to finish before continuing

$Wait-Process <name>

Wait for a process up to a specified timeout

$Wait-Process -Id <pid> -Timeout <seconds>

Get all background jobs in the current session

$Get-Job

Start a command as a background job

$Start-Job -ScriptBlock { <commands> }

Run a script file as a background job

$Start-Job -FilePath <script>

Get the output from a background job

$Receive-Job <job>

Wait for a background job to complete

$Wait-Job <job>

Stop a background job

$Stop-Job <job>

Delete a background job and its results

$Remove-Job <job>

Run commands in a local or remote script block

$Invoke-Command -ScriptBlock { <commands> }

Run commands on a remote computer

$Invoke-Command -ComputerName <host> -ScriptBlock { <cmds> }

Pause script execution for a specified number of seconds

$Start-Sleep <seconds>

Pause script execution for a specified number of milliseconds

$Start-Sleep -Milliseconds <ms>

System Information

Get information about the current PowerShell host

$Get-Host

Display the PowerShell version and related information

$$PSVersionTable

Get comprehensive system and operating system information

$Get-ComputerInfo

Get a specific system information property

$Get-ComputerInfo -Property <prop>

Get operating system information via WMI

$Get-WmiObject Win32_OperatingSystem

Get computer system hardware information via WMI

$Get-WmiObject Win32_ComputerSystem

Get CPU information via WMI

$Get-WmiObject Win32_Processor

Get RAM module information via WMI

$Get-WmiObject Win32_PhysicalMemory

Get physical disk drive information via WMI

$Get-WmiObject Win32_DiskDrive

List all PowerShell drives including file system, registry, and more

$Get-PSDrive

List only file system drives

$Get-PSDrive -PSProvider FileSystem

Get information about disk volumes

$Get-Volume

Get information about physical disks

$Get-Disk

Get information about disk partitions

$Get-Partition

Get the current date and time

$Get-Date

Get the current date formatted as YYYY-MM-DD

$Get-Date -Format "yyyy-MM-dd"

Get the current time formatted as HH:MM:SS

$Get-Date -Format "HH:mm:ss"

Get the current UTC date and time

$[System.DateTime]::UtcNow

Get the current system time zone

$Get-TimeZone

List all available time zones

$Get-TimeZone -ListAvailable

Get the current UI culture setting

$Get-UICulture

Get the current regional and culture settings

$Get-Culture

Get the name of the current computer

$$env:COMPUTERNAME

Get the current logged-in username

$$env:USERNAME

Get the path to the current user's profile directory

$$env:USERPROFILE

Get the path to the temporary files directory

$$env:TEMP

Get the system PATH environment variable

$$env:PATH

List all environment variables

$Get-ChildItem Env:

Get the value of a specific environment variable

$$env:<variable>

Set an environment variable for the current session

$$env:<variable> = <value>

Get an environment variable from a specific scope

$[System.Environment]::GetEnvironmentVariable(<name>, <scope>)

Set an environment variable persistently at a specified scope

$[System.Environment]::SetEnvironmentVariable(<n>, <v>, <scope>)

Get a list of installed Windows updates and hotfixes

$Get-HotFix

Get the system uptime

$Get-Uptime

Network

Send ICMP ping requests to test connectivity to a host

$Test-Connection <host>

Send exactly <n> ping packets to a host

$Test-Connection <host> -Count <n>

Ping a host and return only true or false

$Test-Connection <host> -Quiet

Test a network connection and display diagnostic info

$Test-NetConnection <host>

Test if a specific TCP port is open on a host

$Test-NetConnection <host> -Port <port>

Trace the route to a remote host

$Test-NetConnection <host> -TraceRoute

Perform a DNS query for a domain name

$Resolve-DnsName <domain>

Perform a DNS query for a specific record type

$Resolve-DnsName <domain> -Type <type>

Get all network adapter properties

$Get-NetAdapter

List only active network adapters

$Get-NetAdapter | Where-Object Status -eq 'Up'

Get all IP address configurations

$Get-NetIPAddress

Get all IPv4 address configurations

$Get-NetIPAddress -AddressFamily IPv4

Get comprehensive IP configuration for all adapters

$Get-NetIPConfiguration

Get all entries in the IP routing table

$Get-NetRoute

Get all current TCP connections

$Get-NetTCPConnection

List all listening TCP ports

$Get-NetTCPConnection -State Listen

Get TCP connections on a specific local port

$Get-NetTCPConnection -LocalPort <port>

Get all current UDP endpoints

$Get-NetUDPEndpoint

Download content from a URL

$Invoke-WebRequest <url>

Download a URL and save it to a file

$Invoke-WebRequest <url> -OutFile <file>

Send a POST request with data to a URL

$Invoke-WebRequest <url> -Method POST -Body <data>

Send a request with custom HTTP headers

$Invoke-WebRequest <url> -Headers @{<key>=<value>}

Send a request with authentication credentials

$Invoke-WebRequest <url> -Credential <cred>

Send an HTTP request to a REST API endpoint

$Invoke-RestMethod <url>

Send a GET request to a REST API

$Invoke-RestMethod <url> -Method GET

Send a JSON POST request to a REST API

$Invoke-RestMethod <url> -Method POST -Body <json> -ContentType 'application/json'

Send an authenticated API request with a bearer token

$Invoke-RestMethod <url> -Headers @{Authorization='Bearer <token>'}

Create a new inbound firewall rule

$New-NetFirewallRule -DisplayName <name> -Direction Inbound -Port <port> -Protocol TCP -Action Allow

Get all firewall rules

$Get-NetFirewallRule

Enable a firewall rule by display name

$Enable-NetFirewallRule -DisplayName <name>

Disable a firewall rule

$Disable-NetFirewallRule -DisplayName <name>

Delete a firewall rule

$Remove-NetFirewallRule -DisplayName <name>

Registry

Get a registry key object

$Get-Item HKLM:\<path>

List subkeys and values under a registry key

$Get-ChildItem HKLM:\<path>

Get the values of a registry key

$Get-ItemProperty HKLM:\<path>

Get a specific registry value

$Get-ItemProperty HKLM:\<path> -Name <valuename>

Create a new registry key

$New-Item HKLM:\<path>

Create a new registry value in a key

$New-ItemProperty HKLM:\<path> -Name <n> -Value <v> -PropertyType <type>

Set or update a registry value

$Set-ItemProperty HKLM:\<path> -Name <n> -Value <v>

Delete a registry key

$Remove-Item HKLM:\<path>

Delete a registry key and all its subkeys

$Remove-Item HKLM:\<path> -Recurse

Delete a specific registry value

$Remove-ItemProperty HKLM:\<path> -Name <n>

Check if a registry key exists

$Test-Path HKLM:\<path>

Copy a registry key to another location

$Copy-Item HKLM:\<source> HKLM:\<dest>

Module & Package Management

List all modules imported in the current session

$Get-Module

List all modules installed and available to import

$Get-Module -ListAvailable

Import a module into the current session

$Import-Module <module>

Forcefully reimport a module, refreshing it

$Import-Module <module> -Force

Remove an imported module from the current session

$Remove-Module <module>

Download and install a module from PowerShell Gallery

$Install-Module <module>

Install a module for the current user only

$Install-Module <module> -Scope CurrentUser

Force install a module, reinstalling if already present

$Install-Module <module> -Force

Update an installed module to its latest version

$Update-Module <module>

Update all installed modules to their latest versions

$Update-Module

Uninstall an installed module

$Uninstall-Module <module>

Search for a module in PowerShell Gallery

$Find-Module <keyword>

Search for a module specifically in the PSGallery repository

$Find-Module <keyword> -Repository PSGallery

List all modules installed from a repository

$Get-InstalledModule

Register a new PowerShell module repository

$Register-PSRepository

List all registered PowerShell repositories

$Get-PSRepository

Mark PSGallery as a trusted installation source

$Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

Download a module to a folder without installing it

$Save-Module <module> -Path <path>

Permissions & Security

Get the access control list (permissions) of a file or directory

$Get-Acl <path>

Apply an access control list to a file or directory

$Set-Acl <path> -AclObject <acl>

Display detailed ACL information for a path

$Get-Acl <path> | Format-List

Get the current PowerShell script execution policy

$Get-ExecutionPolicy

List execution policies for all scopes

$Get-ExecutionPolicy -List

Allow local scripts and signed remote scripts to run

$Set-ExecutionPolicy RemoteSigned

Allow all scripts to run without restriction

$Set-ExecutionPolicy Unrestricted

Prevent all scripts from running

$Set-ExecutionPolicy Restricted

Set the execution policy for the current user only

$Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

Get all local user accounts

$Get-LocalUser

Create a new local user account

$New-LocalUser -Name <n> -Password <p>

Delete a local user account

$Remove-LocalUser <name>

List all local groups

$Get-LocalGroup

Add a user to a local group

$Add-LocalGroupMember -Group <g> -Member <m>

Remove a user from a local group

$Remove-LocalGroupMember -Group <g> -Member <m>

List members of a local group

$Get-LocalGroupMember -Group <group>

Convert a plain text string to a SecureString

$ConvertTo-SecureString <text> -AsPlainText -Force

Prompt for credentials and return a credential object

$Get-Credential

Get the digital signature information of a file

$Get-AuthenticodeSignature <file>

Add a digital signature to a script or file

$Set-AuthenticodeSignature <file> <cert>

Services & Events

Get the status of all Windows services

$Get-Service

Get the status of a specific service

$Get-Service <name>

Get only services that are currently running

$Get-Service | Where-Object Status -eq 'Running'

Start a Windows service

$Start-Service <name>

Stop a running Windows service

$Stop-Service <name>

Restart a Windows service

$Restart-Service <name>

Pause a running Windows service

$Suspend-Service <name>

Resume a suspended Windows service

$Resume-Service <name>

Configure a service to start automatically

$Set-Service <name> -StartupType Automatic

Disable a service from starting

$Set-Service <name> -StartupType Disabled

Create a new Windows service

$New-Service -Name <n> -BinaryPathName <path>

Delete a Windows service

$Remove-Service <name>

Read entries from a Windows event log

$Get-EventLog -LogName <log>

Get the most recent entries from the System event log

$Get-EventLog -LogName System -Newest <n>

Get error entries from the Application event log

$Get-EventLog -LogName Application -EntryType Error

Get events from a Windows event log (modern approach)

$Get-WinEvent -LogName <log>

Get error-level events from the System log

$Get-WinEvent -FilterHashtable @{LogName='System';Level=2}

Clear all entries from an event log

$Clear-EventLog -LogName <log>

Create a new event log with a specific source

$New-EventLog -LogName <n> -Source <s>

Write a custom event to an event log

$Write-EventLog -LogName <log> -Source <s> -EventId <id> -Message <msg>

Scripting & Automation

Execute a PowerShell script file

$powershell -File <script>.ps1

Execute a PowerShell command string directly

$powershell -Command "<command>"

Run a script file using the call operator

$& '<script>.ps1'

Dot-source a script to run it in the current scope

$. '.\<script>.ps1'

Assign a value to a variable

$$variable = <value>

Declare a strongly-typed string variable

$[string]$variable = <value>

Declare a strongly-typed integer variable

$[int]$variable = <value>

Declare a boolean variable

$[bool]$variable = $true

Create an array

$$array = @(<items>)

Create a hashtable (dictionary)

$$hash = @{<key>=<value>}

If-else conditional block

$if (<condition>) { ... } else { ... }

If-elseif-else conditional block

$if (<condition>) { ... } elseif (<cond>) { ... } else { ... }

Switch statement for matching multiple conditions

$switch (<variable>) { <value> { ... } }

Loop through each item in a collection

$foreach ($item in $collection) { ... }

C-style for loop

$for ($i=0; $i -lt $n; $i++) { ... }

Execute a block while a condition is true

$while (<condition>) { ... }

Execute a block at least once, then repeat while condition is true

$do { ... } while (<condition>)

Execute a block until a condition becomes true

$do { ... } until (<condition>)

Exit a loop immediately

$break

Skip the current iteration and continue to the next

$continue

Return a value from a function

$return <value>

Define a reusable function with parameters

$function <Name> { param(<params>) ... }

Define an advanced function with pipeline support

$function <Name> { [CmdletBinding()] param() begin{} process{} end{} }

Structured error handling with try-catch-finally

$try { ... } catch { ... } finally { ... }

Set errors to terminate as exceptions globally

$$ErrorActionPreference = 'Stop'

Define a trap to handle terminating errors

$trap { ... }

Throw a terminating error with a custom message

$throw <message>

Access the most recent error that occurred

$$Error[0]

Evaluate and run a string as a PowerShell expression

$Invoke-Expression <string>

Invoke a script block directly

$& { <scriptblock> }

Define parameters for a script or function

$param(<parameter>)

Mark a parameter as required

$[Parameter(Mandatory=$true)]

Restrict a parameter to a set of allowed values

$[ValidateSet(<values>)]

Restrict a numeric parameter to a valid range

$[ValidateRange(<min>, <max>)]

Measure how long a command or expression takes to run

$Measure-Command { <expression> }

Register a new scheduled task in Task Scheduler

$Register-ScheduledTask

Get all scheduled tasks

$Get-ScheduledTask

Manually run a scheduled task

$Start-ScheduledTask -TaskName <name>

Delete a scheduled task

$Unregister-ScheduledTask -TaskName <name>

Help & Discovery

Display help documentation for a command

$Get-Help <command>

Display complete help documentation including all parameters

$Get-Help <command> -Full

Display usage examples for a command

$Get-Help <command> -Examples

Open the online documentation for a command in a browser

$Get-Help <command> -Online

Get help for a specific parameter of a command

$Get-Help <command> -Parameter <param>

Download and update the local help documentation

$Update-Help

List all available PowerShell commands

$Get-Command

Find commands whose name contains a keyword

$Get-Command *<keyword>*

List all defined aliases

$Get-Alias

Find the command that an alias points to

$Get-Alias <alias>

Create a new alias for a command

$New-Alias <alias> <command>

Create or update an alias

$Set-Alias <alias> <command>

Remove a defined alias

$Remove-Alias <alias>

Display the properties and methods of a pipeline object

$Get-Member

Explore what properties and methods an object has

$<object> | Get-Member

List all accessible PowerShell drives

$Get-PSDrive

List all available PowerShell providers

$Get-PSProvider

Display a graphical interface to help build a command

$Show-Command

Clear the PowerShell console screen

$Clear-Host

Alias for Clear-Host, clears the console

$cls

Exit the current PowerShell session

$Exit