PowerShell offers a handy technique to handle system and user-specific settings by surroundings variables. These variables permit for straightforward configuration of assorted system parameters and may be accessed and manipulated inside PowerShell scripts.
On this article, we’ll discover the fundamentals of PowerShell surroundings variables, together with easy methods to set, get, and take away them, in addition to greatest practices for utilizing them in your scripts.
What does an Atmosphere Variable do?
An surroundings variable is a named worth that may have an effect on the way in which working processes behave on a pc. These variables are saved within the working system’s surroundings and may be accessed by any program or script that runs on the pc.
Atmosphere variables can be utilized to retailer numerous kinds of system or user-specific info, similar to paths to necessary information or directories, default program settings, and short-term knowledge.
By utilizing surroundings variables, applications may be designed to be extra versatile and moveable, as they’ll depend on the existence of sure variables with out hardcoding particular values.
In PowerShell, surroundings variables can be utilized to configure numerous facets of the system and to assist automate duties.
Easy PowerShell Atmosphere Variables
Atmosphere variables are an important facet of system configuration and administration.
In PowerShell, there are numerous built-in surroundings variables that present invaluable details about the working system, person, and system configuration.
These variables are utilized by many functions and scripts, making them a necessary instrument for system directors and builders.
A number of the frequent surroundings variables obtainable in PowerShell embody:
USERPROFILE
: This variable factors to the present person’s profile listing, the place user-specific information and settings are saved.TEMP
andTMP
: These variables level to the listing the place short-term information are saved. Many functions use these directories to put in writing short-term information.PATH
: This variable accommodates an inventory of directories separated by semicolons. These directories comprise executable information that may be executed from the command line with out specifying the total path.COMPUTERNAME
: This variable accommodates the title of the pc the place the script is working.USERNAME
: This variable accommodates the title of the present person who’s working the script
Atmosphere Variable Scopes
Atmosphere variables in PowerShell have a hierarchical scope. Which means variables can have totally different values relying on the extent of the scope they’re outlined in. The degrees of scope, so as of priority, are:
Course of
That is the default scope for surroundings variables. Course of-scoped surroundings variables can be found solely to the present PowerShell course of and any youngster processes that it creates. These variables aren’t seen to different processes or classes.
Consumer
Consumer-scoped surroundings variables can be found to the present person account and any processes which are run by that person. These variables aren’t seen to different customers on the identical pc.
System
System-scoped surroundings variables can be found to all customers on the pc. They’re set on the system stage and can be found to all processes and functions on the pc. These variables are sometimes used to outline system-wide settings or paths.
When a variable known as, PowerShell checks the hierarchy from high to backside to search out the primary matching definition of the variable.
If a variable is outlined at the next stage of the hierarchy, it’ll override any lower-level definitions of the identical variable title. This permits for flexibility in managing and utilizing surroundings variables in PowerShell.
Registry and Atmosphere Variables
Managing Atmosphere Variables
It’s not advisable to make use of the registry to handle surroundings variables in PowerShell. Whereas it’s potential to change surroundings variables by the registry, it may be a posh and error-prone course of.
Moreover, utilizing the registry can result in inconsistent habits throughout totally different variations of Home windows.
As an alternative, it’s endorsed to make use of PowerShell cmdlets and instruments to handle surroundings variables. This ensures that modifications are made in a constant and dependable method, and in addition simplifies the method for customers.
Registry Areas of Atmosphere Variables
In Home windows, surroundings variables may be saved and retrieved from the system registry. There are two foremost registry areas the place surroundings variables are saved:
- Consumer Atmosphere Variables: These are particular to a selected person and are saved within the registry beneath HKEY_CURRENT_USEREnvironment.
- System Atmosphere Variables: These variables can be found to all customers on the system and are saved within the registry beneath HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment.
To view the listing of surroundings variables saved within the registry, you should use the Registry Editor (regedit.exe). Navigate to one of many registry areas talked about above and you must see an inventory of surroundings variables and their values.
Notice: Modifying surroundings variables by the Registry Editor may be dangerous and isn’t advisable.
Utilizing the GUI to handle Home windows Atmosphere Variables
The GUI technique may be helpful for many who desire a visible interface or are much less acquainted with the command-line choices for managing surroundings variables. Nevertheless, it’s value noting that utilizing PowerShell or the command immediate may be faster and extra environment friendly for making bulk modifications to surroundings variables.
PSDrive and Supplier
Transferring to the Env: Drive
To change to the Env: drive, you merely have to sort Set-Location Env: or cd Env: within the PowerShell console. As soon as you’re within the Env: drive, you should use the usual PowerShell instructions to navigate and handle surroundings variables. For instance, to listing all surroundings variables, you should use the command Get-ChildItem.
Right here’s an instance of switching to the Env: drive in PowerShell:
PS C:> cd Env: PS Env:> dir
This may change the present location to the Env: drive and listing all of the surroundings variables obtainable.
Tab-Completion and the Env: Drive
The Env: drive in PowerShell permits for handy administration of surroundings variables inside scripts or the console. Along with the assorted strategies of managing surroundings variables, the Env: drive additionally offers tab-completion assist to shortly entry and modify variables.
Let’s say you need to shortly test the worth of the “TEMP” surroundings variable. As an alternative of typing out the total path “Get-ChildItem Env:TEMP
“, you’ll be able to merely sort “ls env:te
” and hit the Tab key to auto-complete the command to “ls env:TEMP
“. This will prevent a couple of keystrokes and make your PowerShell expertise extra environment friendly.
Cataloguing Atmosphere Variables with Env:
In PowerShell, the Env:
drive offers a technique to entry and handle surroundings variables. To listing all surroundings variables utilizing the Env:
drive, you should use the Get-ChildItem cmdlet with the Env: drive as the trail.
Right here’s an instance:
Get-ChildItem Env:
This may listing all of the surroundings variables and their values within the present console window. You can even use this command to retrieve the worth of a particular surroundings variable by specifying its title because the argument:
Wildcard Cataloguiing Atmosphere Variables with Env:
In PowerShell, you should use the Env:
drive to work with surroundings variables as in the event that they had been a file system. Which means you should use numerous methods for working with information and directories, similar to tab completion and wildcard growth, to work with surroundings variables.
A technique to make use of wildcards with the Env: drive is to make use of the Get-ChildItem cmdlet. For instance, to listing all surroundings variables that begin with “TEMP”, you should use the next command:
Get-ChildItem Env:TEMP*
This may return an inventory of surroundings variables that begin with “TEMP”, together with their values.
You can even use the -Filter parameter to specify a wildcard filter. For instance, to listing all surroundings variables that comprise the phrase “PATH”, you should use the next command:
Get-ChildItem Env: -Filter *PATH*
This may return an inventory of all surroundings variables that comprise the phrase “PATH”, together with their values.
Detecting Atmosphere Variable Values with Env
In PowerShell, you should use the Env: drive to work together with surroundings variables. One in all its helpful options is the power to shortly detect the values of surroundings variables. To do that, you should use the Get-ChildItem cmdlet with the Env: drive:
Get-ChildItem Env:
This may show an inventory of all surroundings variables and their corresponding values. If you wish to filter this listing to show solely sure surroundings variables, you should use the The place-Object cmdlet:
Get-ChildItem Env: | The place-Object { $_.Identify -like "Path" }
On this instance, the The place-Object cmdlet is used to filter the listing to solely show surroundings variables with the title “Path. You’ll be able to change “Path” with some other surroundings variable title to show its worth.
You can even entry the worth of a particular surroundings variable instantly by referencing it with the Env: drive. For instance, to get the worth of the “Path” surroundings variable, you should use:
$env:Path
This may show the worth of the “Path” surroundings variable. You’ll be able to change “Path” with some other surroundings variable title to entry its worth.
Including Atmosphere Values to a String
Including surroundings variable values to a string may be helpful for dynamically creating file paths or for setting configuration values in a script. In PowerShell, you should use the syntax $env:VariableName
to entry the worth of an surroundings variable.
So as to add an surroundings variable worth to a string, you should use string interpolation or string concatenation. Right here is an instance utilizing string interpolation:
$envVar = "USERPROFILE" $path = "$env:$envVarDocumentsexample.txt"
On this instance, the $envVar
variable accommodates the title of the surroundings variable we need to entry (USERPROFILE). We then use string interpolation to insert the worth of the surroundings variable into the $path variable. The ensuing worth of $path
could be one thing like C:UsersUsernameDocumentsexample.txt.
Making an Atmosphere Variable
To create a brand new surroundings variable in PowerShell, you should use the New-Merchandise cmdlet. The syntax for creating a brand new surroundings variable is:
New-Merchandise -Path Env:<variable_name> -Worth <variable_value>
Copying an Atmosphere Variable
To copy an surroundings variable in PowerShell, you’ll be able to merely assign the worth of the unique variable to a brand new variable:
$originalVariable = "Unique Worth" $newVariable = $originalVariable
This may create a brand new variable with the identical worth as the unique. Any modifications made to the brand new variable is not going to have an effect on the unique variable, as they’re now two separate variables.
Deleting an Atmosphere Variable
In PowerShell, you’ll be able to delete an surroundings variable utilizing the Take away-Merchandise cmdlet with the -LiteralPath parameter to specify the variable you need to delete.
Right here is an instance that exhibits easy methods to delete an surroundings variable named MY_VAR:
Take away-Merchandise -LiteralPath "Env:MY_VAR"
This command will take away the MY_VAR surroundings variable from the present person’s surroundings variables. Notice that if you wish to delete a system surroundings variable, that you must run the command as an administrator.
Renaming an Atmosphere Variable
To rename an surroundings variable in PowerShell, you should use the Rename-Merchandise cmdlet to rename the corresponding registry key.
Right here is an instance:
Rename-Merchandise -Path "HKCU:EnvironmentOldVariableName" -NewName "NewVariableName"
This renames the surroundings variable “OldVariableName” to “NewVariableName” by renaming the corresponding registry key situated at HKCU:EnvironmentOldVariableName.
$Env: Variables
Buying an Atmosphere Variable
Utilizing the $Env:
variable prefix in PowerShell means that you can retrieve the worth of a particular surroundings variable. You’ll be able to merely append the title of the surroundings variable to $Env: to retrieve its worth.
It is a fast and simple technique to entry surroundings variables with out having to make use of the Get-ChildItem Env
: or Get-Merchandise Env:
cmdlets.
Right here’s an instance of how you should use $Env: to get the worth of the TEMP surroundings variable:
$env:TEMP
This may return the trail to the short-term folder in your system.
Making an Atmosphere Variable
To set or create an surroundings variable utilizing $Env:
, you’ll be able to merely assign a worth to the variable utilizing the format $Env:VariableName
= “Worth”. If the surroundings variable already exists, its worth shall be up to date with the brand new worth. If it doesn’t exist, a brand new surroundings variable shall be created with the required worth.
Right here’s an instance of setting the MyVariable surroundings variable to a worth of 12345:
$Env:MyVariable = "12345"
You’ll be able to then use the variable in the identical PowerShell session, or in any youngster processes launched from that session.
Deleting an Atmosphere Variable
Deleting an surroundings variable in PowerShell may be carried out utilizing the Take away-Merchandise cmdlet with the Env: supplier. To delete an surroundings variable, that you must specify the title of the variable utilizing the syntax:
Take away-Merchandise -Path "Env:<variable_name>"
For instance, to delete the “TEMP” surroundings variable, you’ll use:
Take away-Merchandise -Path "Env:TEMP"
Notice that deleting an surroundings variable completely removes it from the system, and any functions that depend on that variable will not have entry to it.
The [System.Environment] .NET Class
Getting Atmosphere Variables
Along with utilizing PowerShell’s built-in $Env: drive and cmdlets like Get-ChildItem Env:, you may also use the .NET Framework’s Atmosphere class to work with surroundings variables in PowerShell.
The Atmosphere class offers numerous static strategies to work together with surroundings variables, similar to GetEnvironmentVariable(), SetEnvironmentVariable(), and RemoveEnvironmentVariable(). These strategies can be utilized to retrieve, set, or delete surroundings variables within the present course of.
To get the worth of an surroundings variable utilizing the Atmosphere class, you’ll be able to name the static technique GetEnvironmentVariable() and go the title of the variable as a parameter. Right here’s an instance:
$varValue = [Environment]::GetEnvironmentVariable("MyVar")
Utilizing [System.Environment] to get Single Atmosphere Variables
In PowerShell, you should use the [System.Environment]
class to retrieve a single surroundings variable. You are able to do this by calling the GetEnvironmentVariable technique and passing the title of the surroundings variable you need to retrieve as a parameter. Right here’s an instance:
$varValue = [System.Environment]::GetEnvironmentVariable("MY_VARIABLE")
This may retrieve the worth of the surroundings variable named “MY_VARIABLE” and retailer it within the $varValue variable. If the required surroundings variable doesn’t exist, this technique will return $null.
GetEnvironmentVariables()
The GetEnvironmentVariables() technique can be utilized to retrieve all surroundings variables as a dictionary object. Nevertheless, it can be used to retrieve a single surroundings variable by specifying its title as a parameter.
To retrieve a single surroundings variable utilizing GetEnvironmentVariables(), you should use the next code:
$varName = "MY_VAR" $varValue = [System.Environment]::GetEnvironmentVariables()["$varName"] Write-Host "The worth of $varName is: $varValue"
GetEnvironmentVariable()
In PowerShell, you should use the GetEnvironmentVariable() technique to retrieve the worth of a single surroundings variable. This technique takes the title of the surroundings variable as an argument and returns its worth. If the surroundings variable doesn’t exist, it returns $null.
Right here’s an instance of easy methods to use GetEnvironmentVariable() to get the worth of the TEMP surroundings variable:
$tempPath = [System.Environment]::GetEnvironmentVariable("TEMP") Write-Host "The worth of the TEMP surroundings variable is: $tempPath"
Making an Atmosphere Variable
To set an surroundings variable utilizing the [System.Environment] class in PowerShell, you should use the SetEnvironmentVariable technique. This technique takes two parameters: the title of the variable, and its worth.
Right here’s an instance:
[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", "my worth")
This may set the surroundings variable MY_VARIABLE to the worth “my worth”. If the surroundings variable already exists, its worth shall be overwritten. If it doesn’t exist, a brand new surroundings variable shall be created.
Deleting an Atmosphere Variable
In PowerShell, you’ll be able to delete an surroundings variable utilizing the [System.Environment] class by calling the SetEnvironmentVariable()
technique with a null worth for the worth parameter. Right here is an instance:
[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", $null, "Consumer")
On this instance, we’re deleting the MY_VARIABLE surroundings variable for the present person. The Consumer argument specifies the scope of the variable to be deleted.
Different Atmosphere Variables
PSExecutionPolicyPreference
The PSExecutionPolicyPreference is an surroundings variable in PowerShell that determines the execution coverage for scripts. This variable can be utilized to set the default execution coverage for the present session or for a particular script.
The obtainable values for the PSExecutionPolicyPreference variable are: “Undefined”, “Restricted”, “AllSigned”, “RemoteSigned”, “Unrestricted”, “Bypass”, “ByPass”, “Undefined”, and “Default”.
By default, the worth of the variable is “Undefined”, which implies that the execution coverage is set by the coverage set within the native group coverage. The PSExecutionPolicyPreference variable may be set utilizing the Set-Variable cmdlet or by instantly assigning a worth to the variable.
PSModulePath
PSModulePath is an surroundings variable utilized by PowerShell to retailer the areas the place it searches for modules when they’re loaded. Modules in PowerShell are collections of capabilities, variables, and different assets that may be loaded right into a PowerShell session to increase its performance.
By default, PSModulePath contains a number of directories which are looked for modules, such because the person’s “DocumentsWindowsPowerShellModules” folder and the system’s “Program FilesWindowsPowerShellModules” folder.
By now, you must be capable of perceive what an surroundings variable on PowerShell is and what it may be used for. When you’ve got additional queries, you’ll be able to go to the Microsoft PowerShell webpage for extra particulars.