Protego field desk
Data and Scripting Basics · Core scripting

L4. Variables, Types, Arrays, and Hashtables

Course outlineLesson 4 of 10
PowerShell Zero to Hero: course overview

Build reliable scripts by understanding variables, type conversion, arrays, hashtables, PSCustomObject, string interpolation, and when to use each data structure.

Variables and Types

PowerShell variables start with $. They can hold strings, numbers, dates, arrays, hashtables, command output, or full objects.

$name = 'Protego'
$count = 3
$now = Get-Date
$services = @(Get-Process)
$services.GetType().FullName

PowerShell is flexible, but production scripts should still be explicit where mistakes are expensive:

[int]$retryCount = 3
[datetime]$deadline = '2026-07-15'

Arrays

Arrays hold ordered lists:

$servers = @('web01', 'web02', 'db01')
$servers[0]
$servers | ForEach-Object { "Checking $_" }

Before PowerShell 7.5, repeatedly appending to an array with += reallocates it and can be expensive. PowerShell 7.5 optimized array addition. Collecting pipeline output with @(...) or using a generic list remains useful when supporting older versions. Array subexpressions also keep zero or one result as an array.

Hashtables

Hashtables store key-value pairs:

$config = @{
  Environment = 'Prod'
  Region = 'EastUS'
  RetentionDays = 30
}

$config['Region']
$config.RetentionDays

Hashtables are also used for splatting, which makes long commands safer to read:

$params = @{
  Path = '.\report.txt'
  Value = 'Inventory complete'
  Encoding = 'utf8'
}
Set-Content @params

PSCustomObject

[pscustomobject]@{
  ComputerName = [System.Environment]::MachineName
  PowerShell = $PSVersionTable.PSVersion.ToString()
  Timestamp = (Get-Date).ToString('o')
}

Use [pscustomobject] when you want clean structured output from your own script.

Lab

  1. Create an array of three hostnames.
  2. Create a hashtable with environment settings.
  3. Use splatting with Get-ChildItem: create $listParams = @{ Path = "."; File = $true }, then run Get-ChildItem @listParams.
  4. Build a [pscustomobject] inventory record.

References

Continue Learning

Exam Focus Points
  • ✓Variables can hold full objects, not only strings
  • ✓Arrays are ordered lists; hashtables are key-value maps
  • ✓Splatting passes a hashtable of parameters to a command using @params
  • ✓Use PSCustomObject for clean structured script output
  • ✓Add explicit type annotations when conversion errors would be risky
Knowledge Check

1. Which syntax passes a hashtable of named parameters to a command?

2. When should you use PSCustomObject?