I am trying to run a PowerShell command through a windows command prompt to replace text in a file. The problem is that I always get ErrorLevel = 0, even when my PowerShell command does not work. My question is: how to get error code in ErrorLevel when starting PowerShell through cmd ? Please note that I would like to do this through the Windows command line, and not by creating the script part.
Here is an example of what I am saying. An error on the print screen is made deliberately by selecting a non-existing file to show that even with an ErrorLevel error is 0.
The command I use 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:
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 majkinetor's comment, I tried the following and didn't work either :(, I keep getting ErrorLevel 0 in Dos, even if 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 clearly see the error associated with the file name that it does not exist, but the error level is always 0.
I want to get an error code other than 0 for every error that occurs when running a PowerShell command.
Based on some of the comments I read, I would like to say that: I want to do this with PowerShell and with the Dos command, and not with another way. I do not want to create my own error code or personalized error management! All I want is that when an error occurred in my powershell (code, scripts, etc.), the Dos error level received this error code (I do not want to create my own code). Those who have an answer are welcome and thank you for them, but those here simply comment with useless comments, asking to change what I want, or delete photos, etc .... please do not comment, except how to provide help and answer my question without suggesting anything else, I ask for help about something specific, kindly do not change the topic to something else. The idea of ββthis site is to provide help, not to add futility and unhelpfull comments.
