PowerShell Scripting Fundamentals
Welcome to the core of PowerShell automation! This section covers the essential concepts and syntax required to write powerful and efficient PowerShell scripts. Whether you're automating system administration tasks or developing complex workflows, mastering these fundamentals is key.
What is PowerShell Scripting?
PowerShell scripts are text files (with a .ps1
extension) containing a sequence of PowerShell commands and control flow statements. They allow you to automate repetitive tasks, manage systems at scale, and create custom tools.
Basic Syntax and Commands
PowerShell uses a verb-noun naming convention for its commands, known as cmdlets (pronounced "command-lets").
Get-Process
New-Item -Path "C:\MyFolder" -Name "NewFile.txt"
Stop-Service -Name "Spooler"
Variables
Variables are used to store data. They start with a dollar sign ($
).
$userName = "AdminUser"
$computerCount = 10
$isValid = $true
Write-Host "Processing user: $userName"
Write-Host "Number of computers: $computerCount"
Data Types
PowerShell supports various data types, including strings, integers, booleans, arrays, and hashtables.
Arrays: Ordered collections of items.
$servers = "Server01", "Server02", "Server03"
$servers[0] # Accesses the first element ("Server01")
Hashtables: Key-value pairs.
$userConfig = @{
UserName = "jdoe"
Department = "IT"
Active = $true
}
$userConfig["Department"] # Returns "IT"
Control Flow
Control flow statements allow you to dictate the execution path of your script based on conditions.
If/Else Statements
Execute code blocks based on whether a condition is true or false.
$diskSpace = Get-Volume -DriveLetter "C" | Select-Object -ExpandProperty SizeRemaining
$threshold = 10GB
if ($diskSpace -lt $threshold) {
Write-Warning "Low disk space on C: drive! Available: $([math]::Round($diskSpace / 1GB, 2)) GB"
} else {
Write-Host "Sufficient disk space on C: drive."
}
Loops
Repeat a block of code multiple times.
For Loop
for ($i = 1; $i -le 5; $i++) {
Write-Host "Iteration number: $i"
}
ForEach Loop
Iterate over items in a collection.
$files = Get-ChildItem -Path "C:\Logs" -Filter "*.log"
foreach ($file in $files) {
Write-Host "Processing log file: $($file.Name)"
# Add more actions here
}
Error Handling
Robust scripts gracefully handle errors.
Try-Catch-Finally
blocks for structured error handling.
try {
$result = Invoke-Command -ComputerName "NonExistentServer" -ScriptBlock { Get-Date }
Write-Host "Command executed successfully."
} catch {
Write-Error "An error occurred: $($_.Exception.Message)"
} finally {
Write-Host "Script execution finished."
}
Comments
Use comments to explain your code. Single-line comments start with #
.
# This is a single-line comment
$value = 10 # This comment explains the variable assignment
Block comments are enclosed in <# ... #>
.
<#
This is a multi-line comment.
It can span several lines
to provide detailed explanations.
#>
Next Steps
Now that you understand the fundamentals, explore advanced topics like creating functions, building modules, and leveraging PowerShell remoting to manage your infrastructure more effectively.