Creating and Modifying Environment Variables

This topic contains 6 replies, has 2 voices, and was last updated by Profile photo of Byron Grogan Byron Grogan 1 year, 6 months ago.

  • Author
    Posts
  • #27382
    Profile photo of Byron Grogan
    Byron Grogan
    Participant

    Hey folks. I am referencing this article https://technet.microsoft.com/en-us/library/ff730964.aspx

    I want to create an environment variable for %USERPROFILE%\AppData\Local\Apps directory.

    What value / data-type must you specify for the “Test value.” parameter when using the SetEnvironmentVariable method.

    Thanks!

  • #27383
    Profile photo of Don Jones
    Don Jones
    Keymaster

    You're referring to:

    [Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")

    ?

    They're all strings.

  • #27385
    Profile photo of Byron Grogan
    Byron Grogan
    Participant

    Yes that method. Oh so it's just a simple string %USERPROFILE%\AppData\Local\Apps\2.0

  • #27386
    Profile photo of Byron Grogan
    Byron Grogan
    Participant

    Don do you know if it is possible to delete files in an environment variable? by piping Remove-Item or similar?

  • #27387
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Anything involving a PSDrive, including ENV:, will only affect the current process. But – and I'll explain my process here, in case that helps you – I Googled ".NET Environment Class." That got me to https://msdn.microsoft.com/en-us/library/system.environment(v=vs.110).aspx, which is the class you were using to set a variable.

    I clicked on Methods, which got me to https://msdn.microsoft.com/en-us/library/system.environment_methods(v=vs.110).aspx.

    I didn't see a "RemoveEnvironmentVariable" method, which made me sad. So I looked at the docs for SetEnvironmentVariable. Specifically, https://msdn.microsoft.com/en-us/library/96xafkes(v=vs.110).aspx.

    That told me that the method could also DELETE a variable. Winner! You just pass $null as the value, and if the variable exists, it gets deleted.

    Hope that helps.

  • #27396
    Profile photo of Byron Grogan
    Byron Grogan
    Participant

    Thanks! To verify it's deleted you can also use the method [Environment]::GetEnvironmentVariable("Test Value.")

  • #27497
    Profile photo of Byron Grogan
    Byron Grogan
    Participant

    I ran into an 'issue' / limitation while using this method. I needed to create an environment variable for the local app-data directory %USERPROFILE%\AppData\Local\Apps\2.0\. I tried creating a variable which used the $env:USERPROFILE for the target parameter, to access user profiles on remote machines. as a work around I used the following code to access the local app-data!

    new-item -path $env:UserProfile\AppData\Local\Apps\2.0\ -itemtype directory -force

You must be logged in to reply to this topic.