Type Conflicts and Dynamic Casting in Powershell

Pavol Kutaj
2 min readFeb 2, 2021

--

The concern is documenting a mistake in the following code that aimed at adding a leading zero to the first nine months of the year (1 → 01)

$today = Get-Date
$yyyy = $today.Year.toString()
$MM = $today.Month.toString()
$MM = ($MM -lt 10) ? "0$MM" : $MM

1. dynamic casting

  • You can specify the type of a variable before it to force its type.
  • It’s called (dynamic) casting and cast notation

2. these are 13 PowerShell types

3. fix

$oneDay = New-TimeSpan -Days 1
$today = Get-Date
[string]$yyyy = $today.Year.toString()
$MM = $today.Month
$MM = ($MM -lt 10) ? "0" + [string]$MM : [string]$MM
  • and note that 🠋 is not working
  • the cast operator limits $MM to the integer type and is not recast via the ternary operator to string even if forced
$oneDay = New-TimeSpan -Days 1
$today = Get-Date
[string]$yyyy = $today.Year.toString()
[int]$MM = $today.Month
$MM = ($MM -lt 10) ? "0" + [string]$MM : [string]$MM
  • The Types of variables section of the official documentation is full of examples
  • the true condition will not re-cast $MM within the ternary operator into a string

4. sources

--

--

No responses yet