简体   繁体   中英

Set-Variable powershell. How do I link a variable to an exe file?

I'm quite new to the PowerShell environment, but I'm supposed to use it for "Learn python the hard way". In the mac terminal you can just type:

python script.py

In PowerShell on Windows this does not work. I'd like to be in any folder in my computer and execute python on a script in that folder. For that I believe the best thing to do is create a variable that calls python.exe instead of having to list the path every time.

I have tried declaring a python variable in the Command Prompt window but they don't seem to carry over.

Any small additional information like the name of the action I'm trying to do would be helpful!

This is actually pretty easy to do using the Set-Alias instead of Set-Variable . You will basically just pick up the path and how you want to reference it in your code.

I do this often for when I need to call 7z.exe (aka 7-zip ) in my scripts:

$szPath = "$env:ProgramFiles\7-zip\7z.exe
if (Test-Path $szPath) {
 Set-Alias sz $szPath -Scope Global
}

Then anytime I want to call that program and need to use variables specific to 7-zip I just call it:

sz l $filename

You should be able to do the same with python executable:

Set-Alias python '<Path to Python.exe' -Scope Global

I only use Global scope so it ensures I can get to anywhere in my process, so if you have any child scripts that may get called the alias is still usable.

Your other option would be to set the python executable path in your environment variables for Windows. Then you would be able to just call python as well.

This has nothing to do with variables. You just need to ensure that Python is on your PATH.

I don't know how to do this for python, but this example is from the response to "help alias"

PS> new-item -path alias:np -value c:\windows\notepad.exe

Now, "np" will be an alias for notepad, and it can be used as a command, like any other alias.

If C:\\Python27 is your python directory, then :

$newPath = [Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\Python27\"
[Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")

will add it to your PATH environment variable, and then you'll be able python everywhere you want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM