Are There Ternary Operators in Powershell

usecase

The concern is documenting the need to have a conditional assignment of value similar as in Javascript with ternary operators in the situation where I need to have automatically created a folder name based on the current month, but have a leading zero for the first 9 months.

1. usual if statement

$folder = If ($MM -lt 10) {"0$MM"} Else { "$MM"}

2. ternary

  • implemented in posh 7!
$folder = ($MM -lt 10) ? "0$MM" : $MM

CODE

  • here is the code for the context
function new-kron {
$oneDay = New-TimeSpan -Days 1
$today = Get-Date
$yyyy = $today.Year.toString()
$MM = $today.Month.toString()
$MM = ($MM -lt 10) ? "0$MM" : $MM
$yesterday = ($today - $oneDay).ToString("yyyy-MM-dd")
$kronFolder = "c:\Users\Admin\Documents\familia\kron\$yyyy\$MM-$yyyy\"
$kronPost = "$kronFolder\$yesterday.md"

if (Test-Path $kronPost) {
Invoke-Item $kronPost
}
else {
New-Item $kronPost
Set-Content $kronPost -Value "### $yesterday"
Invoke-Item $kronPost
}
}

3. sources

Written by

today I learnt… | as a support eng of the wonderful Snowplow Analytics, expect everything around modern (postmodern?) business intelligence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store