从批处理中调用 PowerShell,并检索脚本中设置的临时环境变量的新值? [英] Calling PowerShell from batch, and retrieving the new value of a temporary environment variable set in the script?

查看:27
本文介绍了从批处理中调用 PowerShell,并检索脚本中设置的临时环境变量的新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望标题简洁,但以防万一:

I hope the title is concise, but just in case:

我正在从批处理文件调用 PowerShell 脚本.我希望 PowerShell 脚本设置环境变量的值,并在 PowerShell 脚本完成时在批处理文件中提供该新值.

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.

我知道可以在 PowerShell 中使用 $env 设置环境变量,但是当 PowerShell 脚本终止时该值不会保留.我想这可能是因为 PowerShell 在单独的进程中执行.

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.

我知道我可以返回退出代码并使用 %ErrorLevel%,但这只会给我数字,并且会发生冲突,因为 1 表示 PowerShell 异常而不是有用的数字.

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.

现在,这里有一个警告:我不希望环境变量持续存在.也就是说,我不希望为用户或系统定义它,因此我希望它在批处理文件退出后立即不可用.最终,我只想将结果从 PowerShell 脚本返回到调用批处理文件.

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.

这可能吗?

提前致谢:)

尼克

推荐答案

为了让 Keith 了解使用 stdout 工作的想法,您可以像这样从批处理脚本中调用 powershell:

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"

有点尴尬,但它有效:

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

这篇关于从批处理中调用 PowerShell,并检索脚本中设置的临时环境变量的新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆