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.
>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
-Fileparameter ofpowershell.exe, the Windows PowerShell CLI than the-Commandparameter.- See this answer for when to use
-Filevs.-Command.
- See this answer for when to use
-
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-LatestTextafter the function definition; if you want to pass any arguments received by the script through, useGet-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.