Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to set a user environment variable in a PowerShell script?

Tags:

powershell

I'm trying to schedule a command in a PowerShell script to run using Windows scheduler. This command relies on a user specific environment variable, and since scheduled tasks do not have access to these I have decided to try and just set the variable inside the PowerShell script itself.

The normal environment variable configuration looks like this:

Enter image description here

And in order to replicate this in the script, I tried using:

$env:DCRCLIFILE = "C:\Users\pzsr7z\Desktop\DCRCLIFILE.txt"

But for some reason the program will not work properly when I set things up this way, even though it works perfectly fine when I run the program using the "normal" user environment variable.

Program execution using the PowerShell initiated environment variable

Image description

Program execution using the "normal" environment variable:

Enter image description here

Is there anything that I should be doing differently when setting the environment variable in the PowerShell script? I'm not sure why this isn't working. I've verified that the environment variable actually gets created, so it's not like the PowerShell command is failing.

like image 763
lacrosse1991 Avatar asked Nov 18 '16 14:11

lacrosse1991


1 Answers

$env:DCRCLIFILE = "C:\Users\pzsr7z\Desktop\DCRCLIFILE.txt"

This only creates a process-level environment variable, which is only visible to, and lasts only as long as, your current PowerShell session.

You need to set a more permanent environment variables (user-level or machine-level) by using the .NET Framework and the SetEnvironmentVariable method:

[Environment]::SetEnvironmentVariable("DCRCLIFILE", "C:\Users\pzsr7z\Desktop\DCRCLIFILE.txt", "User")
like image 106
henrycarteruk Avatar answered Oct 11 '22 15:10

henrycarteruk