Set-EnvVariable

Hey guys, this is just a quick post to cover a new function I posted up on technet

http://gallery.technet.microsoft.com/Set-Environment-Variable-0e7492a3

There are a couple neat features in this function. Not in the functionality per se, I’m sure setting an environment variable isn’t that new to anyone. This function is cool because of some of the surrounding elements. First off, there is the Parameter validation:


# Enter the name of the Environment variable you want modified
[Parameter(Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName='Default')]
[Parameter(ParameterSetName='Concat')]
[validatescript({$_ -in ((Get-ChildItem -path env:\).name)})]
[string]$Name

So because it’s a set-* type function I only wanted to modify existing variables. That’s where the [ValidateScript()] comes in. It’s not as good as validate set but it’s more dynamic. It’ll check everything that’s in the Environment drive when it runs. I don’t want to have a static set because I want it to adapt to anyones environment. I lose tab completion but I still get the validation I wanted.

The other thing you might notice is that there are two parameter sets. I did that because I wanted to add two different functionality streams.

The function exists to modify existing environment variables, but it needs to act in one of two ways. Either it should overwrite the existing value or it needs to concatenate the new value to the existing value, like when adding a directory to the Path. So Set-EnvVariable has two parameter sets, Default, which is for the overwrite behavior and Concat which is for the appending behavior.


# Enter separator character, defaults to ';'
[Parameter(ParameterSetName='Concat')]
[ValidateLength(0,1)]
[string]$Separator = ';',

# Set to append to current value
[Parameter(ParameterSetName='Concat')]
[switch]$Concatenate

You’ll also notice, if you use it that the function always prompts for confirmation. It has a big impact and it defaults to wiping out the value of existing environment variables, not something to do lightly.


[cmdletbinding(SupportsShouldProcess=$true,
ConfirmImpact='high',
DefaultParameterSetName='Default')]

Anyhow, that’s about all there is that’s novel in this function. It’s cool and I like it a lot, please take the time to download it and give it a rating.

Advertisements
This entry was posted in PowerShell. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s