PowerShell and retrieving environment variables from a content file

I was recently creating a Windows PowerShell script which retrieved content from a JSON-formatted file containing configuration information to be used as variables.

A number of  configuration values contained an evironment variable for the user profile of the current user. When retrieving the value the string would be returned as a string and not the dynamic value expected.

For Example, below is the content of the JSON-formatted file which contains information referencing the environment variables.

[
    {
    "SecurePasswords": "%USERPROFILE%\\SecurePasswords",
    "Logs":"%TEMP%"
     }
]

So if we retrieve the content from the configuration file and attempt to retrieve the item at the specified location an error will be received as the dynamic environment variable does not expand and therefore the path specified does not exist.

GetItemEnvironmentVariable1

In order to expand the dynamic environment variable the trick is to use the Environment.ExpandEnvironmentVariables Method ‘[System.Environment]::ExpandEnvironmentVariables()’ which replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.

Now, thats invoke this method using the previous configuration file.

GetItemEnvironmentVariable2

 


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s