I am trying to launch a PowerShell command through Windows command prompt to replace a text into a file. The problem is that I am always getting ErrorLevel = 0 even when my PowerShell command is not working.
My question is how to get an error code into ErrorLevel when I launch PowerShell through cmd
?
Please note that I would like to make this through the Windows command prompt and not by creating a script a part.
Here is an example of what I am saying. The error in the print screen is made intentionally by choosing an non existing file to show you that even when there is an error, the ErrorLevel is equal to 0.
The command I am using is the following (I tried $LastExitCode
and $ExitCode
):
powershell -NonInteractive -NoProfile -Command "(Get-Content HvsvmAppserver.ref) -replace '-Dfr.base0.role=', '-Dfr.base0.role=USR_ROLE'| Set-Content -encoding ASCII HvsJvmAppserver.ref; exit $LastExitCode"
But I also tried the same with:
powershell -NonInteractive -NoProfile -Command "(Get-Content HvsvmAppserver.ref) -replace '-Dfr.base0.role=', '-Dfr.base0.role=USR_ROLE'| Set-Content -encoding ASCII HvsJvmAppserver.ref; exit $ExitCode"
Based on the comment of majkinetor, I tried the following and hasn't work as well :(, I am keep getting ErrorLevel 0 in Dos even when an error occurs in powershell.
powershell -noprofile -command " try { (Get-Content HvsvmAppserver.ref) -replace '-Dfr.base0.role=', '-Dfr.base0.role=USR_ROLE'| Set-Content -encoding ASCII HvsJvmAppserver.ref } catch {exit $LastExitCode}"
You can see clearly an error related to the file name that it doesn't exist, but the error level is always 0.
What I want is to get an error code other than the 0 for each error that happens while executing the PowerShell command.
powershell.exe ...
from a cmd.exe prompt. Just run the commands directly from thePS C:\>
PowerShell prompt. – Residuum