简体   繁体   中英

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

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:

在此处输入图片说明

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

图片说明

Program execution using the "normal" environment variable:

在此处输入图片说明

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.

$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")

I ended up solving this issue by creating a separate batch file and then setting the DCRCLIFILE variable manually in there, after which I ran the dcrclifile.exe command from within the same batch file.

I'm not sure why things did not work properly when I was attempting to set the variable manually in PowerShell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM