Finding Read-Only and Constant Variables

by Mar 27, 2015

All PowerShell versions

Some variables are protected and cannot be changed. To identify these, take a look at this line:

Get-Variable |   
  Where-Object { $_.Options -like '*Constant*' -or $_.Options -like '*ReadOnly*' } |
  Select-Object -Property Name, Options, Description

The result looks similar to this:

 
Name                                           Options Description               
----                                           ------- -----------               
?                                   ReadOnly, AllScope Status des letzten Befehls
ConsoleFileName                     ReadOnly, AllScope Name der aktuellen Kons...
Error                                         Constant                           
ExecutionContext                    Constant, AllScope Die für Cmdlets verfügb...
false                               Constant, AllScope Boolean False             
HOME                                ReadOnly, AllScope Ordner mit dem Profil d...
Host                                Constant, AllScope Ein Verweis auf den Hos...
PID                                 Constant, AllScope Aktuelle Prozess-ID       
PSCulture                           ReadOnly, AllScope Die Kultur der aktuelle...
PSHOME                              Constant, AllScope Der übergeordnete Ordne...
psISE                                         Constant                           
PSUICulture                         ReadOnly, AllScope Die Benutzeroberflächen...
psUnsupportedConsoleAppl...                   Constant                           
PSVersionTable                      Constant, AllScope Versionsinformationen f...
ShellId                             Constant, AllScope "ShellID" gibt die aktu...
true                                Constant, AllScope Boolean True            
 

The interesting part is how Where-Object identified the variables. The code used a string comparison and –like. That’s because the variable options are flags, and flags can be combined. By using –like and placeholders, you can (halfway) safely identify the flag you are after, even if additional flags have been set.

Twitter This Tip! ReTweet this Tip!