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.
Related
I installed AWS SAM from the msi installer from AWS for windows.
after running the installer, I ran sam --version in cmd and powershell.
PS C:\Users\dgupta> sam --version
SAM CLI, version 1.26.0
It returns the version I just installed. However in VS code, I opened a terminal and ran sam --version it errors out.
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
sam : The term 'sam' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, g of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ sam --version
+ ~~~
+ CategoryInfo : ObjectNotFound: (sam:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
why is this happening ? doesn't VS Code terminal and normal terminal have access to the same environment variables ?
It's impossible to diagnose your problem without further information, but perhaps these troubleshooting tips help:
If you're invoking an external executable (sam) by name only, your problem must be that the directory in which the executable resides isn't listed in the $env:PATH environment variable defined for the current process.
However, it is possible that the external sam executable's directory isn't in $env:PATH and that sam is an auxiliary PowerShell command of the same name that knows the true sam's location and invokes it behind the scenes.
For instance an alias - such as New-Alias sam 'C:\path\to\sam.exe' - or a function - such as function sam { & C:\path\to\sam.exe $args } - could be defined.
From the PowerShell session where sam is found:
To determine what type of command the name sam refers to in your session, use the following and check the value of the CommandType column:
Get-Command sam
If the command type is Application, you are indeed dealing with an external executable, and the Source column will report its full path, from which you can glean the executable's directory path (which you can determine directly with Split-Path (Get-Command -Type Application sam).Path
You then need to diagnose why that directory isn't in $env:Path in the other session - see first section below.
If the command type isn't Application:
You need to determine where the auxiliary alias or function is defined and why your other session doesn't see it, which, if the problem is reproducible in new sessions, must be connected to what profile files (as reflected in the automatic $PROFILE variable) were loaded.
Diagnose why a directory is missing from $env:PATH:
Possible reasons:
You've just installed an executable, and the installer modified the persistent $env:PATH definition in the registry.
Any running processes started before this modification or even started afterwards directly from such a process do not see the modification.
Solution:
Start a new session, which in your case means restarting Visual Studio Code, but be sure to start it from the Start Menu / taskbar / File Explorer, as they are aware of the modified environment. When in doubt, log off and back on to your Windows session, or reboot your machine.
Alternatively, refresh $env:PATH from the registry in-session - see below.
Something in your current PowerShell session has (possibly inadvertently) removed sam's directory from the in-process $env:PATH variable.
Solution:
Refresh the in-process $env:PATH definition from the registry with the following command (note that any prior in-process modifications are then lost):
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User')
If these solutions don't help (persistently), the problem must be :
Either: Even the persistent Path variable definition is lacking an entry for the directory or interest (even though installers normally do add such an entry).
Or: The problem arises from what PowerShell profile files are loaded into the different environments.
See the next sections.
Add a directory entry to the persistent definition of the Path environment variable yourself:
Interactively:
Run sysdm.cpl, select the Advanced tab, and click on Environment Variables..., then modify the Path variable as desired.:
Note: To modify the Path variable under System variables, i.e. the system-wide part of the Path variable, you need to be an administrator.
After having modified Path this way, you need to open a new shell session in the manner described above in order to see the effects.
Programmatically:
See this answer for helper function Add-Path; the answer also explains why set.exe should not be used.
Diagnose what profile files were loaded into a session:
PowerShell's profile files are (by default) loaded (dot-sourced) on session startup and allow sessions to be customized, which can include things such as custom alias definitions, functions, and even in-process $env:PATH additions.
There are multiple profile files, all of which are loaded (by default), if present, along two independent dimensions: all-users vs. current-user, and all-hosts vs. current-host (a host being the PowerShell host environment, such as a regular console window or the terminal in Visual Studio Code).
The automatic $PROFILE variable reports the current-user, current-host profile-file path, but actually has normally invisible properties listing all paths (you can make them visible with $PROFILE | select * - see this answer).
What profiles are loaded into a session for a given user is determined by the following factors:
Fundamentally, whether profile loading is suppressed altogether, using the CLI's -NoProfile switch.
If not suppressed (the default, even with -Command and -File invocations):
What edition of PowerShell you're using: The comes-with Windows, legacy Windows PowerShell edition (whose latest and final version is 5.1), whose CLI is powershell.exe, vs. the install-on-demand cross-platform PowerShell (Core) edition, whose CLI is pwsh.exe, have separate profile locations.
The type of the host environment, as reflected in the automatic $Host variable.
To see what command line was used to invoke the current session, run the following:
[Environment]::CommandLine
Note:
In a PowerShell Integrated Console in Visual Studio Code you'll always see -NoProfile among the parameters, but the profiles may still be loaded during startup, depending on the settings of PowerShell extension
It follows from the above that different host environments load different sets of profile files, and in the PowerShell Integrated Console provided by Visual Studio Code's PowerShell extension, different profile files are indeed loaded (if loading is enabled via the settings) - compared to regular console windows[1]
If you want your PowerShell Integrated Consoles to load the same current-user profile as regular console windows:
Via Visual Studio Code's settings, make sure that the PowerShell: Enable Profile Loading setting is enabled.
From a PowerShell Integrated Console, run psedit $PROFILE to open the host-specific current-user profile for editing.
Add the following content:
. ($PROFILE -replace '\.VSCode', '.PowerShell')
[1] Note that you can use PowerShell in the Visual Studio Code terminal even without the PowerShell extension, and such session do use the same profiles as regular console windows - see this answer.
I installed AWS SAM from the msi installer from AWS for windows.
after running the installer, I ran sam --version in cmd and powershell.
PS C:\Users\dgupta> sam --version
SAM CLI, version 1.26.0
It returns the version I just installed. However in VS code, I opened a terminal and ran sam --version it errors out.
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
sam : The term 'sam' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, g of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ sam --version
+ ~~~
+ CategoryInfo : ObjectNotFound: (sam:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
why is this happening ? doesn't VS Code terminal and normal terminal have access to the same environment variables ?
It's impossible to diagnose your problem without further information, but perhaps these troubleshooting tips help:
If you're invoking an external executable (sam) by name only, your problem must be that the directory in which the executable resides isn't listed in the $env:PATH environment variable defined for the current process.
However, it is possible that the external sam executable's directory isn't in $env:PATH and that sam is an auxiliary PowerShell command of the same name that knows the true sam's location and invokes it behind the scenes.
For instance an alias - such as New-Alias sam 'C:\path\to\sam.exe' - or a function - such as function sam { & C:\path\to\sam.exe $args } - could be defined.
From the PowerShell session where sam is found:
To determine what type of command the name sam refers to in your session, use the following and check the value of the CommandType column:
Get-Command sam
If the command type is Application, you are indeed dealing with an external executable, and the Source column will report its full path, from which you can glean the executable's directory path (which you can determine directly with Split-Path (Get-Command -Type Application sam).Path
You then need to diagnose why that directory isn't in $env:Path in the other session - see first section below.
If the command type isn't Application:
You need to determine where the auxiliary alias or function is defined and why your other session doesn't see it, which, if the problem is reproducible in new sessions, must be connected to what profile files (as reflected in the automatic $PROFILE variable) were loaded.
Diagnose why a directory is missing from $env:PATH:
Possible reasons:
You've just installed an executable, and the installer modified the persistent $env:PATH definition in the registry.
Any running processes started before this modification or even started afterwards directly from such a process do not see the modification.
Solution:
Start a new session, which in your case means restarting Visual Studio Code, but be sure to start it from the Start Menu / taskbar / File Explorer, as they are aware of the modified environment. When in doubt, log off and back on to your Windows session, or reboot your machine.
Alternatively, refresh $env:PATH from the registry in-session - see below.
Something in your current PowerShell session has (possibly inadvertently) removed sam's directory from the in-process $env:PATH variable.
Solution:
Refresh the in-process $env:PATH definition from the registry with the following command (note that any prior in-process modifications are then lost):
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User')
If these solutions don't help (persistently), the problem must be :
Either: Even the persistent Path variable definition is lacking an entry for the directory or interest (even though installers normally do add such an entry).
Or: The problem arises from what PowerShell profile files are loaded into the different environments.
See the next sections.
Add a directory entry to the persistent definition of the Path environment variable yourself:
Interactively:
Run sysdm.cpl, select the Advanced tab, and click on Environment Variables..., then modify the Path variable as desired.:
Note: To modify the Path variable under System variables, i.e. the system-wide part of the Path variable, you need to be an administrator.
After having modified Path this way, you need to open a new shell session in the manner described above in order to see the effects.
Programmatically:
See this answer for helper function Add-Path; the answer also explains why set.exe should not be used.
Diagnose what profile files were loaded into a session:
PowerShell's profile files are (by default) loaded (dot-sourced) on session startup and allow sessions to be customized, which can include things such as custom alias definitions, functions, and even in-process $env:PATH additions.
There are multiple profile files, all of which are loaded (by default), if present, along two independent dimensions: all-users vs. current-user, and all-hosts vs. current-host (a host being the PowerShell host environment, such as a regular console window or the terminal in Visual Studio Code).
The automatic $PROFILE variable reports the current-user, current-host profile-file path, but actually has normally invisible properties listing all paths (you can make them visible with $PROFILE | select * - see this answer).
What profiles are loaded into a session for a given user is determined by the following factors:
Fundamentally, whether profile loading is suppressed altogether, using the CLI's -NoProfile switch.
If not suppressed (the default, even with -Command and -File invocations):
What edition of PowerShell you're using: The comes-with Windows, legacy Windows PowerShell edition (whose latest and final version is 5.1), whose CLI is powershell.exe, vs. the install-on-demand cross-platform PowerShell (Core) edition, whose CLI is pwsh.exe, have separate profile locations.
The type of the host environment, as reflected in the automatic $Host variable.
To see what command line was used to invoke the current session, run the following:
[Environment]::CommandLine
Note:
In a PowerShell Integrated Console in Visual Studio Code you'll always see -NoProfile among the parameters, but the profiles may still be loaded during startup, depending on the settings of PowerShell extension
It follows from the above that different host environments load different sets of profile files, and in the PowerShell Integrated Console provided by Visual Studio Code's PowerShell extension, different profile files are indeed loaded (if loading is enabled via the settings) - compared to regular console windows[1]
If you want your PowerShell Integrated Consoles to load the same current-user profile as regular console windows:
Via Visual Studio Code's settings, make sure that the PowerShell: Enable Profile Loading setting is enabled.
From a PowerShell Integrated Console, run psedit $PROFILE to open the host-specific current-user profile for editing.
Add the following content:
. ($PROFILE -replace '\.VSCode', '.PowerShell')
[1] Note that you can use PowerShell in the Visual Studio Code terminal even without the PowerShell extension, and such session do use the same profiles as regular console windows - see this answer.
When you're in file explorer you can click on File > Open Windows Powershell(or its icon in the Quick Access Toolbar) to start an instance of Powershell in the directory that your file explorer is in. I would like to then automatically run a simple command in this directory and close the Powershell window after it is done.
I have tried adding my command to my Powershell Profile but it executes before the path variable has been set and it runs with $pwd being equal to C:\Users\MyUsername (my home directory) or C:\WINDOWS\system32 (seems to be a race condition of some sort, no idea why it does one or the other). To the best of my understanding this is because the file explorer "open in powershell button" opens powershell and THEN cd's to the directory I was in in file explorer. So when the profile.ps1 is ran it is using the only directories it knows if since the cd call hasn't been made yet. This is similar to running the command start powershell.exe in cmd vs start powershell.exe -command "cd 'C:\wherever'". The former correctly runs my profile command while the latter uses the current directory of cmd and not the C:\wherever.
So, obviously the $pwd variable is being assigned at different times in the case of opening it from cmd and opening it from file explorer. Is there some way to delay the execution of a command in the profile until after the shell has fully loaded? Simply sleeping the script doesn't help.
Alternatively, if anyone knows how to edit the registry so that I can change the behavior of clicking File > Open Windows Powershell (since it must have access to some variable storing the current directory and I assume it calls the Powershell executable with this variable as an argument being cd'd to), that would work too.
Then again I could be incredibly naive about how File > Open Windows Powershell and the Powershell instantiation process works.
Any help is greatly appreciated, thank you!
I figured it out in the most hacky, gross way ever, but without easy access to Windows internals this is the only working method I could find. I set up my powershell profile to make my window title my prompt like so:
function Prompt
{
$host.ui.RawUI.WindowTitle = $(get-location)
“PS> “
}
Then I set up a task in the Task Scheduler that was triggered by powershell reaching its prompt (there are 3 possible hooks, when the console is starting up, when it starts an IPC listening thread, and when the console is ready for input). I used the Event Viewer to do this (I was going to post screenshots but I don't have 10 reputation yet).
Then, I set the action on this task to run the script shown below, which reads from the window title of my first instance of powershell
Start-Sleep -s 1
$A = Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID}
$B = $A.MainWindowTitle
& C:\Program` Files\MyProgram\MyProgram.exe "$B"
stop-process -Id $A.Id
stop-process -Id $PID
This whole menagerie of events properly runs my program with the current file explorer directory as an argument (and then closes powershell) when I click the little powershell icon on the quick access toolbar in file explorer.
Found a much cleaner and faster way to do this. All I had to do was set up my profile to look like this, no tasks or second instance of powershell required
function Prompt
{
& C:\Program` Files\MyProgram\MyProgram.exe "$pwd"
stop-process -Id $PID
}
When I start Notepad++ from Start menu, the window has certain dimensions and the font size is as I've set it to last time. However, then I execute it from PowerShell, the window is much smaller and so is the font size.
I suspect that I'm not executing the program with me as the invoker. Is that correct and what can I do about it?
I've tried both Invoke-Item and Start-Process but they both produced the same result (and I'm not sure about the difference between them, despite googlearching).
function Edit{
param([string]$file = " ")
Invoke-Item 'C:\Program Files (x86)\Notepad++\notepad++.exe ' $file
#Start-Process 'C:\Program Files (x86)\Notepad++\notepad++.exe' $file
}
If you are using above windows 7.
If you run Notepad++ as your account it will run as your standard account however if you launch it form an admin PowerShell session you will be launching Notepad++ in an admin session as well, which causes the Notepad++ to use a 'seperate profile' for lack of a better way of explaining it.
Basically your standard account and your admin account, although they may be your account, they aren't the same profile and are able to have different settings.
I'm trying to have powershell create a folder for me and it works fine when I type it into the console. However, when I run the same command as a script, no folder is created and no error messages are supplied.
This is the line of code I am using.
new-item - path c:\test\ -name testfolder -itemtype directory
edit: I am on Windows 7
This should be a comment, but I cannot comment. There is definitely nothing wrong with that line of code. It runs on my machine, either from the terminal window or as a script. Because the code works for you at the terminal window but not when executing as a script my first guess is that your system may be configured to disallow powershell scripts. This is the default setting, and it will prevent a script file from executing but will not prevent commands typed at the prompt from working. Open a powershell session and type get-executionpolicy. If it returns "restricted" then you have found the culprit. This setting can be changed by opening an elevated powershell session (run as admin) and typing set-executionpolicy -executionpolicy RemoteSigned. Of course you should read about what those settings mean before changing them to determine what is best for your situation. For example the remotesigned option means that scripts originating from your machine will execute without a trusted signature, but external scripts will require a signature.