DevTools

Cheatsheet PowerShell

Shell de automação e scripting da Microsoft

Back to languages
PowerShell
26 cards found
Categories:
Versions:

Basic Commands


4 cards
Navigation
Get-Location        # pwd
Set-Location C:\    # cd
Get-ChildItem       # ls / dir
Get-ChildItem -Recurse -Filter *.ps1

Move around the system.

Help
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Command *service*
Get-Member -InputObject "text"

Discover commands.

Common Aliases
ls   → Get-ChildItem
cd   → Set-Location
cat  → Get-Content
cp   → Copy-Item
mv   → Move-Item
rm   → Remove-Item

Familiar shortcuts.

History and Execution
Get-History
Invoke-History 5  # re-run #5
Start-Transcript  # record session
Stop-Transcript

History and logging.

Pipeline and Objects


5 cards
Pipeline
Get-Process | Where-Object {
  $_.CPU -gt 100 }

Get-Service | Where-Object Status -eq
  "Running" | Select-Object Name

Chain commands with |.

Measure and Group
Get-ChildItem | Measure-Object -Property
  Length -Sum -Average

Get-Process | Group-Object ProcessName |
  Sort-Object Count -Descending

Statistics and grouping.

Where-Object
Get-ChildItem | Where-Object {
  $_.Length -gt 1MB }

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

Filter objects.

Select and Sort
Get-Process | Sort-Object CPU -Descending |
  Select-Object -First 10 Name, CPU

Get-ChildItem | Sort-Object Length |
  Format-Table Name, Length

Sort and select.

ForEach-Object
Get-ChildItem *.txt | ForEach-Object {
  Write-Host $_.Name $_.Length
}

1..10 | ForEach-Object { $_ * 2 }

Iterate over collections.

Files and Folders


4 cards
Read and Write
Get-Content file.txt
Get-Content file.txt -Tail 20
Set-Content file.txt "New text"
Add-Content log.txt "New line"

File contents.

Create and Copy
New-Item -Path . -Name "folder" -Type Dir
New-Item file.txt -ItemType File
Copy-Item a.txt b.txt
Move-Item old/ new/

Manipulate items.

Search Content
Select-String -Path *.log -Pattern "error"
Select-String -Path app.log -Pattern
  "exception" -Context 2,2

# Equivalent to grep

Search inside files.

Permissions and Attributes
Get-Acl file.txt
Get-Item file.txt | Select-Object
  Attributes, IsReadOnly

(Get-Item f.txt).IsReadOnly = $true

View and change properties.

System and Processes


4 cards
Processes
Get-Process
Get-Process -Name chrome
Stop-Process -Name notepad -Force
Start-Process "notepad.exe"
Get-Process | Sort-Object WS -Desc |
  Select -First 5

Manage processes.

Services
Get-Service
Get-Service -Name "wuauserv"
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "nginx"

Control Windows services.

Networking
Get-NetIPAddress
Get-NetTCPConnection -LocalPort 8080
Test-Connection google.com  # ping
Test-NetConnection host -Port 443

Network diagnostics.

System Information
Get-ComputerInfo
Get-CimInstance Win32_OperatingSystem
Get-Volume  # disks
Get-PhysicalDisk
$env:PATH

Hardware and OS.

Scripting


5 cards
Variables
$name = "Anna"
$list = @(1, 2, 3)
$hash = @{ key = "value"; n = 42 }

Write-Host "Hello $name"
$hash.key

Data types.

Try / Catch
try {
  Get-Content "C:\nonexistent.txt" -ErrorAction Stop
} catch {
  Write-Warning "Error: $_"
} finally {
  "Done"
}

Error handling.

Conditions
if ($x -gt 10) {
  "Greater"
} elseif ($x -eq 10) {
  "Equal"
} else {
  "Less"
}

# -eq -ne -gt -lt -ge -le

Conditional structures.

Loops
foreach ($item in $list) {
  Write-Host $item
}

for ($i = 0; $i -lt 10; $i++) { $i }

while ($x -lt 100) { $x *= 2 }

Iteration.

Functions
function Get-Greeting {
  param(
    [string]$Name = "World",
    [int]$Times = 1
  )
  1..$Times | ForEach-Object {
    "Hello, $Name!"
  }
}

Define functions with params.

Advanced


4 cards
Modules
Get-Module -ListAvailable
Import-Module ActiveDirectory
Install-Module -Name Posh-SSH
Find-Module -Name *azure*

Manage modules.

PowerShell Remoting
Enter-PSSession -ComputerName Server01
Invoke-Command -ComputerName Server01 {
  Get-Process | Select -First 5
}

Enable-PSRemoting -Force

Run remotely.

WMI / CIM
Get-CimInstance Win32_BIOS
Get-CimInstance Win32_LogicalDisk |
  Select DeviceID, @{N="GB Free";
  E={[math]::Round($_.FreeSpace/1GB,1)}}

Query hardware/OS.

Schedule Tasks
$action = New-ScheduledTaskAction -Execute
  "powershell.exe" -Argument "-File C:\script.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 8am
Register-ScheduledTask -TaskName "Backup"
  -Action $action -Trigger $trigger

Task Scheduler via PS.