What Order Are Variables Read in Powershell
Using PowerShell to set up Windows surround variables, read surround variables and create new surroundings variables is easy once you know the play a trick on. The tricks you learn in this article will work for Windows ten environment variables as well as whatever Windows client/server after Windows vii SP1/Windows Server 2008.
PowerShell provides many dissimilar ways to interact with Windows surroundings variables from the $env: PSDrive. the registry, and the [Organization.Environment] .NET course. Yous'll learn about each method including understand environment variable scope in this step-past-step walkthrough.
Assumptions
Throughout this commodity, I'll be using Windows PowerShell 5.1 on Windows ten. But if yous have whatever version of Windows PowerShell later than v3 on Windows 7 SP1 or later, the techniques I'1000 most to bear witness y'all should piece of work just fine.
What are Surround Variables?
Surroundings variables, every bit the name suggests, store information about the environment that is used past Windows and applications. Environs variables tin be accessed by graphical applications such equally Windows Explorer and plainly text editors similar Notepad, every bit well as the cmd.exe and PowerShell.
Using surround variables helps y'all to avert hard-coding file paths, user or calculator names and much more in your PowerShell scripts or modules.
Common Environment Variables
Equally you begin to learn more nearly how to piece of work with environment variables in PowerShell, you'll come up across many unlike variables. Some are more useful than others. Below is a list of some of the common surround variables and their usage for reference.
| Variable | Usage |
|---|---|
| ClientName | The name of the remote computer connected via a Remote Desktop session. |
| SessionName | This helps to identify if the electric current Windows session is regarded by the operating system every bit running at the panel. For panel sessions SessionName will exist 'Console'. Enhanced Session connections to Hyper-5 Virtual Machines do not written report SessionName as 'Console', whereas Standard Sessions practise. |
| ComputerName | The proper noun of the computer. |
| SystemRoot and Windir | The path to the current Windows installation. |
| ProgramFiles and ProgramFiles(x86) | The default locations for x64 and x86 programs. |
| ProgramW6432 | The default location for programs, avoiding 32/64 bit redirection. This variable only applies for 32 bit processes running on a 64 bit platform. This ways that you can use information technology to identify when a 32 bit instance of PowerShell is running on a 64 bit organization. |
| UserDNSDomain | The Fully Qualified Domain Proper noun of the Active Directory domain that the current user logged on to. Only nowadays for domain logons. |
| UserDomain | The NETBIOS-style proper name of the domain that the current user logged on to. Tin be a computer proper noun if in that location'south no domain. |
| UserDomainRoamingProfile | The location of the key re-create of the roaming profile for the user, if any. Only present for domain logons. |
| UserName | The proper name of the currently logged on user. |
| UserProfile | The location of the profile of the current user on the local computer. |
Environment Variable Scopes
There are 3 scopes of environs variables. Call back of scopes as layers of variables that build upwards to give a total movie. Combined, these "layers" provide many different environment variables to any running process in Windows.
Surround Variable Scope "Bureaucracy"
Each of these "layers" either combine or overwrite i another. They are defined in a hierarchy similar: machine –> user –> process with each scoped variable overwriting the parent variable if ane exists in the parent scope.
For example, a common environs variable is TEMP. This variable stores the folder path to Windows' local temporary binder. This environment variable is set to:
-
C:\WINDOWS\TEMPin the motorcar scope -
C:\Users\<username>\AppData\Local\Tempin the user telescopic -
C:\Users\<username>\AppData\Local\Tempin the procedure telescopic.
If there's no TEMP surroundings variable set in the user scope then the end result volition be C:\WINDOWS\TEMP.
Environs Variable Scope Types
At that place are 3 different environment variable scopes in Windows.
Motorcar
Environs variables in the machine telescopic are associated with the running instance of Windows. Whatever user account tin can read these, only setting, irresolute or deleting them needs to washed with elevated privileges.
User
Environment variables in the user scope are associated with the user running the current process. User variables overwrite car-scoped variables having the same name.
Notation: Microsoft recommends that Machine and User scoped surround variable values incorporate no more 2048 characters.
Process
Environment variables in the process telescopic are a combination of the car and user scopes, along with some variables that Windows creates dynamically.
Below is a list of surround variables available to a running process. All of these variables are dynamically created.
-
ALLUSERSPROFILE -
APPDATA -
COMPUTERNAME -
HOMEDRIVE -
HOMEPATH -
LOCALAPPDATA -
LOGONSERVER -
PROMPT -
PUBLIC -
SESSION -
SystemDrive -
SystemRoot -
USERDNSDOMAIN -
USERDOMAIN -
USERDOMAIN_ROAMINGPROFILE -
USERNAME -
USERPROFILE
Environment Variables in the Registry
Environment variables are stored in two registry locations, one for the user scope and i for the machine scope.
Don't Use the Registry to Manage Surround Variables
There'due south a catch when making changes to variables inside of the registry. Any running processes will not see variable changes in the registry. Processes only run into the registry variables and values that were present when the process was started, unless Windows notifies them that there has been a alter.
Instead of modifying the registry direct, yous can use a .Cyberspace form instead. The .NET [System.Environment] grade can alter machine and user–scoped environment variables and handle the registry housekeeping for you.
Modifying environs variables in the registry directly, whilst possible, doesn't make sense. The .Net class offers a simpler, Microsoft-supported approach. You lot'll learn about using the [Arrangement.Surroundings] .NET class after in this article.
Environment Variable Registry Locations and Querying
I hope y'all've been convinced to not modify the registry straight but if yous'd similar to accept a peek at what's in at that place, you lot tin find all user environment variables in the HKEY_CURRENT_USER\Environment key. Auto-scoped surround variables are stored at HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Director\Environment.
Inside of either of these keys lies registry values of blazon REG_SZ or REG_EXPAND_SZ. REG_EXPAND_SZ values concord surround variables embedded as part of their value. These environment variables are expanded when the value is retrieved.
To demonstrate this, use the REG utility. This is a small control-line utility included with Windows.
Query the TEMP environment variable as seen below. Run REG with the QUERY parameter to call back the value of the TEMP variable.
> REG QUERY HKCU\Environment /V TEMP HKEY_CURRENT_USER\Environs TEMP REG_EXPAND_SZ %USERPROFILE%\AppData\Local\Temp You'll sometimes detect environment variables displayed surrounded by percentage symbols (
%COMPUTERNAME%) like above. This is the onetime-school fashion of showing environment variables via cmd.exe and batch files. Know that PowerShell does not recognize this format.
The REG utility allows united states to come across the native value of the registry value. The value type is REG_EXPAND_SZ and the value contains the %USERPROFILE% environment variable.
If you'd rather apply PowerShell to think the registry value, yous can so using the Get-Item cmdlet as shown below.
PS51> Get-ItemProperty -Path HKCU:\Surroundings -Name TEMP TEMP : C:\Users\<your username>\AppData\Local\Temp PSPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Environment PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER PSChildName : Surroundings PSDrive : HKCU PSProvider : Microsoft.PowerShell.Core\Registry View and Set Windows Environs Variables via the GUI
To run into a GUI view of the user and organisation environment variables, run SystemPropertiesAdvanced.exe from PowerShell, a control prompt or from Windows Primal+R to brandish the Organization Properties Avant-garde tab. Click on the EnvironmentVariables button, which is highlighted in the epitome below.
The Surround Variables dialog, shown beneath, allows you lot to view, create and alter user and auto-scoped environment variables. Note that the dialog refers to motorcar scoped variables as System variables.
At present that you have an understanding of environment variables, allow's become to what you're here for, managing them with PowerShell!
In that location are a few dissimilar ways you tin interact with environment variables using PowerShell.
- The
Env:PSDrive and Provider – session-based. Merely sets the values of environs variables for the current PowerShell session -
$env:variables – session-based. Simply sets the values of environment variables for the current PowerShell session - The
[System.Environment].NET Class – allows you to persist user and system-scoped environment variables across sessions and reboots
The Env: PSDrive and Provider
Ane of the best way to read environment variables is a PowerShell concept known as PowerShell drives (PS drives). A PS drive allows you to treat environment variables equally if they are a file organisation through the Env: drive.
Switching to the Env: Drive
Like all PS drives, you reference it via paths similar Env:\TEMP, Env:\COMPUTERNAME, etc. But to save some keystrokes, switch to the Env: drive just as yous would any file system drive, as shown below.
PS51> cd Env: PS51 Env:\> ## or PS51> Set-Location Env: PS Env:\> Tab-Completion with the Env: Drive
Yous can use the same commands you would use to access a file system, such every bit Get-Detail and Get-ChildItem to access surroundings variables. Just instead of the file organisation, yous're reading the Env: drive.
Because environment variables are stored in a PS drive, you can utilise the tab completion feature of PowerShell to cycle through the bachelor variables, as shown below.
Permit's now spring into a couple examples of how you tin use the Env: PS drive to work with surroundings variables.
Listing Environment Variables with Env:
PS51> Get-Item -Path Env: PS51> Go-Item -Path Env:USERNAME Listing Environment Variables Using a Wildcard with Env:
PS51> Get-Item -Path Env:user* Finding Environment Variable Values with Env:
The results of these commands are key/value [System.Collections.DictionaryEntry] .NET objects. These objects concord the environment variable'due south name in the Name property and the value in the Value property.
You can access a specific value of an environment variable by wrapping the Get-Item control reference in parentheses and referencing the Value property as shown beneath:
PS51> (Get-Item -Path Env:computername).Value MYCOMPUTERHOSTNAME In situations where y'all need to only render certain surroundings variables, use standard PowerShell cmdlets such as Select-Object and Where-Object to select and filter the objects returned by the Env: provider.
In the example beneath, simply the surround variable COMPUTERNAME is returned.
PS51> Get-ChildItem -Path Env: | Where-Object -Property Name -eq 'COMPUTERNAME' As an culling method, use the Get-Content cmdlet. This cmdlet returns a [String] object containing the value of the environment variable. This object is simpler to bargain with as it returns only the value, rather than an object with Name and Value properties.
PS51> Go-Content -Path Env:\COMPUTERNAME Demo: Inserting Environment Values in a String
Using Get-Content, yous can find the value of an environs variable and insert the COMPUTERNAME environment variable, for case, into a text string.
PS51> 'Computer Name is: {0}' -f (Get-Content -Path Env:COMPUTERNAME) Computer Name is: MYCOMPUTER Setting an Environs Variable (And Creating) with Env:
Create new environment variables with PowerShell using the New-Item cmdlet. Provide the proper noun of the environs variable in the class Env:\<EnvVarName> for the Name value and the value of the surround variable for the Value parameter as shown below.
PS51> New-Item -Path Env:\MYCOMPUTER -Value MY-WIN10-PC Name Value ---- ----- MYCOMPUTER MY-WIN10-PC Use the Set-item cmdlet to set an environment variable, or create a new one if it doesn't already exist. You tin see beneath using the Set-Item cmdlet, you tin can both create or modify and surroundings variable.
PS51> Ready-Item -Path Env:testvariable -Value "Alpha" Copying an Surroundings Variable with Env:
Sometimes the state of affairs arises that you need to replicate the value of an environment variable. You lot can do this using the Copy-Item cmdlet.
Below you lot tin can see that the value of the COMPUTERNAME variable is copied to MYCOMPUTER, overwriting its existing value.
PS51> Get-Item -Path Env:\MYCOMPUTER Name Value ---- ----- MYCOMPUTER MY-WIN10-PC PS51> Copy-Item -Path Env:\COMPUTERNAME -Destination Env:\MYCOMPUTER PS51> Become-Particular -Path Env:\MYCOMPUTER Proper name Value ---- ----- MYCOMPUTER WIN10-1903 Removing an Environment Variable with Env:
Situations will arise where an environs variable is no longer needed. You tin can remove environment variables using one of iii methods:
- Use the
Prepare-Detailcmdlet to set an surround variable to an empty value
PS51> Set-Detail -Path Env:\MYCOMPUTER -Value '' - Employ the
Remove-Detailcmdlet.
PS51> Remove-Item -Path Env:\MYCOMPUTER - Apply the
Articulate-Itemcmdlet.
PS51> Articulate-Item -Path Env:\MYCOMPUTER Renaming an Environment Variable with Env:
In situations where the proper noun of an environment variable needs to be changed, yous take the pick to rename, rather than delete and recreate with the Env: provider.
Use the Rename-Item cmdlet to modify the name of an environment variable whilst keeping its value. Beneath you tin meet that you can see that the MYCOMPUTER variable is renamed to OLDCOMPUTER whilst retaining its value.
PS51> Rename-Item -Path Env:\MYCOMPUTER -NewName OLDCOMPUTER PS51> Go-Item -Path OLDCOMPUTER Name Value ---- ----- OLDCOMPUTER WIN10-1903 $Env: Variables
Having mastered the Env: drive to treat environment variables as files, this section shows you how to treat them as variables. Another way yous can manage in-session environment variables is using the the PowerShell Expression Parser. This feature allows you to use the $Env: scope to admission surround variables.
Getting an Surroundings Variable with $Env:
Using the $Env scope, you can reference environment variables straight without using a command like Get-Item as shown below.
This method makes it like shooting fish in a barrel to insert environment variables into strings like below:
PS51> "The Estimator Proper name is {0}" -f $env:computername The Computer Name is WIN10-1809 PS51> "The Calculator Name is $env:computername" The Estimator Name is WIN10-1809 Setting or Creating an Environment Variable with $Env:
Setting an environs variable using this method is straightforward. This volition also create a new environs variable if one does not already exist similar beneath.
PS51> $env:testvariable = "Alpha" Apply the += syntax to add to an existing value, rather than overwriting it.
PS51> $env:testvariable = "Alpha" PS51> $env:testvariable += ",Beta" PS51> $env:testvariable Alpha,Beta Removing an Environs Variable with $Env:
To remove an environment variable using this method, simple set up its value to an empty cord.
PS51> $env:testvariable = '' Using the [System.Surround] .NET Class
The .Net class [Organisation.Environment] offers methods for getting and setting surround variables besides. This is only method to access various surroundings scopes straight and set environment variables that survive across PowerShell sessions.
In all of the following examples, if no scope is provided, the process scope is assumed.
When using the [Organisation.Surroundings], you'll utilize a few unlike .NET static class methods. You don't demand to empathise what a static method is. You but need to understand to use any of the techniques you lot're about to learn, you'll demand to first reference the class ([Organisation.Surroundings]) followed by two colons (::) then followed past the method.
List Environment Variables with [System.Environs]
If you lot'd like to see all surroundings variables in a particular scope, you'd use the GetEnvironmentVariables method. This method returns all environment variables by the scope specified as the method argument (in parentheses).
PS51> [System.Environment]::GetEnvironmentVariables('User') PS51> [Arrangement.Environs]::GetEnvironmentVariables('Car') PS51> [System.Environment]::GetEnvironmentVariables('Procedure') # The same as Procedure PS51> [System.Surroundings]::GetEnvironmentVariables() Getting Single Environment Variables with [System.Surround]
If you need to find a specific environment variable you tin do so two different means.
-
GetEnvironmentVariables().<var name>– not recommended -
GetEnvironmentVariable('<var name>','<scope>')
GetEnvironmentVariables()
Using the GetEnvironmentVariables() method, y'all use dot notation to reference the value. Enclose the [System.Environment] class and static method reference in parentheses followed by a dot then the name of the environment variable similar below:
PS51> ([System.Environment]::GetEnvironmentVariables()).APPDATA Note that when referencing surround variables this way, you lot must ensure yous friction match capitalization! In the example higher up, attempt to reference the
APPDATAvariable usingappdata. Employ theGetEnvironmentVariable()instead.
GetEnvironmentVariable()
Rather than using the GetEnvironmentVariables() method, instead utilise GetEnvironmentVariable() to notice single surroundings variables. It gets effectually the issue with capitalization and also allows you to specify the scope.
To use this method, specify the environment variable proper name and the scope you lot'd like to look for that variable in separated by comma.
PS51> [System.Environment]::GetEnvironmentVariable('ComputerName','User') # Bare PS51> [System.Environs]::GetEnvironmentVariable('ComputerName','Machine') # Blank PS51> [System.Surround]::GetEnvironmentVariable('ComputerName','Procedure') WIN10-1903 # The same as Process PS51> [Arrangement.Environment]::GetEnvironmentVariable('ComputerName') WIN10-1903 Setting an Environment Variable with [System.Environment]
Apply the SetEnvironmentVariable() method to set the value of an environs variable for the given scope, or create a new one if it does not already be.
When setting variables in the procedure scope, you'll notice that the process scope is volatile while changes to the user and machine scopes are permanent.
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Alpha','User') PS51> [System.Surroundings]::SetEnvironmentVariable('TestVariable','Alpha','Procedure') PS51> [Arrangement.Environment]::SetEnvironmentVariable('TestVariable','Alpha','Motorcar') # The same as Process PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Blastoff') Notation: Calling the SetEnvironmentVariable method with a variable proper name or value of 32767 characters or more volition cause an exception to be thrown.
Removing an Environment Variable with [System.Surroundings]
Use the SetEnvironmentVariable() method to remove an environment variable for the given scope by setting its value to an empty string.
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '', 'User') PS51> [Organization.Surroundings]::SetEnvironmentVariable('TestVariable', '', 'Process') PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '', 'Machine') # The same as process PS51> [Arrangement.Environment]::SetEnvironmentVariable('TestVariable', '') Useful PowerShell Environs Variables
Like many other Windows applications, PowerShell has some environs variables of it's own. Two useful surroundings variables to know about are PSExecutionPolicyPreference and PSModulePath.
PSExecutionPolicyPreference
The PSExecutionPolicyPreference environment variable stores the current PowerShell execution policy. Information technology is created if a session-specific PowerShell execution policy is set past:
- Running the
Set-ExecutionPolicycmdlet with aScopeparameter ofProcess - Running the
powershell.exeexecutable to start a new session, using theExecutionPolicycommand line parameter to set up a policy for the session.
PSModulePath
The PSModulePath environment variable contains the path that PowerShell searches for modules if you do non specify a full path. It is formed much similar the standard PATH environment variable, with individual directory paths separated past a semicolon.
PS51> $env:PSModulePath C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules Quick tip: Split each folder to get a string array to process each path individually using $env:PSModulePath.split(';')
Summary
Environment variables are a useful method for getting data about a running system, or storing information beyond sessions and reboots. Whether you lot're just reading the default Windows operating organisation surround variables and creating your own, y'all now tin can manage them using a variety of means with PowerShell!
Further Reading
- about_Environment_Variables
- The .NET [Arrangement.Environment] Class on Microsoft docs
- Learn the PowerShell string format and expanding strings
Source: https://adamtheautomator.com/powershell-environment-variables/
0 Response to "What Order Are Variables Read in Powershell"
Post a Comment