Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

  • 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading