我希望标题简洁明了,但以防万一:
我从批处理文件中调用PowerShell脚本.我希望PowerShell脚本设置环境变量的值,并在PowerShell脚本完成时使该新值在批处理文件中可用.
我知道可以在PowerShell中使用$ env设置环境变量,但是当PowerShell脚本终止时,该值不会保留.我想这可能是因为PowerShell在一个单独的进程中执行.
我知道我可以返回退出代码并使用%ErrorLevel%,但这只会给我数字,并且会有冲突,因为1表示PowerShell异常而不是有用的数字.
现在,这里需要注意的是:我不希望环境变量持续存在.也就是说,我不希望为用户或系统定义它,因此我希望它在批处理文件退出后立即不可用.最后,我只想将结果从PowerShell脚本传递回调用批处理文件.
这可能吗?
提前致谢 :)
缺口
我有一个输出单个字符串值的 PowerShell 脚本。我有一个 cmd 批处理脚本,需要执行 PowerShell 脚本并将单个 PowerShell 输出值放入批处理脚本中的变量中。我正在寻找各种导出到文件或读取文件的方法,但这不是我想要的。谢谢!
(编辑)这是我尝试使用它的地方(响应发布脚本):
@echo off
REM The next line puts the .ps1 output into the variable
REM and, obviously, this does not work
set pass_word=<C:\temp\PullPassword.ps1
tabcmd login -s "http://myserver.net" -u mylogon -p %pass_word%
Run Code Online (Sandbox Code Playgroud)
(编辑)我在这里看到了OP的答案Getting Powershell variable value in batch script,还查看了foxdrive的答案,所以我开始使用FOR...DO语句。我认为我对 cmd 非常擅长,但不明白为什么我的命令不起作用:
for /f "delims=" %%a in ('powershell . "C:\temp\PullPassword.ps1"') do set val=%%a
echo %a%
Run Code Online (Sandbox Code Playgroud)
当我在另一篇文章中查看 Foxdrive 的完整答案时,我震惊了:%a% 是错误的,我需要 %val%!噢,耻辱!以下作品:
@echo off
set mypath=C:\temp\PullPassword.ps1
for /f "delims=" %%a in ('powershell . …Run Code Online (Sandbox Code Playgroud)