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:
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
You have to use a sub-expression $(..)
operator to have it evaluate the reference of that property:
Write-Output "Error: $($process.ExitCode)"