windowspowershellenvironment-variables

How to change the LOCALAPPDATA environment variable in PowerShell?


I'm trying to change the location of the %LOCALAPPDATA% environment variable in PowerShell, but the change is not taking effect.

Details of the Problem

I want to set the LOCALAPPDATA variable to a new directory (G:\AppData\Local), but after following several methods, it still shows the default location (C:\Users\username\AppData\Local) in PowerShell and other applications.

What I Tried

  1. Set the environment variable using [System.Environment]::SetEnvironmentVariable():

    [System.Environment]::SetEnvironmentVariable("LOCALAPPDATA", "G:\AppData\Local", "User")
    
    • The variable should reflect the new path in the current PowerShell session.
  2. Verified the change using echo $env:LOCALAPPDATA:

    • The command shows the new location, but it's not reflected in other applications.
  3. Restarted Powershell:

    • Closed and reopened PowerShell, but the change is still not visible.

Solution


  • Changing the path of known folder %LOCALAPPDATA% for the current user:
    (
      Add-Type -NameSpace NS$PID -Name KnownFolderPath -PassThru -MemberDefinition @'
    [DllImport("shell32.dll")]
    public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
    '@
    )::SHSetKnownFolderPath(
      [ref] [guid] '{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}', # folder ID
      0, # flags
      [IntPtr]::Zero, # target the current user
      'G:\AppData\Local' # new path
    )
    

    Note: