views:

51

answers:

2

Hey guys!

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

+1  A: 

The most straight forward way to capture results from PowerShell is to use stdout in PowerShell. For example, this saves the date to the d env var in cmd.exe

set d = powershell -noprofile "& { get-date }"
Keith Hill
Nice solution. I doubt there is any other that is so easy and straightforward.
stej
Nicholas Hill
@Nicholas, you are right. I have tried it now and there is really only string stored in the variable.
stej
Doh! If only CMD were as straight-forward as PowerShell. Good thing @zdan has got the cmd.exe side covered cuz the only thing I ever used cmd.exe for was runnning command line utilities and other people's batch files. :-)
Keith Hill
@Keith, once you get the vagaries of the "for" command down, CMD can actually become useful (though only if powershell isn't available).
zdan
+1  A: 

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
zdan