3

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.

Community
  • 1
  • 1
Air_Cooled_Nut
  • 129
  • 3
  • 5
  • 21
  • 2
    Can you post your script, or at least enough of it to be able to demonstrate what it is you're trying to do? – mjolinor Feb 11 '14 at 16:20

1 Answers1

6

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"
foxidrive
  • 40,353
  • 10
  • 53
  • 68