Return result from Powershell script to parent batch file that executed the PowerShell script. RRS feed

  • Question

  • I need help with how to return a result value from a Powershell script to the batch file that is calling the powershell script.

    I'll include the code I'm using since it may be of use to some people.

    I have a batch file that will count the number of lines in a text file.  This text file contains a list of files I'm planning to send to a client.  I'm comparing the number of files within the text file to
    the actual number of files in a directory which will be counted by a Powershell script.  If the numbers do not match the files will not be sent.

    Batch File to count number of rows in a file and save the result to variable "IndexFile":

    Set IndexFile = findstr /R /N "^" E:\IndexFile\Index.txt |find /C ":"

    ps .\CountFilesinDirectory.ps1 <-- Batch file is executing the PowerShell script.

    Powershell script which will be executed by the above batch file and count the number of files in the "FTPOUT" directory.  

    $PowerShellResult = (Get-ChildItem E:\FTPOUT | Measure-Object ).Count

    The result is stored in Powershell variable "$PowerShellResult".  How do I return the value stored in the PowerShell variable to the parent batch file so that the batch file can
    compare the number of rows in the index file with the number of files in the "FTPOUT" directory?

    So the batch file would have code something like:
    If %IndexFile% = %PowershellResult% then EXIT 0 ELSE EXIT 1 

    Thursday, October 25, 2018 4:09 PM

All replies

  • Just output the value as a string.   Use the batch enumerator to capture the string to a variable.

    Another method is to set the exit code to the number

    exit $count


    Thursday, October 25, 2018 4:18 PM
  • For exit I've find you have to run it as:

    powershell -file .\script.ps1

    Then if you did:

    exit $count 

    It would be in the %errorlevel%.

    Thursday, October 25, 2018 7:01 PM