Solved

Powershell required to backup Environmental Variable

Posted on 2016-11-02
13
25 Views
Last Modified: 2016-11-10
Hi all,

I'm looking for a way to backup a specific variable with the value on machines and then place a temporary one in it's place for a number of weeks for a trial licence. Once this trial is complete I then need to restore that variable to how it was before.

Can anyone help?

thanks
0
Comment
Question by:ranski
  • 6
  • 4
  • 3
13 Comments
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
The first part:
rename-item env:MyVar MyVar_Save
$env:MyVar = 'Something else'
dir env:MyVar*   # just for test

Open in new window

Reverting:
remove-item env:MyVar
rename-item env:MyVar_Save MyVar

Open in new window

The "time trigger" will need to get implemented somewhere else, e.g. as a scheduled task.
0
 

Author Comment

by:ranski
Comment Utility
thanks.  How would I add settings to the EV?
0
 

Author Comment

by:ranski
Comment Utility
also will the above work if the EV isn't present on a system?
0
 
LVL 82

Accepted Solution

by:
oBdA earned 500 total points
Comment Utility
Save this as Backup-EnvironmentVariable.ps1 or Whatever.ps1.
You need to pass it at least the variable name to backup.
If you pass -NewValue as well (optional), it will set the variable it just backed up to the new value passed.
It will by default not overwrite an existing backup on subsequent calls; use -Force to overwrite the existing backup with the current value.
Pass the variable name and the switch -Restore to restore the variable to its original value.
If the variable isn't present (or another error occurred), it will leave with errorlevel 1.
You can use -Verbose to see what it's doing, otherwise it will be quiet.
I'm assuming a system variable, so administrative permissions are required.
[CmdletBinding()]
Param(
	[string]$Name,
	[string]$NewValue,
	[switch]$Force,
	[switch]$Restore,
	[string]$Extension = '_bak'
)
$BackupName = "$($Name)$($Extension)"
If ($Restore) {
	If (-not ($RestoreValue = [Environment]::GetEnvironmentVariable($BackupName, 'Machine'))) {
		Write-Error -Message "Found no backup for variable to restore: '$($BackupName)'!"
		Exit 1
	}
	Try {
		[Environment]::SetEnvironmentVariable($Name, $RestoreValue, 'Machine')
		Write-Verbose -Message "Variable '$($Name)' restored to value '$($RestoreValue)' from variable '$($BackupName)'."
	} Catch {
		Write-Error -Message $_.Exception.Message
		Exit 1
	}
} Else {
	If (!$Force -and [Environment]::GetEnvironmentVariable($BackupName, 'Machine')) {
		Write-Warning -Message "Variable is already backed up: '$($BackupName)'"
		Exit 0
	}
	If (-not ($BackupValue = [Environment]::GetEnvironmentVariable($Name, 'Machine'))) {
		Write-Error -Message "Variable to backup not found: '$($Name)'"
		Exit 1
	}
	Try {
		[Environment]::SetEnvironmentVariable($BackupName, $BackupValue, 'Machine')
		Write-Verbose -Message "Variable '$($Name)' with value '$($BackupValue)' backed up to '$($BackupName)'."
		If (![string]::IsNullOrEmpty($NewValue)) {
			[Environment]::SetEnvironmentVariable($Name, $NewValue, 'Machine')
			Write-Verbose -Message "Variable '$($Name)' set to new value '$($NewValue)'."
		}
	} Catch {
		Write-Error -Message $_.Exception.Message
		Exit 1
	}
}
Exit 0

Open in new window


Qlemo,
that only sets the value for the current PS session, it doesn't set the environment variable permanently.
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
If the env var does not exist, the rename will fail, but the new var set. And when reverting, the "new" var will get deleted, and the old not found to rename back, so nothing will stay left.

What do you mean exactly with "add settings to the EV"? An env var contains a string, nothing else.
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
oBdA, that is absolutely correct. How embarrassing ...
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:ranski
Comment Utility
Thanks both.

The EV I need to backup is called LICENSE_FILE and i plan to run this as a logon script. Does the above achieve this?

Once it's backed up a new item with the same name needs to be created with a different list of licence servers in the value.
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
A login script runs each time the user logs in. How should that work here?
0
 

Author Comment

by:ranski
Comment Utility
We could use a drop file. If present do nothing?
0
 
LVL 82

Expert Comment

by:oBdA
Comment Utility
Check in the GUI whether this is a User variable or a System variable.
Or open a PS and check which one of these does not throw an error:
[Environment]::GetEnvironmentVariable('LICENSE_FILE', 'Machine')
[Environment]::GetEnvironmentVariable('LICENSE_FILE', 'User')

Open in new window

If it's a System variable, using a logon script won't work, as the change requires administrative permissions. You'd then need a Startup script to do that.

Qlemo,
the script won't backup again when the backup variable exists already.
0
 

Author Comment

by:ranski
Comment Utility
Hi oBdA

The EV is System based and is already being set via Group Policy. There may however be locations that have set this manually which is why i need to go that extra but further than just backup the GPO and make a change then revert back.

It's really important that we capture all machines and force then to use the new licence servers but then allow us to revert back a month later.

Any ideas?
0
 

Author Comment

by:ranski
Comment Utility
0
 
LVL 82

Assisted Solution

by:oBdA
oBdA earned 500 total points
Comment Utility
Then deploy the script above as computer startup script to the machines in question.
Arguments for the script are
-Name LICENSE_FILE -NewValue "New Value"

Open in new window

Once the trial is over, deploy the script again or change to these arguments (you can just keep it running):
-Name LICENSE_FILE -Restore

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now