Chapter 16. Environmental Awareness

16.0 Introduction

While many of your scripts will be designed to work in isolation, you’ll 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 and built-in variables to features that it offers from the .NET Framework.

16.1 View and Modify Environment Variables


You want to interact with your system’s environment variables.


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

You can modify environment variables this way, too. For example, to temporarily add the current directory to the path:

PS > Invoke-DemonstrationScript Invoke-DemonstrationScript.ps1: The term 'Invoke-DemonstrationScript.ps1' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Suggestion [3,General]: The command Invoke-DemonstrationScript.ps1 was not found, but does exist in the current location. PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\Invoke-DemonstrationScript.ps1". ...

Get PowerShell Cookbook, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.