Setting environment variables in powershell - powershell

In cmd, you could access cmd environment variables outside of cmd, but is there a way to accomplish that is powershell?
BACKGROUND:
In command-prompt (cmd.exe), there are environment variables like %COMSPEC% and %PROGRAMFILES% that you could use outside of cmd an din file explorer and other places (i. e. shortcuts) just by typing in %VariableName% somewhere (this is how I see a lot of people accessing their appdata folders) but I have yet to find a way to do it in powershell. In cmd, you could even define a variable with setx nd be able to use it outside of cmd. Ex:
setx testbat "%HOMEDRIVE%%HOMEPATH%\Desktop\Programs\test.bat"
Then you could use it like this in shortcuts:
%testbat%
Shortcut Wizard with cmd variable
However, I have not been able to replicate this with Powershell variables.
What I've tried:
I saw this and wondered if making an environment variable in powershell with this in mind could be possible:
$env:test = "C:\Users\Neko"
Then I restarted and tried using this both in cmd and in the search prompt (search prompt)
C:\Users\Neko>cd %test%
The system cannot find the path specified.
C:\Users\Neko>echo %test%
%test%
Sure enough, it didn't even show up in powershell when I did gci env: after the restart
Since this didn't work I deleted the variable and had an idea:
PS C:\Users\Neko> gci env:
Name Value
---- -----
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\Neko\AppData\Roaming
CommonProgramFiles C:\Program Files\Common Files
CommonProgramFiles(x86) C:\Program Files (x86)\Common Files
CommonProgramW6432 C:\Program Files\Common Files
COMPUTERNAME XXXXXXXXX
ComSpec C:\Windows\system32\cmd.exe
DriverData C:\Windows\System32\Drivers\DriverData
HOMEDRIVE C:
HOMEPATH \Users\Neko
LOCALAPPDATA C:\Users\Neko\AppData\Local
LOGONSERVER \\XXXXXXXXX
NUMBER_OF_PROCESSORS 8
OneDrive C:\Users\Neko\OneDrive
OneDriveConsumer C:\Users\Neko\OneDrive
OS Windows_NT
POWERSHELL_DISTRIBUTION_CHA... MSI:Windows 10 Pro Education
PROCESSOR_ARCHITECTURE AMD64
PROCESSOR_IDENTIFIER Intel64 Family 6 Model 126 Stepping 5, GenuineIntel
PROCESSOR_LEVEL 6
PROCESSOR_REVISION 7e05
ProgramData C:\ProgramData
ProgramFiles C:\Program Files
ProgramFiles(x86) C:\Program Files (x86)
ProgramW6432 C:\Program Files
PSModulePath C:\Users\Neko\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\M...
PUBLIC C:\Users\Public
SystemDrive C:
SystemRoot C:\Windows
TEMP C:\Users\Neko\AppData\Local\Temp
test C:\Users\Neko
TMP C:\Users\Neko\AppData\Local\Temp
USERDOMAIN XXXXXXXXX
USERDOMAIN_ROAMINGPROFILE XXXXXXXXX
USERNAME Neko
USERPROFILE C:\Users\Neko
windir C:\Windows
WSLENV WT_SESSION::WT_PROFILE_ID
WT_PROFILE_ID XXXXXXXXX
WT_SESSION XXXXXXXXX
PS C:\Users\Neko> del "env:test"
PS C:\Users\Neko> gci env:
Name Value
---- -----
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\Neko\AppData\Roaming
CommonProgramFiles C:\Program Files\Common Files
CommonProgramFiles(x86) C:\Program Files (x86)\Common Files
CommonProgramW6432 C:\Program Files\Common Files
COMPUTERNAME XXXXXXXXX
ComSpec C:\Windows\system32\cmd.exe
DriverData C:\Windows\System32\Drivers\DriverData
HOMEDRIVE C:
HOMEPATH \Users\Neko
LOCALAPPDATA C:\Users\Neko\AppData\Local
LOGONSERVER \\XXXXXXXXX
NUMBER_OF_PROCESSORS 8
OneDrive C:\Users\Neko\OneDrive
OneDriveConsumer C:\Users\Neko\OneDrive
OS Windows_NT
Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPo...
PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL
POWERSHELL_DISTRIBUTION_CHA... MSI:Windows 10 Pro Education
PROCESSOR_ARCHITECTURE AMD64
PROCESSOR_IDENTIFIER Intel64 Family 6 Model 126 Stepping 5, GenuineIntel
PROCESSOR_LEVEL 6
PROCESSOR_REVISION 7e05
ProgramData C:\ProgramData
ProgramFiles C:\Program Files
ProgramFiles(x86) C:\Program Files (x86)
ProgramW6432 C:\Program Files
PSModulePath C:\Users\Neko\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\M...
PUBLIC C:\Users\Public
SystemDrive C:
SystemRoot C:\Windows
TEMP C:\Users\Neko\AppData\Local\Temp
TMP C:\Users\Neko\AppData\Local\Temp
USERDOMAIN XXXXXXXXX
USERDOMAIN_ROAMINGPROFILE XXXXXXXXX
USERNAME Neko
USERPROFILE C:\Users\Neko
windir C:\Windows
WSLENV WT_SESSION::WT_PROFILE_ID
WT_PROFILE_ID XXXXXXXXX
WT_SESSION XXXXXXXXX
I then checked to see if the cmd set command beared the same results as gci env: and it did, so I then tried to use setx to see if it appeared in powershell as well:
setx test "Test"
And after a restart, it did
PS C:\Users\Neko> $env:test
Test
I realized that the variables all were stored in the registry and that I could edit the registry of course with:
Set-Itemproperty -path 'HKCU:\Environment' -Name 'Test' -value 'Test'
But it doesn't feel the same as something like setx
CONCLUSION:
I want to learn if there is a true-powershell-esque command that can define environemnt variables that I can use outside of powershell like setx can in cmd. I am not looking for full scripts just commands or something like $env:variable = "value".
UPDATE:
Yes, you can create a function to do this as well, technically a one-liner possibly, not what I'm looking for. I want to be able to create environment variables in powershell with built in cmdlets. Something "true-powershell"

Powershell itself provides these methods to interact with environment variables:
The Environment provider drive
The Item cmdlets
The .NET System.Environment class
On Windows, the System Control Panel
So, to set a persistent environment variable (PSModulePath) to a value $newpath at machine level you might use
[Environment]::SetEnvironmentVariable("PSModulePath", $newpath, 'Machine')
To get an environment variable you might use
$path = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine')
or the variable syntax
$Env:PSModulePath
Here's the documentation.

Related

PowerShell: What kind of keyword ist env: ? Meaning of such a keyword?

For to display all environmental variables in PowerShell one uses:
Get-ChildItem env:
What is 'env:'?
It clear to me that it is some abbreviation for "environment". But what kind of abbreviation? What's the meaning of the colon at the end?
Your query is defined in the PowerShell help files:
About Automatic Variables:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1
$env is a virtual drive for the above. Easily seen via the below and its purpose to allow access to the above:
# These are treated as normal filesystem drives, and you can create custom ones.
Get-PSDrive
<#
Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Alias Alias
C 5.04 34.83 FileSystem C:\ Scripts
Cert Certificate \
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan
#>
Get-ChildItem -Path 'env:\'
<#
Using these in code requires the $ in front of each named variable to get the content/values. In your scripts, never name your custom variables the same as any of the below.
Name Value
---- -----
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\WDAGUtilityAccount\AppData\Roaming
CLIENTNAME 8fda9520-99a6-4
CommonProgramFiles C:\Program Files\Common Files
CommonProgramFiles(x86) C:\Program Files (x86)\Common Files
CommonProgramW6432 C:\Program Files\Common Files
COMPUTERNAME 0C092C31-6890-4
...
#>
If you do want to use the names above, as custom variables for other values, then you should provide a unique prefix. Say, your initials, so as to not have conflicts/errors.

How to revert Powershell PATH variable to the default value

I have mistakenly replaced the PATH variable instead of appending to it. How do I revert back to the default value of the PATH?
If we want to reset your PATH environment variable without restarting your PowerShell session, give this a try:
$Env:Path = [System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine).Path + ';' + [System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User).Path
To get the default current path run the following
($env:PATH).split(";")
if i understand your question that you have by mistake replace the path variable so if you run the command on the last answer it will revert back the fault current path it will not add the default which has been missed
The default path part of it is the default for any windows are:
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0
C:\Users$user\AppData\Local\Microsoft\WindowsApps
and the other depending on your apps like that
C:\WINDOWS\System32\OpenSSH
C:\Program Files (x86)\Microsoft Team Foundation Server 2010 Power Tools\Best Practices Analyzer
C:\Program Files\PuTTY
C:\Program Files\Docker\Docker\resources\bin
C:\ProgramData\DockerDesktop\version-bin
C:\Program Files\PowerShell\7-preview\preview
C:\Users$user\AppData\Local\Microsoft\WindowsApps
C:\Users$user\AppData\Local\Programs\Fiddler
C:\Users$user\AppData\Local\Microsoft\WindowsApps
C:\Program Files (x86)\OpenVPN\bin
C:\Users$user\AppData\Local\GitHubDesktop\bin
C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin
C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static
you can search what is the default PowerShell path for each program you have
To add a new path
$INCLUDE = "C:\tmp"
$OLDPATH = [System.Environment]::GetEnvironmentVariable('PATH','machine')
$NEWPATH = "$OLDPATH;$INCLUDE"
[Environment]::SetEnvironmentVariable("PATH", "$NEWPATH", "Machine")

Powershell 5.0 doesn't see PATH environment variables under User account

I added an environment variable to my System Path -> C:\Program Files\TEE-CLC. After that, I expect, that I can run my foo.exe which is under C:\Program Files\TEE-CLC from PowerShell without providing a full path to it. The issue is when I start a new, fresh Powershell session under my user, it doesn't see the newly added path, but when I start it under administrator everything works fine.
I checked $env:Path in both modes (User and Admin) and found that my new path doesn't exist when I am under User, but I can see it when Powershell is as Administrator
How I can make my newly added variable visible running under User rather than Administrator?
UPDATE
I ran 2 commands under User and the result is different. Why doesn't $env:Path display the same output as [System.Environment]::GetEnvironmentVariable('PATH', 'MACHINE') and why current PSSession doesn't see the path from the latter command?`
STEPS TO REPRODUCE
Add environemt path variable [Environment]::SetEnvironmentVariable('PATH', ($env:Path + ';C:\Program Files\Foo'), 'MACHINE')
Close the session
Open a NEW ps session as user -> check $env:PATH -> C:\Program Files\Foo is not there
Open a NEW ps session as admin -> check $env:PATH -> C:\Program Files\Foo is there
Unless I've missed something, I cannot reproduce your issue, here's example, I've just perfromed on a Test machine for you.
First I opened an elevated powershell.exe window, i.e. 'as administrator`:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\WINDOWS\system32> $Env:Path
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps
PS C:\WINDOWS\system32> [Environment]::SetEnvironmentVariable('Path', ($Env:Path + ';C:\Program Files\Foo'), 'MACHINE')
PS C:\WINDOWS\system32> $Env:Path
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps
PS C:\WINDOWS\system32> [Environment]::GetEnvironmentVariable('Path', 'MACHINE')
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Foo
PS C:\WINDOWS\system32>
Then I opened a new non elevated powershell.exe window:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\Tester> $Env:Path
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Foo;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;
PS C:\Users\Tester> [Environment]::GetEnvironmentVariable('Path', 'MACHINE')
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Foo
PS C:\Users\Tester>
As you can see C:\Program Files\Foo was shown in both example outputs.
Then I opened another new elevated powershell.exe window:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\WINDOWS\system32> $Env:Path
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Foo;
PS C:\WINDOWS\system32> [Environment]::GetEnvironmentVariable('Path', 'MACHINE')
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Tester\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Foo
PS C:\WINDOWS\system32>
As you can see C:\Program Files\Foo was shown in both example outputs.
This issue suddenly appeared for me out of the blue and I was able to solve it for myself at least.
Warning: backup your PATH somewhere before running anything. There's a 1024ch limit so be careful.
Background
As a user (non-admin), your $Path is the equivalent of [System.Environment]::GetEnvironmentVariable('PATH', 'USER') while as admin your $Path is the equivalent of [System.Environment]::GetEnvironmentVariable('PATH', 'MACHINE'). There are probably many instances where you want these separated. In my case everything under my "MACHINE" $Path are things I'd want as a regular user, so I'll just show how to combine these paths so that no matter how you run powershell you'll have the same path.
Process
Open cmd.exe as an administrator (there's probably a way to do this in powershell but this method seems so much easier and will apply to powershell fine)
Add the combined paths to the user path:
setx path "%path%"
(within cmd %path% is a combination of both the user and machine paths)
(Extra) Add the combined paths to the system path:
setx /M path "%path%"
Restart powershell. The executables you expect should now be available as a user.

Windows Powershell Environment Variables

I tried but did not find an answer :
How do I get the current user home in Windows PowerShell?
System variables (those that you would address in Batch as %varname%) are accessible in PowerShell as $env:varname. You can list the system variables that are visible to your PowerShell session with Get-ChildItem -Path Env:.
In Windows, it looks like $env:userprofile or $env:homepath without the drive.
dir env: | where value -match admin
Name Value
---- -----
APPDATA C:\Users\admin\AppData\Roaming
HOMEPATH \Users\admin
LOCALAPPDATA C:\Users\admin\AppData\Local
OneDrive C:\Users\admin\OneDrive
Path C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Wind...
PSModulePath C:\Users\admin\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerSh...
TEMP C:\Users\admin\AppData\Local\Temp
TMP C:\Users\admin\AppData\Local\Temp
USERNAME admin
USERPROFILE C:\Users\admin
Try this:
[Environment]::ExpandEnvironmentVariables("%UserProfile%")

How to properly set path in Powershell and 7zip?

I have a Powershell script to create a self-extracting archive via 7zip. But it's receiving this error:
cannot find specified SFX module
The Powershell code is:
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe
sz a -t7z -sfx -ppassword $fullpath $filetostore
Both variables are valid. I've tried -sfx and -sfx7z.sfx, same error. The 7z.sfx file is indeed in the correct folder with 7zip. I can also verify the alias is working, as the 7zip copyright appears when running the code (so 7zip commandline is being initiated). This command works outside Powershell.
I'm also tried Set-Location into the 7zip folder, but same error. What am I missing?
It seems you should add the 7-zip folder to your PATH environment variable to make things easier :
#find the 7-zip folder path
$7zPath = (Get-ChildItem "C:\Program Files","C:\Program Files (x86)" -Include "7-zip" -Recurse -ErrorAction SilentlyContinue).FullName
#add it to PATH environment variable
$env:Path += ";$7zPath;"
Then you can run 7z -sfx with no errors about the SFX module.
While Sodawillow has an answer that will work for the active session, a more permanent answer would be to add 7zip to the path for the Environment you are working in:
[Environment]::SetEnvironmentVariable("Path",$env:Path+";C:\Program Files\7-zip", [EnvironmentVariableTarget]::User)
The above one-liner should add 7zip to the active user account's path. Change 'User' to 'Machine' for the whole computer, or 'Process' for the currently running window. If you set 'User' or 'Machine', you will need to open a new powershell instance to see the change reflected.