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
## the concern is to create a markdown file situated into proper folder YYYY/mm-YYYY/YYYY-mm-dd.md 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\$yesterday.md"

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

63 Followers

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com