Chapter 16. Environmental Awareness

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 and built-in variables to features that it offers from the .NET Framework.

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 the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:27 + Invoke-DemonstrationScript <<<< + CategoryInfo : ObjectNotFound: (Invoke-DemonstrationScript :String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command Invoke-DemonstrationScript was not found, but does exist in the current location. Windows ...

Get Windows PowerShell Cookbook, 2nd Edition 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.