Calling PowerShell from batch, and retrieving the new value of a temporary environment variable set in the script?

batch-file, environment, powershell, scripting, variables

Solution

To get Keith's idea of using stdout to work, you can invoke powershell from your batch script like this:

FOR /F "usebackq delims=" %v IN (`powershell -noprofile "& { get-date }"`) DO set "d=%v"

A little awkward, but it works:

C:\>FOR /F "usebackq delims=" %v IN (`powershell -noprofile "& { get-date }"`) DO set "d=%v"
C:\>set d
d=August 5, 2010 11:04:36 AM

Problem

I hope the title is concise, but just in case: I am calling a PowerShell script from a batch file. I want the PowerShell script to set the value of an environment variable, and for that new value to be available in the batch file when the PowerShell script finishes. I know that it is possible to set an environment variable using $env in PowerShell, but the value does not persist when the PowerShell script terminates. I imagine this is probably because PowerShell gets executed in a separate process. I am aware that I can return an exit code and use %ErrorLevel%, but that will only give me numbers, and there will be a conflict, since 1 indicates a PowerShell exception rather than a useful number. Now, here's the caveat: I don't want the environment variable to persist. That is, I don't want it to be defined for the user or system, and therefore I want it to be unavailable as soon as the batch file exits. Ultimately, I simply want to communicate results back from a PowerShell script to the calling batch file. Is this possible? Thanks in advance :) Nick

Original source