Table of Contents

PowerShell Cheatsheet

Basic Syntax

```powershell

  $x = 5
  $name = "John"
  ```

```powershell

  # This is a single-line comment
  <#
  This is a
  multi-line comment
  #>
  ```

Data Types

Control Flow

```powershell

  if ($x -gt 5) {
      Write-Output "x is greater than 5"
  } elseif ($x -eq 5) {
      Write-Output "x is 5"
  } else {
      Write-Output "x is less than 5"
  }
  ```

```powershell

    for ($i = 0; $i -lt 5; $i++) {
        Write-Output $i
    }
    ```

```powershell

    $count = 0
    while ($count -lt 5) {
        Write-Output $count
        $count++
    }
    ```

```powershell

    $arr = @(1, 2, 3)
    foreach ($item in $arr) {
        Write-Output $item
    }
    ```

Functions

```powershell

  function Greet {
      param ($name)
      "Hello, $name"
  }
  Greet "John"
  ```

Data Structures

```powershell

  $arr = @(1, 2, 3)
  $arr += 4
  ```

```powershell

  $hash = @{ "key1" = "value1"; "key2" = "value2" }
  $hash["key1"] = "newValue"
  ```

Error Handling

```powershell

  try {
      $result = 10 / 0
  } catch {
      Write-Output "An error occurred: $_"
  } finally {
      Write-Output "Execution finished"
  }
  ```

File Handling

```powershell

  $content = Get-Content -Path "file.txt"
  Write-Output $content
  ```

```powershell

  "Hello, World!" | Out-File -FilePath "file.txt"
  ```

```powershell

  "Additional text" | Add-Content -Path "file.txt"
  ```

Cmdlets

Importing Modules

```powershell

  Import-Module -Name MyModule
  ```

Classes & Objects

```powershell

  class Person {
      [string]$Name
      [int]$Age
      Person ([string]$name, [int]$age) {
          $this.Name = $name
          $this.Age = $age
      }
      [void]Greet() {
          Write-Output "Hello, my name is $($this.Name)"
      }
  }
  $p = [Person]::new("Alice", 25)
  $p.Greet()
  ```

Useful Commands

Useful Tips

```powershell

  Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object -Property CPU -Descending
  ```

Conclusion

This cheatsheet provides a quick overview of essential PowerShell commands and syntax for easy reference. For more advanced features, refer to the official PowerShell documentation.