PowerShell Cheat Sheet

PowerShell is a task automation framework and scripting language developed by Microsoft. Below is a PowerShell cheat sheet covering common commands and operations:

Basics

Get Help:

Get-Help <command>

Get Command Information:

Get-Command <command>

Working with Files and Directories

List Files and Directories:

Get-ChildItem

Change Directory:

Set-Location <path>

Copy File:

Copy-Item <source> <destination>

Move/Rename File:

Move-Item <source> <destination>

Variables and Data Types

Assign Variable:

$variable = "value"
  1. Data Types:
    • String, Integer, Array, HashTable, Object.
  2. Check Variable Type:
$variable.GetType()

Strings

String Concatenation:

$string1 + $string2

String Interpolation:

"Hello, $($variable)"

Arrays

Create Array:

$array = @("item1", "item2", "item3")

Access Array Elements:

$array[0]

Add Element to Array:

$array += "newItem"

Conditions

If Statement:

if ($condition) {
    # code
}

Switch Statement:

switch ($variable) {
    "value1" { # code }
    "value2" { # code }
    default { # code }
}

Loops

For Loop:

for ($i=1; $i -le 5; $i++) {
    # code
}

Foreach Loop:

foreach ($item in $array) {
    # code
}

Functions

Define Function:

function MyFunction {
    param (
        [string]$param1,
        [int]$param2
    )
    # code
}

Call Function:

MyFunction -param1 "value" -param2 42

PowerShell Modules

Install Module:

Install-Module -Name <ModuleName>

Import Module:

Import-Module <ModuleName>

PowerShell Remoting

Enter Remote Session:

Enter-PSSession -ComputerName <RemoteComputer>

Invoke Command on Remote Computer:

Invoke-Command -ComputerName <RemoteComputer> -ScriptBlock { # code }

Get System Information

Get System Information:

Get-ComputerInfo

Get Running Processes:

Get-Process

Get Disk Space:

Get-Volume

Miscellaneous

Execute Script:

.\script.ps1

Clear Screen:

Clear-Host

Exit PowerShell:

Exit

This cheat sheet provides a quick reference for common PowerShell commands and operations. PowerShell is a versatile scripting language with extensive capabilities, and this cheat sheet covers only the basics. For more detailed information, explore the official PowerShell documentation.