I'm trying to write a function that will run 1 line of code if run PowerShell 5.1, and a different line if code if run in PowerShell 7. The problem I am running into is that PowerShell 5.1 won't even execute the code because it doesn't know what to do with the ? in the ternary operator.
It returns the error "Unexpected token '?' in expression or statement".
Is there a way to tell PowerShell 5 to ignore a piece of code?
Here is an example:
Function MyTestFunction
{
$Value = 5
if ($PSVersionTable.PSVersion.Major -le 5)
{
if ($Value -eq 5) { "Value is 5" } else { "Value isn't 5" }
}
else
{
$Value -eq 7 ? "Value is 7" : "Value isn't 7"
}
}
I can get it to work by converting it to a string and using invoke-expression or a scriptblock. But this just seems sloppy to me. And it slows down the execution a bit.
$String = "'$Value -eq 7 ? '"Value is 7'" : '"Value isn't 7'""
Invoke-Expression -Command $String
& ([scriptblock]::Create($String))
I'm pretty sure there isn't but I'm hoping there's some command or setting that I'm not aware of in PowerShell 5 that will allow me to tell powershell to ignore the line of code
$Value -eq 7 ? "Value is 7" : "Value isn't 7"
when it's run in 5.1 so it will compile and execute.
Preferably Something that's doesn't require me to escape or convert the code.