r/PowerShell • • 12h ago

Question Do Constants give advantages?

So, we all know we can make a Constant by using New-Variable -Name 'ImTryingIguess" -Value 'whatever' -Option Constant
(or using Set-Variable the same way)

Question is: does using a constant instead of a regular variable give any advantage?
Like, smaller memory footprint or something?

So far, from what I managed to understand, its only effect is keeping people from altering the variable, which can be very useful with large scripts manned by multiple people, as one might decide to recycle a variable name that should otherwise stay untouched.

I personally prefix any "constant" name with CONST_(i.e.: $CONST_TitleTemplate) which, so far, has been working well, but I was wondering if I was missing some magic powershell shenanigan.

17 Upvotes

11 comments sorted by

28

u/kagato87 12h ago

Yes.

As with any programming language, it makes it harder to create a regression by throwing an error when something tries to change it later on. With a regular variable you could accidentally change it, which is a pain to troubleshoot.

It's a less common issue in powershell, but the effect is the same. It makes your code easier to maintain.

5

u/lan-shark 12h ago edited 6h ago

It's also used by the language itself for the automatic variables $true, $false, and maybe some others.

Edit: fixed names

4

u/surfingoldelephant 10h ago edited 1h ago

Those particular variables (originally $HOME and $IsWindows before the above comment was edited) are ReadOnly rather than Constant. Unlike constants, they can still be modified or removed with Set-/Remove-Variable -Force.

Also, Windows PowerShell has a type-constraining bug that allows either type to be modified:

$HOME = 1       # Error
[int] $HOME = 2 # OK
$HOME           # 2

That bug is fortunately fixed in v7.

1

u/lan-shark 6h ago

True, I forget they made those editable in Core for backwards compatibility. Fixed

1

u/BlackV 6h ago

I swear everytime you post I learn something new

4

u/DrSinistar 12h ago

Constants have never been useful for me in PowerShell.

4

u/Genmaken 6h ago

Constantly disappointed by them

2

u/uptimefordays 10h ago

No memory or perf win, a constant is the same PSVariable object with a flag set. You've got the main benefit right: protection against accidental reassignment. The catch is that `Constant` can't be removed for the life of its scope, so if you dot-source or re-run in the VS Code console you'll hit "variable is read-only or constant" until you restart the session. `ReadOnly` is usually the better tradeoff since `-Force` can clear it. For shared config, a module-scoped variable or a settings object is often cleaner than a pile of `CONST_ globals`.

1

u/NorCalFrances 11h ago

Only for code safety & ensuring the value / name doesn't accidentally get reused. Constants are treated by the PS interpreter as a variable with an extra flag, so technically there's a tiny bit of added overhead.

1

u/KevMar Community Blogger 10h ago

which can be very useful with large scripts manned by multiple people, as one might decide to recycle a variable name that should otherwise stay untouched.

If you break it up into multiple function and pass those values in as Parameters then this doesn't really happen so much. If they forget about it and reuse a variable name within the function, a new variable in local scope is created that doesn't change the original.

It's rare that I ever have a reason to call Set-Variable. It's usually a symptom of something else.

1

u/surfingoldelephant 9h ago edited 9h ago

if I was missing some magic powershell shenanigan

Not really. They're regular PSVariables with Constant set as the ScopedItemOptions. It's only enforced at runtime, meaning there's no protection during parse time. Also, because of PowerShell's dynamic scoping, it's still easy to unintentionally shadow a Constant/ReadOnly variable (unless it's also created with AllScope, but even that doesn't cover all scenarios). It can make using the debugger harder as well if you need to modify something on the fly.

There's also a bug in Windows PowerShell that allows them to be modified with type-constraining (fixed in v7):

New-Variable -Name foo -Value bar -Option Constant
[string] $foo = 'baz'
$foo # baz                

In their current state, personally I think Constant/ReadOnly options are best left to automatic variables. I'd only really consider using them for my own variables if they were reworked to be part of parse time.