0

Hello I'm trying to write a PowerShell script to execute python files. I want to get PowerShell to launch python.exe while using the username environment variable in the filepath to python.exe (this is so my colleague and I can run the PowerShell script interchangeably without worrying about our usernames, and we'd like to avoid uninstalling and reinstalling Python to C:\Python - we just ran with the default installation directory that is in our user profiles).

Here is what works in PowerShell to launch Python: C:\Users\myusername\Anaconda3\python.exe

However it does not work when I use this: C:\Users\$env:UserName\Anaconda3\python.exe

Here is the error message below:

The term 'C:\Users\$env:UserName\Anaconda3\python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1

C:\Users\$env:UserName\Anaconda3\python.exe

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo: ObjectNotFound: (C:\Users\$env:U...nda3\python.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId: CommandNotFoundException

I'm not very well versed in PowerShell yet and so far in my reading I haven't been able to figure out why this doesn't work. Can someone shed some insight on this? Would very much appreciate any assistance.

  • 1
    `& "C:\Users\$env:UserName\Anaconda3\python.exe"` is what you're after. – Abraham Zinala Feb 14 '22 at 18:58
  • 1
    In short: An executable path that is _quoted_ or contains _variable references_ must - for syntactic reasons - be invoked with `&`, the [call operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#call-operator-); see [this answer](https://stackoverflow.com/a/57678081/45375) to the linked duplicate for details. – mklement0 Feb 14 '22 at 18:59
  • Thank you both so much! Apologies for the duplicate – user17966820 Feb 14 '22 at 19:12

0 Answers0