PowerShell ISE not recognizing $profile variables - powershell

In my $profile directory, I have a few custom variables, as well as the default variables, such as $root (which equals "C:\"), etc. One custom variable I have holds the filepath to my desktop, so I can easily reference the path, and also not have to create the variable every time I start up PS. If I attempt to resolve any variable value from the $profile path within ISE(both the script pane and console) it does not work. However, if I use the regular PS terminal, it works no problem. Any suggestions or explanations?

PowerShell ISE uses a different host profile than a standard PowerShell session. The $profile variable actually displays the profile for the CurrentUserCurrentHost profile by default, but there are four profile locations stored in this variable. Each of these locations are dot-sourced by default when you load PowerShell. You can see this by typing $profile | Get-Member -MemberType NoteProperty to see the total profiles configured:
AllUsersAllHosts
AllUsersCurrentHost
CurrentUserAllHosts
CurrentUserCurrentHost
Before we continue, let's talk about what a PowerShell Host really is. From Microsoft:
The host application can define the runspace where commands are run, open sessions on a local or remote computer, and invoke the commands either synchronously or asynchronously based on the needs of the application.
So what this means is that a PowerShell Host implements a PowerShell session. This can be powershell.exe for a basic, standard host, but there could be any number of alternative applications or development tools that may implement their own PowerShell Host as well, for a number of reasons.
The AllHosts profile locations should remain standard regardless of your PowerShell host, but different PowerShell hosts will typically set their own CurrentHost profile locations for their host. For example, powershell.exe is its own PowerShell host, and will have its own host-specific profiles, named Microsoft.PowerShell_profile.ps1. PowerShell ISE implements its own PowerShell host, and has different host-specific profiles named Microsoft.PowerShellISE_profile.ps1.
If you want code in your profile to be host-agnostic, you should make sure to place your profile code in one of the AllHosts profiles. Host-specific code, such as things you only want to be available in the context of the ISE PowerShell host, or a VSCode PowerShell host, should go into that host-specific profile.

$profile is different in the ISE:
$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
console:
$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Related

git : The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program [duplicate]

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.

VS code terminal can't find AWS SAM even though windows terminal can

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.

There is an inconsistency concerning the location of powershell's profile on my windows 7 machine

I created a profile.ps1 in the same directory that contains the powershell executable, which on my machine is C:\Windows\System32\WindowsPowerShell\v1.0
The profile file is definitely executed when I run powershell.exe
However when I enter $profile at the powershell prompt, the following non-existent filename is returned
C:\Users\richard\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.psi
Does anyone know how this inconsistency may have happened and what steps should I take to resolve it?
$Profile is a string, but it has 4 note properties with possible locations to put profile scripts. Each is selected depending on which user and which host is being executed.
To see all 4, use something like this
$profile| select-object *Host* | format-list
The list you get will show profile script locations that would be run for you and this host.

Is it possible to start Powershell ISE with specified (not default) profile?

I want to have several (more than one) PowerShell profiles which will create different environments.
More specifically I need way for start separate PowerShell ISE for work with TFS and other PowerShell ISE instance for regular work. 'TFS' environment require loading some additional snappins, modules, modify prompt and so on. I do not want all this stuff will be executed for regular PowerShell ISE sessions but only when I want to.
I found that I can automatically load arbitrary script through command line parameter -File, but it does not executed automatically..
I do it by creating a shortcut for PowerShell ISE with a default directory :
In the default Directory (here called D:\TFS) I create a .PS1 file called local_profile.ps1.
In the beginning of the current profile file (C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1) I add :
# Try to load local profile
Get-ChildItem "local_profile.ps1" -ErrorAction SilentlyContinue | %{.$_}
You just have to add your initialization code to D:\TFS\local_profile.ps1.
powershell ISE has a profile too.
Probably is something like:
E:\Users\UserName\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
Or you can open powershell ise and look at $profile variable.
After locate your profile file, write your modules import and custom scripts in it.

Using $env:username in a logon script is not working

I have this setup with a GPO to run as a logon script, obviously to map a drive for clients.
net use H: \\server1\share\$env:username
Dead simple. If I put in a specific username in place of the variable then it works. Also, if I run this script directly on a client machine it works.
Do you get an error? Does it helps if you wrap the path in double quotes?
"\\server1\share\$env:username"
That should work with or without the quotation marks. Are the clients all Windows 7? I believe that Powershell logon/startup scripts don't work on earlier versions, even if you have Powershell installed, because it's an add-on rather than a native shell. If you're using downlevel clients, you can invoke the powershell script from a cmd batch file. But if you're going to do that, might as well skip Powershell and just run net use H:\\server1\share\%username% from your batch file.
Run this in a .bat file as a login script (use a FQDN for the server name):
net use H: \\server.example.com\share\%USERNAME%
If that not works, your GPO is just not yet applied. You can force that by running on the machine gpupdate /force.
For testing make sure that the GPO is applied to the right OU to the group "Authenticated Users" (computers are in the group too). And if that is not working, you can also "Enforce" the GPO. Don't forget to do a gpupdate /force after any change to the GPO or it settings.
You can also try a .js logon script like:
var WSH = new ActiveXObject("WScript.Shell");
// Map share
WSH.Run("net use H: \\\\server.example.com\\share");