PowerShell Cheatsheet
Sinopsis
PowerShell es una solución de automatización de tareas multiplataforma compuesta por un shell de línea de comandos, un lenguaje de scripting y un marco de gestión de configuración.
Comandos básicos
Obtener ayuda
# 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
Navegación
# 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 ..
Operaciones de archivo
# 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
Variables y tipos de datos
Variables
# 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"]
Tipos de datos
# 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"
Estructuras de control
Declaraciones condicionales
# 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
# 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")
Funciones
Funciones básicas
# 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
Funciones avanzadas
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 and Objects
Pipeline Basics
# 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
Manipulación de objetos
# 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
Procesamiento de archivos y textos
Operaciones de archivo
# 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
Procesamiento de texto
# 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])"
\\\\}
Administración del sistema
Gestión de procesos
# 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
Gestión de servicios
# 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
Operaciones de registro
# 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"
Operaciones de red
Comandos de red
# 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
Solicitudes web
# 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"
Manejo de errores
Try-Catch-Finally
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"
\\\\}
Variables de error
# Check last error
$Error[0]
# Clear errors
$Error.Clear()
# Error action preference
$ErrorActionPreference = "Stop" # Stop, Continue, SilentlyContinue
Módulos y complementos
Gestión del módulo
# 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
Creación de módulos
# 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
Guiones Mejores Prácticas
Estructura del script
#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"
Validación del parámetro
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter()]
[ValidateRange(1,100)]
[int]$Age,
[Parameter()]
[ValidateSet("Red","Green","Blue")]
[string]$Color
)
Características avanzadas
Empleo
# 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
Remoción
# 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)
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
Operadores comunes
Operadores de comparación
-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
Operadores lógicos
-and # Logical AND
-or # Logical OR
-not # Logical NOT
! # Logical NOT (alternative)
Cmdlets útiles
Reunión de información
Get-ComputerInfo
Get-HotFix
Get-EventLog -LogName System -Newest 10
Get-WmiObject -Class Win32_OperatingSystem
Get-CimInstance -ClassName Win32_ComputerSystem
Supervisión de la ejecución
Get-Counter "\Processor(_Total)\% Processor Time"
Get-Process|Sort-Object CPU -Descending|Select-Object -First 10
Measure-Command \\\\{ Get-Process \\\\}
Recursos
- ** Documentación oficial**: Microsoft PowerShell Docs
- PowerShell Gallery: PowerShell Gallery
- Comunidad: PowerShell Community