Powershell add to path, temporarily - powershell

I'm trying to write a simple PowerShell script to deploy a Visual Studio ASPNET Core 1 project.
Currently, in a batch file i can say
Path=.\node_modules\.bin;%AppData%\npm;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\git
That will modify the path variable for the duration of the session... for the life of me I can't figure out how to do this simple thing in powershell.
Can someone help me translate this into powershell?
TIA!

Option 1: Modify the $env:Path Variable
Append to the Path variable in the current window:
$env:Path += ";C:\New directory 1;C:\New directory 2"
Prefix the Path variable in the current window:
$env:Path = "C:\New directory 1;C:\New directory 2;" + $env:Path
Replace the Path variable in the current window (use with caution!):
$env:Path = "C:\New directory 1;C:\New directory 2"
Option 2: Use the editenv Utility
I wrote a Windows command-line tool called editenv that lets you interactively edit the content of an environment variable. It works from a Windows console (notably, it does not work from the PowerShell ISE):
editenv Path
This can be useful when you want to edit and rearrange the directories in your Path in a more interactive fashion, and it affects only the current window.

You can just use $env:Path, but if you're anxious that that isn't explicit enough, you can use System.Environment.SetEnvironmentVariable():
[System.Environment]::SetEnvironmentVariable('Path',$Value,[System.EnvironmentVariableTarget]::Process);
And GetEnvironmentVariable() can explicitly retrieve:
[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Process);
[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine);
[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::User);

Related

Can I remove the location from my terminal in VSC? [duplicate]

So I've just downloaded Visual Studio Code to use as my default IDE for learning Python. I'm running on a 64-bit machine so I made the default terminal windows powershell.
The place where I'll be saving most of my files is about 8 folders deep which all show up in the terminal before any commands can be written. Is there any way to hide or shorten the file path in the terminal?
As #Biclops suggested, there is good info here: configure PowerShell to only show the current folder in the prompt
However, I needed more basic info to get this to work. This is a very good resource to get started: Windows PowerShell Profiles. So I first followed the steps suggested there:
[always using vscode's integrated terminal using PowerShell]
test-path $profile (is there a profile set up?)
new-item -path $profile -itemtype file -force (assuming the answer to the above is false)
notepad $profile (opens notepad)
paste in (from the SuperUser answer above)
function prompt {
$p = Split-Path -leaf -path (Get-Location)
"$p> "
}
save (you shouldn't have to chose a location, it is already done for you)
reload vscode - you will probably get an error message about running scripts (or just do next step before reload)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser (at your integrated terminal PS prompt, also from the SuperUser answer)
reload vscode
You should be good to go!
Great Question and Great Answers.
But this information is dated, and Windows is currently updating from Windows 10 to Windows 11. In addition, the base Windows PowerShell has been incorporated into the new Windows Terminal Preview app. which is being used here.
The solution provided above by Mark and Tarruda23 (above) almost works. But Windows throws an error - described below.
The steps:
First, it was necessary to determine whether a profile existed. Using the Windows Explorer, the following path was checked. If a profile already exists, this path shows where an existing profile should be found. On this PC, no profile ( .ps1 ) file existed and this folder was empty. Don't close the Explorer.
C:\Users\prior\OneDrive\Documents\WindowsPowerShell
Since no file exists, a new file needed to be created. This new file must be saved with a specific name - shown below.
Navigate to the empty folder and open PowerShell. The .ps1 profile must be created and saved in this folder. Use the Powershell's build-in text editor to create the new file. Type:
ISE
Then type or paste the following into the empty text file:
function prompt {
$p = Split-Path -leaf -path (Get-Location)
"$p> "
}
Save this file with the following name:
Microsoft.PowerShell_profile.ps1
Use the PowerShell to open Notepad and check that .ps1 file. This demonstrates the Windows system has found the new .ps1. Next close the Notepad.
Notepad $profile
Now the PowerShell is probably displaying an error message in red text. This error message reads in part:
\Microsoft.PowerShell _profile.ps1 cannot be loaded because running scripts is disabled on this system.
Run the PowerShell as the Administrator. Type the following.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Windows will prompt with a question:
Do you want to change the execution policy?
Type y for yes. This will change and remove the Windows default settings that prevents running script files. Once done, this will remove that error message.
All should be good now. PowerShell will now start and run with shorter and abbreviated PS> prompt that shows either the User name, or the name of the folder where the PowerShell is running.

Changing a value in the Path environment variable

My company uses a program that breaks when Java is updated. This is due to the program install (I assume) placing a static path to Java in the Path environment variable. For example, the current Path variable in question is C:\Program Files (x86)\Java\jre1.8.0_171\bin\client, but if Java is updated and the program is re-installed, the Path variable will update to include C:\Program Files (x86)\Java\jre1.8.0_181\bin\client.
I was able to find exactly what I needed (I think) here https://blogs.technet.microsoft.com/heyscriptingguy/2007/11/08/hey-scripting-guy-how-can-i-remove-a-value-from-the-path-environment-variable/, but that code is for Powershell 2.0 and doesn't work on Windows 10.
Is this still possible in Windows 10?
You can use the System.Environment class to modify your environment variables machine-wide:
# get the PATH and split it up
$PATH = [Environment]::GetEnvironmentVariable('PATH', 'Machine') -split ';'
# filter out the JRE paths
$PATH = $PATH -notmatch 'java\\jre'
# get any real JRE paths
$PATH += (Get-Item -Path "${Env:ProgramFiles(x86)}\Java\jre*\bin\client").FullName
$PATH = $PATH -join ';'
[Environment]::SetEnvironmentVariable('PATH', $PATH, 'Machine')
Note: You will need to run your shell elevated to execute these commands.
Java is not a Windows issue, and therefore TechNet will not help you. There is a fix below.
Windows 10 and Windows 8:
Open the Legacy Control Panel
Click the Advanced system settings link.
Click Environment Variables. In the section System Variables, find the PATH environment variable and select it.
Click Edit.
If the PATH environment variable does not exist, click New.
In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.
Click OK.
Close all remaining windows by clicking OK.
Reopen the PowerShell window, and run your Java code.
Source: https://www.java.com/en/download/help/path.xml

Paths from environmental variables not available in Powershell

So I have installed the Team Foundation Server PowerShell Tools, and verified they exist, but the executables (TFPT.exe) do not appear to be available in powershell.
Looking at $env:path (and looking at the path variable through System Properties) I see that the end of the path variable looks like this:
$env:Path = {other variables};%TFSPowerToolDir%;%BPADir%;.;
System Properties Enviromental Variables = {other variables};%TFSPowerToolDir%;%BPADir%
When I look at $env:TFSPowerToolDir I get C:\Program Files (x86)\Microsoft Team Foundation Server 2013 Power Tools\, so that seems correct.
But if I try to run tfpt I get the error "The term 'tfpt.exe' is not recognixed as the name of a cmdlet...
If I first do cd $env:TFSPowerToolDir and the run tfpt it works fine. So the environmental variable is correct. But it doesn't seem to get placed in the path.
Any ideas on how to fish this?
Can't replicate the problem here, actually. The problem seems to be that other environment variables are not expanded in $Env:PATH here, but in a quick test PowerShell did so for me reliably.
You could try to work around the problem by manually expanding environment variables in your profile script. E.g. with something like the following:
$Env:PATH = [regex]::Replace($Env:PATH, '%([^%]+)%', {
param($m)
$n = $m.Groups[1].Value
Get-Content -Raw Env:\$n
})

Open Notepad++ from PowerShell

How can I open up a file in Notepad++ from the Powershell command line?
Inside PowerShell I can simply use the start and get general results
to open a python file with notepad++ here is what I did.
Start notepad++ ex1.py
this will start notepad++ and load the file ex1.py assuming you are in the same directory as the .py file. You can change that by adding the full path name
start notepad++ c:\users\you\desktop\files\ex1.py
Because the default path contains spaces, you have to quote the path to the exe. However because PowerShell is also a scripting language. A string by itself is simply evaluated as a string e.g.:
C:\ PS> 'Hello world'
Hello world
So you have to tell PowerShell you want to invoke the command that is named by the string. For that you use the call operator & e.g.:
C:\ PS> & 'C:\Program Files (x86)\Notepad++\notepad++.exe'
or if notepad++ is in your path:
C:\ PS> notepad++
or if you're in the same dir as the exe:
C:\ PS> .\notepad++
To open Notepad++ with and create a new empty file in the current path
start notepad++ newFile.txt
To open Notepad++ with an existing file
start notepad++ apples.txt
To specify the path and open multiple files
start notepad++ fruits/apples.txt, fruits/oranges.txt, package.json
To extrapolate on the previous answers and tie them up in a tidy bow:
If you want to open a file with spaces in the path or name:
. 'C:\Program Files (x86)\Notepad++\notepad++.exe' 'C:\Temp\File With Spaces.txt'
or
& 'C:\Program Files (x86)\Notepad++\notepad++.exe' 'C:\Temp\File With Spaces.txt'
It can also be set it as an alias:
Set-Alias -Value 'C:\Program Files (x86)\Notepad++\notepad++.exe' -Name 'NotePad'
$FileWithSpaces = 'C:\T e m p\File With Spaces.txt'
NotePad $FileWithSpaces
The top line here can be copied into (one of) your $Profile .ps1 file(s) so you don't need to keep using Set-Alias in every new PS instance.
Edit your profile and add an alias
Set-Alias -name 'npp' -value 'C:\Program Files\Notepad++\notepad++.exe'
Then:
npp c:\temp\test.txt
Edit your profile:
npp $profile
etc
I know this is an old question, but I found a bit of a workaround, quite by accident, and it is extremely straightforward. If you install and maintain Notepad++ via Chocolatey (think apt-get for Windows, but built on top of NuGet), then you get a shim that can be invoked from the command line.
cinst notepad++
And even if you already have an existing installation of Notepad, you can still "install" it from Chocolatey, and it will pull in the existing installation and maintain it.
I use Chocolatey for as much as I possibly can, because you can update everything in one fell swoop.
After that, editing things from PowerShell is a snap. Like my PowerShell profile:
notepad++ $PROFILE
Hope this helps someone, or several someones!
In my case, I wanted to start Notepad++ with a file as an argument, and open as admin. I wanted to open one of the PowerShell profiles. I had to use the following command variation:
start-process -Verb runas -filepath "C:\Program Files (x86)\Notepad++\notepad++.exe" "`"$($PROFILE.AllUsersAllHosts)`""
All the other variations didn't work, I think due to a space in the path of the file to be opened. So, you must escape the " as:
"He said `"This is fun.`""

adding cygwin bin directory to powershell path environment variable ... cygwin within powershell

Powershell is great for scripting. But when it comes to everyday use, certain things can be a huge PITA!!
so i thought it would be great if i could do something like this in my profile.ps1:
$env:path = "$($env:path);c:\cygwin\bin"
to get access to utilities like tar, zip, etc... but this doesn't work. The variable looks right when i do:
PS > $env:path
but when i try to do, say,
PS > unzip foo.zip
i get a command not found type error.
WTF PowerShell!?
edit: great answers! I looked at it with fresh eyes this morning and realized that I just needed to spell 'cygwin' correctly! now I don't have to switch back and forth between two consoles. It should be noted for anyone who uses this tip that your path in powershell is evaluated in order - if you put c:\cygwin\bin at the end of the $env:path variable, it will be searched last, so it won't interfere with existing powershell aliases / cmdlets.
It worked for me:
To set your profile:
$command = '$env:path = $env:path + ";C:\Program Files\Notepad++"'
$command | Out-File -FilePath $PROFILE -Append -Encoding UTF8
Or just the current shell:
$env:path = $env:path + ";C:\Program Files\Notepad++"
Using $env:path to add the cygwin bin to PATH should work as long as you are trying to use it in the same Powershell session. If you open a new console or if you close and open Powershell, it will not be persisted. Otherwise, what you are doing should work. Make sure you are indeed adding the correct path. If you want to persist the changes, add the line to your $profile.
Also, try using the Mingw / Msys / Msysgit utils. I find Mingw to be more lightweight than cygwin ( if you are using cygwin just to get some of these utils.)
PowerShell by default is only going to modify its local copy of PATH. When you run an external command, they aren't going to see the local environment variables.
Per this TechNet article, you can fall back to the .NET static method SetEnvironmentVariable to do this at the user level if you want this to be a permanent change:
[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")