O'Reilly logo

Windows PowerShell Cookbook, 2nd Edition by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required