'How can I get a variable valued current working directory (pwd) in powershell profile
I was trying to use anaconda as my Python virtual environment, and my virtual environment is stored in project directory.
Manually, I need to use following command to activate my local virtual environment:
conda activate ./envs
Before that, I edited script of profile.ps1 with following code:
conda init powershell
and which is revealed as following content:
#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
(& "C:\Users\dengyijian\anaconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | Invoke-Expression
#endregion
So, every time when I lauch my powershell window in project directory (press shift + right click mouse), and I got (base) environment.
What I need is enabling local environment ./venv automatically, for which I tried Including $(pwd) command, but I only got PS C:\Windows\system32>.
So as my title asking, how can I get a variable valued current working directory (pwd) in powershell profile when I launch powershell in specified working directory?
Solution 1:[1]
Unfortunately, the "Open PowerShell window here" explorer context menu option doesn't do things in the right order to allow for this. The basic command it runs does this:
- working directory starts at
c:\Windows\system32\ - Starts powershell with command to set directory (you can see this in task manager):
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location -literalPath '[explorer directory]'
- Powershell starts,
- then runs your profile .ps1
- then finally runs the
Set-Locationcommand to switch directory
Your profile script has no idea where it's being sent to yet.
You can kind of get around this by parsing the path from the command line, using $pid to get the process info:
# example of command line when starting powershell from explorer in C:\temp\
(Get-CimInstance win32_process -Filter "Handle=$pid").CommandLine
"PowerShell.exe" -noexit -command Set-Location -literalPath 'C:\temp'
# so, in your profile.ps1, take whatever is after "literalpath", then whatever is between single quotes:
$ExplorerPath = (((Get-CimInstance win32_process -Filter "Handle=$pid").CommandLine -split 'literalPath')[1] -split "'")[1]
# Then feed it to conda however you need,
# BUT remember that the next command to run after your profile script will be the "Set-Location" above
$ExplorerPath
C:\temp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cpt.Whale |
