Chapter 14. Environmental Awareness
14.0. Introduction
While many of your scripts will be designed to work in isolation, you will often find it helpful to give your script information about its execution environment: its name, current working directory, environment variables, common system paths, and more.
PowerShell offers several ways to get at this information—from its cmdlets, to builtin variables, to features that it offers from the .NET Framework.
14.1. View and Modify Environment Variables
Problem
You want to interact with your system’s environment variables.
Solution
To interact with environment variables, access them in almost the same way that you access regular PowerShell variables. The only difference is that you place env:
between the ($) dollar sign and the variable name:
PS >$env:Username Lee
You can modify environment variables this way, too. For example, to temporarily add the current directory to the path:
PS >Invoke-DemonstrationScript The term 'Invoke-DemonstrationScript' is not recognized as a cmdlet, funct ion, operable program, or script file. Verify the term and try again. At line:1 char:26 + Invoke-DemonstrationScript <<<< PS >$env:PATH = $env:PATH + "." PS >Invoke-DemonstrationScript.ps1 The script ran!
Discussion
In batch files, environment variables are the primary way to store temporary information, or to transfer information between batch files. PowerShell variables and script parameters are more effective ways to solve those problems, but environment variables ...
Get Windows PowerShell Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.