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.
Here is the reference to your issue. Determine the version of powershell
You may use the 'PSVersion' object in 'PSVersionTable' where 'Major' is the property to check the version and the invoke-command. The below modified code may look like this with if-else statement and should run the first line of code in Powershell 5.1 and the below code for version 7 should run only on Powershell 7.
Since the ternary operator '? :' was not available prior to Powershell 7 the if statement can be rewritten as
This should run on both 5.1 and 7 versions.