Solved

Powershell required to backup Environmental Variable

Posted on 2016-11-02
13
44 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 69

Expert Comment

by:Qlemo
ID: 41870748
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
ID: 41870765
thanks.  How would I add settings to the EV?
0
 

Author Comment

by:ranski
ID: 41870767
also will the above work if the EV isn't present on a system?
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 84

Accepted Solution

by:
oBdA earned 500 total points
ID: 41870810
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 69

Expert Comment

by:Qlemo
ID: 41870820
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 69

Expert Comment

by:Qlemo
ID: 41870830
oBdA, that is absolutely correct. How embarrassing ...
0
 

Author Comment

by:ranski
ID: 41873015
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 69

Expert Comment

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

Author Comment

by:ranski
ID: 41873027
We could use a drop file. If present do nothing?
0
 
LVL 84

Expert Comment

by:oBdA
ID: 41873029
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
ID: 41873038
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
ID: 41873040
0
 
LVL 84

Assisted Solution

by:oBdA
oBdA earned 500 total points
ID: 41873171
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

Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Utilizing an array to gracefully append to a list of EmailAddresses
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

713 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