0
votes

I have some legacy python scripts that manage my shell environment for all the programs and plugins I am running on Linux (bash) and windows (cmd.exe). I want to port this to powershell.

How do I set environment variables in powershell by calling python script that prints $env:myVar=myvalue and causes my environment variable to persist in the powershell.

In Bash I can use a bash function to call my python script which prints export var=value to stdout and the function will set the environment variables in my shell. This will also work in windows cmd shell by calling a .bat file.

I cannot figure out how to do this in powershell. I think it should be something like this:

setvar.ps1:

function SETVAR {c:\python26\python.exe varconfig.py }

varconfig.py:

import sys  
print >> sys.stdout, '$env:myVar=foo'
1
I'm a bit confused here. You say have some legacy python scripts that you want to port to powershell. Then why are you just replacing your cmd wrapper with powershell? Shouldn't you rewrite the whole python script to poweshell instead? - Frode F.
What's your intention of using the environment variables; to save data across sessions? If so, I'd store it in text files instead of creating a bunch of system environment variables or even set the variables in your profile script. - Adam Bertram
I would think twice before porting portable Python script to Microsoft specific Powershell... Some people go in opposite direction — see Can I use Python as a bash replacement? - Piotr Dobrogost
Thanks for the feedback, sorry for the confusion, I want to convert the cmd shell part to powershell. The python scripts work well, the use is to setup the environment to run a version of a program, so PATH, PYTHONPATH, and other environment vars that a specific version of a program for a session. I want to use powershell because we use UNC paths so I can't navigate to directories in cmd shell. I don't need to save data across session. - leeg

1 Answers

0
votes

Is it something like this you need? It runs your scripts uses EVERY returned line to set a enviroment variable using the same format as in your sample.

& c:\python26\python.exe varconfig.py | % { 
    #Expecting all result to be $env:NAME=VALUE for variables that need to be set
    $a = $_ -replace '\$env:(\w+)=(.*)', '$1;$2' -split ';'

    #Setting variables at process-level. Can be replaced with "User" and "Machine" for permanent variables
    [System.Environment]::SetEnvironmentVariable($a[0],$a[1], "Process")
}

For process-level only, you could also simply use this. It will add quotes to the value from Your script and then simply execute it.

& c:\python26\python.exe varconfig.py | % { iex $($_ -replace '=(.*)', '="$1"') }