Are There Ternary Operators in Powershell


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


  • here is the code for the context
## the concern is to create a markdown file situated into proper folder YYYY/mm-YYYY/ with date of yesterday (my diary)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 # ternary operator
$yesterday = ($today - $oneDay).ToString("yyyy-MM-dd")
$kronFolder = "c:\Users\Admin\Documents\familia\kron\$yyyy\$MM-$yyyy\"
$kronPost = "$kronFolder\$"

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

3. sources



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
Pavol Kutaj

Pavol Kutaj


Infrastructure Support Engineer/Technical Writer ( with a passion for Python/writing documentation. More about me: