Zum Inhalt

PowerShell Cheatsheet

Überblick

PowerShell ist eine plattformübergreifende Aufgabenautomatisierungslösung, die aus einer Kommandozeilenhülle, einer Skriptsprache und einem Konfigurationsmanagement-Rahmen besteht.

Grundlegende Befehle

Hilfe bekommen

```powershell

Get help for a command

Get-Help Get-Process Get-Help Get-Process -Examples Get-Help Get-Process -Full

Update help files

Update-Help

Get command syntax

Get-Command Get-Process -Syntax ```_

```powershell

Current location

Get-Location pwd

Change directory

Set-Location C:\Windows cd C:\Windows

List directory contents

Get-ChildItem ls dir

Go back to previous directory

cd .. ```_

Dateioperationen

```powershell

Create new file

New-Item -ItemType File -Name "test.txt" ni test.txt -ItemType File

Create new directory

New-Item -ItemType Directory -Name "TestFolder" mkdir TestFolder

Copy files

Copy-Item source.txt destination.txt cp source.txt destination.txt

Move files

Move-Item oldname.txt newname.txt mv oldname.txt newname.txt

Remove files

Remove-Item test.txt rm test.txt

Get file content

Get-Content file.txt cat file.txt

Set file content

Set-Content -Path file.txt -Value "Hello World" "Hello World"|Out-File file.txt ```_

Variablen und Datentypen

Variablen

```powershell

Declare variables

$name = "John" $age = 30 $isActive = $true

Array

$colors = @("red", "green", "blue") $numbers = 1,2,3,4,5

Hash table

$person = @\\{ Name = "John" Age = 30 City = "New York" \\}

Access hash table values

$person.Name $person["Age"] ```_

Datentypen

```powershell

String

$text = "Hello World" $multiline = @" This is a multi-line string "@

Numbers

$integer = 42 $decimal = 3.14

Boolean

$isTrue = $true $isFalse = $false

Date

$today = Get-Date $specificDate = [DateTime]"2023-12-25" ```_

Kontrollstrukturen

Bedingte Aussagen

```powershell

If statement

if ($age -gt 18) \\{ Write-Host "Adult" \\} elseif ($age -eq 18) \\{ Write-Host "Just turned adult" \\} else \\{ Write-Host "Minor" \\}

Switch statement

switch ($day) \\{ "Monday" \\{ "Start of work week" \\} "Friday" \\{ "TGIF!" \\} "Saturday" \\{ "Weekend!" \\} "Sunday" \\{ "Weekend!" \\} default \\{ "Regular day" \\} \\} ```_

Loops

```powershell

For loop

for ($i = 1; $i -le 10; $i++) \\{ Write-Host $i \\}

ForEach loop

$colors = @("red", "green", "blue") foreach ($color in $colors) \\{ Write-Host $color \\}

While loop

$i = 1 while ($i -le 5) \\{ Write-Host $i $i++ \\}

Do-While loop

do \\{ $input = Read-Host "Enter 'quit' to exit" \\} while ($input -ne "quit") ```_

Funktionen

Grundlegende Funktionen

```powershell

Simple function

function Say-Hello \\{ Write-Host "Hello World!" \\}

Function with parameters

function Say-HelloTo \\{ param( [string]$Name ) Write-Host "Hello, $Name!" \\}

Function with return value

function Add-Numbers \\{ param( [int]$a, [int]$b ) return $a + $b \\}

Call functions

Say-Hello Say-HelloTo -Name "John" $result = Add-Numbers -a 5 -b 3 ```_

Erweiterte Funktionen

```powershell function Get-SystemInfo \\{ [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$ComputerName,

    [Parameter()]
    [switch]$IncludeServices
)

$info = Get-ComputerInfo -ComputerName $ComputerName

if ($IncludeServices) \\\\{
    $services = Get-Service -ComputerName $ComputerName
    $info|Add-Member -NotePropertyName Services -NotePropertyValue $services
\\\\}

return $info

\\} ```_

Pipeline und Objekte

Pipeline Basics

```powershell

Basic pipeline

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

Select specific properties

Get-Process|Select-Object Name, CPU, WorkingSet

Format output

Get-Process|Format-Table Name, CPU, WorkingSet Get-Process|Format-List Name, CPU, WorkingSet ```_

Objektbearbeitung

```powershell

Create custom objects

$person = [PSCustomObject]@\\{ Name = "John" Age = 30 City = "New York" \\}

Add properties

$person|Add-Member -NotePropertyName Email -NotePropertyValue "john@email.com"

Filter objects

Get-Process|Where-Object \\{$_.ProcessName -like "chrome*"\\}

Group objects

Get-Process|Group-Object ProcessName

Measure objects

Get-Process|Measure-Object WorkingSet -Sum -Average -Maximum ```_

Datei- und Textverarbeitung

Dateioperationen

```powershell

Read file line by line

Get-Content file.txt|ForEach-Object \\{ Write-Host "Line: $_" \\}

Search in files

Select-String -Path "*.txt" -Pattern "error"

Replace text in files

(Get-Content file.txt) -replace "old", "new"|Set-Content file.txt

Get file information

Get-ItemProperty file.txt Get-ChildItem *.txt|Select-Object Name, Length, LastWriteTime ```_

Textverarbeitung

```powershell

String operations

$text = "Hello World" $text.ToUpper() $text.ToLower() $text.Replace("World", "PowerShell") $text.Split(" ") $text.Substring(0, 5)

Regular expressions

$text = "Phone: 123-456-7890" if ($text -match "\d\\{3\\}-\d\\{3\\}-\d\\{4\\}") \\{ Write-Host "Phone number found: $($matches[0])" \\} ```_

Systemverwaltung

Prozessmanagement

```powershell

Get processes

Get-Process Get-Process -Name "notepad" Get-Process|Where-Object \\{$_.CPU -gt 100\\}

Start process

Start-Process notepad Start-Process -FilePath "C:\Program Files\App\app.exe" -ArgumentList "/silent"

Stop process

Stop-Process -Name "notepad" Stop-Process -Id 1234 ```_

Service Management

```powershell

Get services

Get-Service Get-Service -Name "Spooler" Get-Service|Where-Object \\{$_.Status -eq "Running"\\}

Start/Stop services

Start-Service -Name "Spooler" Stop-Service -Name "Spooler" Restart-Service -Name "Spooler"

Set service startup type

Set-Service -Name "Spooler" -StartupType Automatic ```_

Register Operationen

```powershell

Navigate registry

Set-Location HKLM:\SOFTWARE

Get registry values

Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"

Set registry values

Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting" -Value "Value"

Create registry keys

New-Item -Path "HKCU:\Software\MyApp" ```_

Netzwerkaktivitäten

Netzwerkkommandos

```powershell

Test network connectivity

Test-Connection google.com Test-NetConnection google.com -Port 80

Get network configuration

Get-NetIPConfiguration Get-NetAdapter

DNS operations

Resolve-DnsName google.com Clear-DnsClientCache ```_

Web-Anfragen

```powershell

Simple web request

Invoke-WebRequest -Uri "https://api.github.com/users/octocat"

REST API calls

$response = Invoke-RestMethod -Uri "https://api.github.com/users/octocat" $response.name

Download files

Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip" ```_

Fehlerbehebung

Test-Katch-Finally

powershell try \\\\{ $result = 10 / 0 \\\\} catch [System.DivideByZeroException] \\\\{ Write-Host "Cannot divide by zero!" \\\\} catch \\\\{ Write-Host "An error occurred: $($_.Exception.Message)" \\\\} finally \\\\{ Write-Host "Cleanup code here" \\\\}_

Fehlervariablen

```powershell

Check last error

$Error[0]

Clear errors

$Error.Clear()

Error action preference

$ErrorActionPreference = "Stop" # Stop, Continue, SilentlyContinue ```_

Module und Snap-Ins

Modulmanagement

```powershell

List available modules

Get-Module -ListAvailable

Import module

Import-Module ActiveDirectory

Get module commands

Get-Command -Module ActiveDirectory

Install module from PowerShell Gallery

Install-Module -Name Az ```_

Module erstellen

```powershell

Create module file (MyModule.psm1)

function Get-Greeting \\{ param([string]$Name) return "Hello, $Name!" \\}

Export-ModuleMember -Function Get-Greeting

Import custom module

Import-Module .\MyModule.psm1 ```_

Best Practices Scripting

Schriftstruktur

```powershell

Requires -Version 5.1

Requires -Modules ActiveDirectory

<# .SYNOPSIS Brief description of script .DESCRIPTION Detailed description .PARAMETER Name Description of parameter .EXAMPLE Example usage

>

[CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$Name )

Script logic here

Write-Verbose "Processing $Name" ```_

Parametervalidierung

```powershell param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name,

[Parameter()]
[ValidateRange(1,100)]
[int]$Age,

[Parameter()]
[ValidateSet("Red","Green","Blue")]
[string]$Color

) ```_

Erweiterte Funktionen

Jobs

```powershell

Start background job

$job = Start-Job -ScriptBlock \\{ Get-Process \\}

Get job status

Get-Job

Receive job results

Receive-Job $job

Remove job

Remove-Job $job ```_

Entfernen

```powershell

Enable remoting

Enable-PSRemoting -Force

Create session

$session = New-PSSession -ComputerName "Server01"

Run commands remotely

Invoke-Command -Session $session -ScriptBlock \\{ Get-Process \\}

Enter interactive session

Enter-PSSession -Session $session

Close session

Remove-PSSession $session ```_

Desired State Configuration (DSC)

```powershell Configuration WebServer \\{ Node "WebServer01" \\{ WindowsFeature IIS \\{ Ensure = "Present" Name = "Web-Server" \\}

    File WebContent \\\\{
        Ensure = "Present"
        DestinationPath = "C:\inetpub\wwwroot\index.html"
        Contents = "<html><body>Hello World</body></html>"
    \\\\}
\\\\}

\\}

Compile configuration

WebServer -OutputPath "C:\DSC"

Apply configuration

Start-DscConfiguration -Path "C:\DSC" -Wait -Verbose ```_

Gemeinsame Betreiber

Vergleich Betreiber

powershell -eq # Equal -ne # Not equal -gt # Greater than -ge # Greater than or equal -lt # Less than -le # Less than or equal -like # Wildcard comparison -match # Regular expression match -contains # Collection contains value -in # Value in collection_

Logische Operatoren

powershell -and # Logical AND -or # Logical OR -not # Logical NOT ! # Logical NOT (alternative)_

Nützliche Cmdlets

Informationen sammeln

powershell Get-ComputerInfo Get-HotFix Get-EventLog -LogName System -Newest 10 Get-WmiObject -Class Win32_OperatingSystem Get-CimInstance -ClassName Win32_ComputerSystem_

Leistungsüberwachung

powershell Get-Counter "\Processor(_Total)\% Processor Time" | Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 | Measure-Command \\\\{ Get-Process \\\\}_

Ressourcen

  • *offizielle Dokumentation: Microsoft PowerShell Docs
  • *PowerShell Gallery: [PowerShell Gallery](LINK_3
  • Gemeinschaft: [PowerShell Community](__LINK_3___