Skip to content

In what conditions is a parameter disallowed because it is a read-only variable? #6377

@alx9r

Description

@alx9r

Sometimes read-only variables are allowed as parameters, other times they are not. Is there a rule or some understandable mechanism at play here? Is there a way to predict which names cause a VariableNotWritable error when used as parameters?

Steps to reproduce

& {param($PSEdition)} # fails
& { [bool]((Get-Variable PSEdition | % Options) -band 'Constant') } # true
& {param([Alias('PSEdition')]$__PSEdition)} # succeeds

Set-Variable IAmAConstant -Value 'constant value' -Option Constant
& { [bool]((Get-Variable IAmAConstant | % Options) -band 'Constant') } # true
& {param($IAmAConstant)} # succeeds

$m = New-Module {}
& $m { [bool]((Get-Variable PSEdition | % Options) -band 'Constant') } # true
& $m {param($PSEdition)} # succeeds

Expected behavior

I expected either all constant variables or none to be prohibited as parameters.

Actual behavior

In some cases constant variables are permitted as parameters, in other cases they cause errors like following:

Cannot overwrite variable PSEdition because it is read-only or constant.
At line:1 char:1
+ & {param($PSEdition)} # fails
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (PSEdition:String) [], SessionStateUnauthorizedAccessExce 
   ption
    + FullyQualifiedErrorId : VariableNotWritable

Environment data

> $PSVersionTable

Name                           Value                                            
----                           -----                                            
PSVersion                      6.0.0                                            
PSEdition                      Core                                             
GitCommitId                    v6.0.0                                           
OS                             Microsoft Windows 6.3.9600                       
Platform                       Win32NT                                          
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                          
PSRemotingProtocolVersion      2.3                                              
SerializationVersion           1.1.0.1                                          
WSManStackVersion              3.0                                              

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugIssue has been identified as a bug in the productResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions