Using Classes (Initializing Properties - Part 2)

Class properties can be assigned a mandatory type and a default value. When you instantiate an object from a class, the properties are pre-populated and accept only the data type specified:

#requires -Version 5.0
class Info 
{ 
  # strongly typed properties with default values
  [String]
  $Name = $env:USERNAME

  [String]
  $Computer = $env:COMPUTERNAME
  
  [DateTime]
  $Date = (Get-Date)
}

# create instance
$infoObj = [Info]::new()

# view default (initial) values
$infoObj

# change value
$infoObj.Name = 'test'
$infoObj

Twitter This Tip! ReTweet this Tip!