简体   繁体   中英

How to put a single PowerShell output string into a cmd variable?

I have a PowerShell script that outputs a single string value. I have a cmd batch script that needs to execute the PowerShell script and place that single PowerShell output value into a variable in the batch script. I'm finding all sorts of methods for exporting to a file or reading a file but that's not what I want. Thanks!

(edit) Here's where I'm trying to use it (in response to posting the script):

@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%

( edit ) I saw the answer by the OP here Getting Powershell variable value in batch script and also looked at foxdrive's answer so I started playing with the FOR...DO statement. I thought I was pretty good with cmd and couldn't figure out why what I had wasn't working:

for /f "delims=" %%a in ('powershell . "C:\temp\PullPassword.ps1"') do set val=%%a
echo  %a% 

When I was looking at foxdrive's full answer in the other post it struck me: %a% was wrong, I needed %val%! Oh, the shame! The below works:

@echo off
set mypath=C:\temp\PullPassword.ps1
for /f "delims=" %%a in ('powershell . "C:\temp\PullPassword.ps1"') do set pass_word=%%a 
tabcmd login -s "http://myserver.net" -u mylogon -p %pass_word%

So I'll credit where it's due and mark foxdrive's answer correct, even though it was the other post that clarified my mistake.

This may help: it expects that the powershell script outputs the text to STDOUT which is the normal place for it to appear.

@echo off
for /f "delims=" %%a in (' powershell "script.ps1" ') do set "var=%%a"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM