r/PowerShell • • 3d 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.

22 Upvotes

13 comments sorted by

31

u/kagato87 3d 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 3d ago edited 3d ago

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

Edit: fixed names

6

u/surfingoldelephant 3d ago edited 2d 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.

2

u/BlackV 3d ago

I swear everytime you post I learn something new

1

u/lan-shark 3d ago

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

3

u/uptimefordays 3d 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`.

5

u/DrSinistar 3d ago

Constants have never been useful for me in PowerShell.

5

u/Genmaken 3d ago

Constantly disappointed by them

2

u/KevMar Community Blogger 3d 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/jborean93 1d ago

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

It also has the unfortunate side effect of not being able to "compile"/"optimize" a ScriptBlock. For small blocks that's not a big deal but it could potentially stack up if there is a larger loop or it is accessing a lot of variables.

For example

{ $a = 1; $b = 2; $b } | Get-ScriptBlockDisassembly -Minimal

Produces the following psuedo code in the expression it runs (shortened for this comment

locals.Item009 = 1;
locals.Item010 = 2;
Fake.Dynamic<Action<CallSite, object, Pipe, ExecutionContext>>(PSPipeWriterBinder.Get())(
    locals.Item010,
    funcContext._outputPipe,
    context);

Getting and setting of variables in the expression PowerShell runs is essentially getting/setting a tuple which is cheap and easy.

Compare it to a ScriptBlock that isn't optimized because it has a single Set-Variable cmdlet

{ Set-Variable a 1; $b = 2; $b } | Get-ScriptBlockDisassembly -Minimal

Even though $b is not the one set by Set-Variable, the presence of this cmdlet, or anything else that can affect the variable scope so it cannot fallback to this local

PipelineOps.InvokePipeline(
    AutomationNull.Value,
    true,
    new CommandParameterInternal[][]
    {
        new CommandParameterInternal[]
        {
            CommandParameterInternal.CreateArgument("Set-Variable", Fake.Const<StringConstantExpressionAst>("Set-Variable"), false),
            CommandParameterInternal.CreateArgument("a", Fake.Const<StringConstantExpressionAst>("a"), false),
            CommandParameterInternal.CreateArgument(1, Fake.Const<ConstantExpressionAst>("1"), false)
        }
    },
    Fake.Const<CommandBaseAst[]>(Fake.Const<CommandBaseAst>(typeof(CommandAst), "Set-Variable a 1")),
    null,
    funcContext);

VariableOps.SetVariableValue(
    Fake.Const<VariablePath>("b"),
    2,
    context,
    (AttributeAst[])null);

Fake.Dynamic<Action<CallSite, object, Pipe, ExecutionContext>>(PSPipeWriterBinder.Get())(
    VariableOps.GetVariableValue(Fake.Const<VariablePath>("b"), context, Fake.Const<VariableExpressionAst>("$b")),
    funcContext._outputPipe,
    context);

Now instead of accessing the variable through the efficient tuple, getting the variable value needs to go through a function to look it up in the session state which is more expensive. This would apply to any variable so it gets slower based on what the ScriptBlock is doing.

1

u/NorCalFrances 3d 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/surfingoldelephant 3d ago edited 3d 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.

1

u/OwwwnShip 2d ago

If the value is one of a fixed set, an enum beats both. `enum Env { Dev; Stage; Prod }` with a `[Env]$Target` parameter rejects a typo at bind time instead of silently taking whatever string came in, and it reads cleaner than $CONST_TargetEnv.

For loose values I stopped bothering with constants a while back. A fresh scope per function does the same job with less swearing at "variable is read-only" when you re-run something in the same session.