JNK
JNK

Reputation: 65197

PowerShell - Outputting to a variable not working

I am writing a rather lengthy PowerShell script to perform a lot of functions. For the most part, everything is going very well.

However, another function I am running at all levels of the script is a very detailed log. I'll post the command line portion as an example (simplified):

    $Batch = $RunMe[1]
    $ResultCode = (Invoke-Expression $Batch -ErrorAction Stop)
    $ResultCode

My expected result is:

Return Code 0

Then I would log it. Instead I am getting something like:

C:\batchfiles\batchfile.bat argument

Which is the command I am using Invoke-Expression to execute.

Some quick explanation of the variables:

$RunMe is an array that stores the commands (0 is either "Batch" or "Proc" and 1 is the command to run)

$Batch is created in the code as written (this is the first reference to it)

$CurrFileToExec is the current file being processed (the script runs on a folder at a time). I'm using it for a string replace for the command line I got from SQL.

I can't get $ResultCode to pass the correct output of the command. It just passes the command line function ($Batch) again.

As I said, the actual functionality part works great, but I can't get that return code to my logfile.

Upvotes: 2

Views: 3463

Answers (2)

JNK
JNK

Reputation: 65197

The solution was to modify my $Batch variable to add a cmd /c to the beginning. I think there was an issue with just using Invoke-Expression and scoping of the output parameter. I added a line for:

$Batch = "cmd /c " + $Batch

Then ran again, and $ResultCode had the expected output.

Upvotes: 4

x0n
x0n

Reputation: 52480

If I can presume $batch contains external executables, the return code will be in the automatic variable $LASTEXITCODE - invoke-expression's return consists of things written to STDOUT and STDERR by external applications or things written to powershell's output or error streams by script. It will not contain the executable's dos-style return code, if you called one.

Upvotes: 5

Related Questions