scripting:powershell
Table of Contents
PowerShell Cheatsheet
Basic Syntax
- Variables: No need for explicit declaration.
```powershell
$x = 5 $name = "John" ```
- Comments:
```powershell
# This is a single-line comment
<# This is a multi-line comment #> ```
Data Types
- Common Types:
- String: `$text = “Hello”`
- Integer: `$x = 10`
- Array: `$arr = @(1, 2, 3)`
- Hashtable: `$hash = @{key = “value”}`
- Boolean: `$flag = $true`
Control Flow
- If-else statement:
```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"
}
```
- Loops:
- For loop:
```powershell
for ($i = 0; $i -lt 5; $i++) {
Write-Output $i
}
```
- While loop:
```powershell
$count = 0
while ($count -lt 5) {
Write-Output $count
$count++
}
```
- Foreach loop:
```powershell
$arr = @(1, 2, 3)
foreach ($item in $arr) {
Write-Output $item
}
```
Functions
- Defining a function:
```powershell
function Greet {
param ($name)
"Hello, $name"
}
Greet "John" ```
Data Structures
- Arrays:
```powershell
$arr = @(1, 2, 3) $arr += 4 ```
- Hashtables:
```powershell
$hash = @{ "key1" = "value1"; "key2" = "value2" }
$hash["key1"] = "newValue"
```
Error Handling
- Try-Catch-Finally Block:
```powershell
try {
$result = 10 / 0
} catch {
Write-Output "An error occurred: $_"
} finally {
Write-Output "Execution finished"
}
```
File Handling
- Reading a file:
```powershell
$content = Get-Content -Path "file.txt" Write-Output $content ```
- Writing to a file:
```powershell
"Hello, World!" | Out-File -FilePath "file.txt" ```
- Appending to a file:
```powershell
"Additional text" | Add-Content -Path "file.txt" ```
Cmdlets
- Getting Cmdlets: `Get-Command`
- Cmdlet Help: `Get-Help Get-Content`
- Piping: `Get-Process | Sort-Object CPU -Descending`
Importing Modules
- Importing a module:
```powershell
Import-Module -Name MyModule ```
Classes & Objects
- Defining a class:
```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
- Get processes: `Get-Process`
- Stop a process: `Stop-Process -Name notepad`
- List services: `Get-Service`
- Change directory: `Set-Location -Path C:\`
- Get current directory: `Get-Location`
Useful Tips
- Automatic Variables:
- `$?` - Status of last command (True/False)
- `$_` - Current pipeline object
- `$PSVersionTable` - PowerShell version information
- Filtering and Sorting:
```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.
scripting/powershell.txt · Last modified: 2025/02/13 09:48 by jmbargallo
