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 can I Write-Output a PowerShell process object's ExitCode?

I need your help determining why I can’t output a PowerShell script process ExitCode and how to fix this. I think it has something to do with the data type of the result of the Start-Process command and the ExitCode property within it (which according to the error message at bottom here seems to be of "AnyType").

I have a simple CMD batch file named out.bat like this:

@echo off
echo Hello World, it's %1!

Then I have a seven-line PowerShell script named out.ps1, like this:

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

1.  $a = "C:\Temp\"
2.  $b = "out.txt"
3.  $c = "out.bat"
4.  $process = Start-Process -FilePath "${a}${c}" -ArgumentList "123" -RedirectStandardOutput ${a}${b} -Wait -PassThru
5.  Get-Content ${a}${b}
6.  Write-Output $process.ExitCode
7.  Write-Output "Error: $process.ExitCode"

My PowerShell script does successfully output the error code sent back by my CMD batch script file and output it per the sixth line above.

Hello World, it's 123!
0

However, the last line fails with,

Cannot convert value to type System.String.
At line:7 char:1
+ Write-Output "Error: $process.ExitCode"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromAnyTypeToString

How can I get line 7 to simply output the following?

Error: 0

>Solution :

You have to use a sub-expression $(..) operator to have it evaluate the reference of that property:

Write-Output "Error: $($process.ExitCode)"
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