Home > Mobile >  How to use a PowerShell function return as a variable in a batch file
How to use a PowerShell function return as a variable in a batch file

Time:02-02

I was trying to use the return from myPowershellScript.ps1 to use as a variable in my batch file.

myPowershellScript.ps1

function GetLatestText
{
    return "Hello World"
}

I was trying to use the For /F function. There may be a better way.

myBatch.bat

for /f "delims=" %%a in (' powershell -command "\\Rossi2\Shared\myPowershellScript.ps1" ') do set "var=%%a"

echo %var%

Desired output, would be to have 'Hello World' output in the cmd window.

I was trying to use the batch file as some old processes use them. For newer processes I do everything in PowerShell and it works fine.

The current output is blank.

CodePudding user response:

  • Your syntax for trying to capture output from a PowerShell script from a batch file is correct (assuming single-line output from the script),[1] except that it it is more robust to use the -File parameter of powershell.exe, the Windows PowerShell CLI than the -Command parameter.

  • Your problem is with the PowerShell script itself:

    • You're defining function Get-LatestText, but you're not calling it, so your script produces no output.

    • There are three possible solutions:

      • Place an explicit call to Get-LatestText after the function definition; if you want to pass any arguments received by the script through, use Get-LatestText @args

      • Don't define a function at all, and make the function body the script body.

      • If your script contains multiple functions, and you want to call one of them, selectively: in your PowerShell CLI call, dot-source the script file (. <script>), and invoke the function afterwards (this does require -Command):

         for /f "delims=" %%a in (' powershell -Command ". \"\\Rossi2\Shared\myPowershellScript.ps1\"; Get-LatestText" ') do set "var=%%a"
        
         echo %var%
        

[1] for /f loops over a command's output line by line (ignoring empty lines), so with multiline output only the last line would be stored in %var% - more effort is needed to handle multiline output.

CodePudding user response:

You can combine the batch and the powershell in single file (save this as .bat ):

<# : batch portion
@echo off & setlocal

    for /f "tokens=*" %%a in ('powershell -noprofile "iex (${%~f0} | out-string)"') do set "result=%%a"
    echo PS RESULT: %result%

endlocal
goto :EOF

: end batch / begin powershell #>

function GetLatestText
{
    return "Hello World"
}

write-host GetLatestText
  • Related