logo
eng-flag

PowerShell Cheatsheet

Table of Contents

  1. Basic Commands
  2. File and Directory Operations
  3. Text Manipulation
  4. Process Management
  5. Network Commands
  6. System Information
  7. PowerShell Specific Features
  8. Variables and Data Types
  9. Flow Control
  10. Functions and Modules
  11. Error Handling
  12. Remoting
  13. Security and Execution Policy

Basic Commands

  • Print working directory: Get-Location or pwd
  • Change directory: Set-Location [path] or cd [path]
  • Go to home directory: cd ~
  • Go to previous directory: cd -

Example:

PS C:UsersUser> Get-Location
Path
----
C:UsersUser

PS C:UsersUser> Set-Location C:Windows
PS C:Windows>

Listing Files and Directories

  • List files and directories: Get-ChildItem or dir or ls
  • List all items including hidden: Get-ChildItem -Force
  • List with details: Get-ChildItem | Format-List

Example:

PS C:> Get-ChildItem -Force

    Directory: C:
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d--hs-        11/14/2023  10:14 PM                $Recycle.Bin
d--hsl        7/12/2023   3:51 AM                 Documents and Settings
d-----        7/12/2023   1:06 PM                 PerfLogs
d-r---        7/12/2023   3:51 AM                 Program Files
d-r---        7/12/2023   3:52 AM                 Program Files (x86)
d-----        7/12/2023   1:06 PM                 Users
d-----        11/15/2023  9:32 AM                 Windows

File and Directory Operations

Creating Files and Directories

  • Create an empty file: New-Item -ItemType File -Name [filename]
  • Create a directory: New-Item -ItemType Directory -Name [dirname]
  • Create nested directories: New-Item -ItemType Directory -Path [path/to/dirname] -Force

Example:

PS C:> New-Item -ItemType File -Name newfile.txt
PS C:> New-Item -ItemType Directory -Name newdir
PS C:> New-Item -ItemType Directory -Path deeply
esteddirectory -Force

Copying, Moving, and Removing

  • Copy file: Copy-Item [source] [destination]
  • Copy directory recursively: Copy-Item [source] [destination] -Recurse
  • Move/rename file or directory: Move-Item [source] [destination]
  • Remove file: Remove-Item [filename]
  • Remove directory and contents: Remove-Item [dirname] -Recurse -Force

Example:

PS C:> Copy-Item file1.txt file2.txt
PS C:> Move-Item file2.txt newname.txt
PS C:> Remove-Item newname.txt
PS C:> Remove-Item olddir -Recurse -Force

Text Manipulation

Viewing File Contents

  • View entire file: Get-Content [filename]
  • View first few lines: Get-Content [filename] -Head 10
  • View last few lines: Get-Content [filename] -Tail 10

Example:

PS C:> Get-Content log.txt
PS C:> Get-Content log.txt -Tail 5

Searching and Filtering

  • Search for pattern in file: Select-String -Path [filename] -Pattern [pattern]
  • Search recursively in directory: Get-ChildItem -Recurse | Select-String -Pattern [pattern]

Example:

PS C:> Select-String -Path log.txt -Pattern "error"
PS C:> Get-ChildItem -Recurse | Select-String -Pattern "TODO"

Text Editing

  • Open file in default editor: Invoke-Item [filename]

Example:

PS C:> Invoke-Item config.txt

Process Management

Viewing Processes

  • List all processes: Get-Process
  • Get specific process: Get-Process -Name [processname]

Example:

PS C:> Get-Process
PS C:> Get-Process -Name chrome

Managing Processes

  • Start a new process: Start-Process [path/to/executable]
  • Stop a process: Stop-Process -Name [processname]
  • Stop a process by ID: Stop-Process -Id [processID]

Example:

PS C:> Start-Process notepad.exe
PS C:> Stop-Process -Name notepad

Network Commands

Network Information

  • Get IP configuration: Get-NetIPConfiguration
  • Test network connection: Test-NetConnection [destination]
  • Get DNS client cache: Get-DnsClientCache

Example:

PS C:> Get-NetIPConfiguration
PS C:> Test-NetConnection www.google.com

Network Operations

  • Download file: Invoke-WebRequest -Uri [URL] -OutFile [filename]
  • Send ping: Test-Connection [destination]

Example:

PS C:> Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"
PS C:> Test-Connection 8.8.8.8

System Information

  • Get system information: Get-ComputerInfo
  • Get installed hotfixes: Get-HotFix
  • Get disk information: Get-Disk

Example:

PS C:> Get-ComputerInfo | Select-Object WindowsProductName, OsVersion, OsArchitecture

PowerShell Specific Features

Pipeline

  • Use pipeline to pass output: command1 | command2

Example:

PS C:> Get-Process | Where-Object {$_.CPU -gt 10} | Sort-Object CPU -Descending

Aliases

  • Get all aliases: Get-Alias
  • Create new alias: New-Alias -Name [alias] -Value [command]

Example:

PS C:> New-Alias -Name proc -Value Get-Process

Variables and Data Types

Working with Variables

  • Create variable: $variableName = value
  • Get variable type: $variableName.GetType()

Example:

PS C:> $name = "John"
PS C:> $age = 30
PS C:> $name.GetType()

Arrays and HashTables

  • Create an array: $array = @(1, 2, 3, 4)
  • Create a hashtable: $hash = @{Key1 = "Value1"; Key2 = "Value2"}

Example:

PS C:> $fruits = @("Apple", "Banana", "Orange")
PS C:> $person = @{Name = "Alice"; Age = 25; City = "New York"}

Flow Control

Conditional Statements

  • If statement:
if (condition) {
    # code
} elseif (condition) {
    # code
} else {
    # code
}

Loops

  • ForEach loop:
foreach ($item in $collection) {
    # code
}
  • For loop:
for ($i = 0; $i -lt 10; $i++) {
    # code
}

Example:

PS C:> foreach ($file in Get-ChildItem) {
>>     Write-Host $file.Name
>> }

Functions and Modules

Creating Functions

function FunctionName {
    param (
        [Parameter(Mandatory=$true)][string]$param1,
        [int]$param2 = 0
    )
    # Function body
}

Example:

PS C:> function Greet {
>>     param ([string]$name)
>>     Write-Host "Hello, $name!"
>> }
PS C:> Greet -name "Alice"
Hello, Alice!

Working with Modules

  • Import module: Import-Module [ModuleName]
  • Get all commands in a module: Get-Command -Module [ModuleName]

Example:

PS C:> Import-Module ActiveDirectory
PS C:> Get-Command -Module ActiveDirectory

Error Handling

  • Try-Catch block:
try {
    # Code that might cause an error
} catch {
    # Error handling code
} finally {
    # Code that runs regardless of error
}

Example:

PS C:> try {
>>     $result = 10 / 0
>> } catch {
>>     Write-Host "An error occurred: $_"
>> }
An error occurred: Attempted to divide by zero.

Remoting

  • Enable PowerShell remoting: Enable-PSRemoting
  • Start a remote session: Enter-PSSession -ComputerName [hostname]
  • Run command on remote computer: Invoke-Command -ComputerName [hostname] -ScriptBlock { command }

Example:

PS C:> Enter-PSSession -ComputerName Server01
[Server01]: PS C:>

Security and Execution Policy

  • Get execution policy: Get-ExecutionPolicy
  • Set execution policy: Set-ExecutionPolicy [PolicyName]
  • Get script signing status: Get-AuthenticodeSignature [script.ps1]

Example:

PS C:> Get-ExecutionPolicy
Restricted
PS C:> Set-ExecutionPolicy RemoteSigned

2024 © All rights reserved - buraxta.com