How to get the error code (ErrorLevel) from PowerShell on the Windows command line?

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.

Error 2

+8
source share
4 answers

Try this code in the cmd.exe shell:

 C:> powershell -noprofile -command " try { 1/0 } catch {exit 22}" C:> echo %errorlevel% 22 

So, add your commands to the try block. If this happens, you call the non powershell command, you can exit $LastExitCode (but from the try block).


EDIT

Well, I know what happens to your non-working code, it never missed a catch catch block, since Get-Content produces an error without end . You should take care of this:

 C:> Powershell -Command "try { (Get-Content HvsvmAppserver.ref -ea stop) -replace '-Dfr.base0.role=', '-Dfr.base0.role=USR_ROLE'| Set-Content -encoding ASCII HvsJvmAppserver.ref -ea stop } catch {$_; exit 123 }" Get-Content : Cannot find path 'C:\Users\majkinetor\HvsvmAppserver.ref' because it does not exist. At line:1 char:8 + try { (Get-Content HvsvmAppserver.ref -ea stop) -replace '-Dfr.base0. ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Users\majkinetor\HvsvmAppserver.ref:String) [Get-Content], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand C:> echo %errorlevel% 123 

Notice the -ea stop that I added to both commands (shorter than ErrorAction). My decision was right the first time, however you need to understand that the script must be properly designed. You can also use trap instead of catch, but you still have to use EA stop. Perhaps the shortest general solution that doesn't depend too much on the script:

  $ErrorActionPreferance = 'Stop' <your script goes here, no need for -ea stop in it> trap { exit 123 } 

This will not work if the script question changes $ErrorActionPreference (which rarely happens), but will work in all other cases.

+5
source

So, let's put this as an answer based on my comment:

You get zero because that is the value you pass. if you want to use one of your variables as an exit code, you must give them something.

To which you answered:

@ShawnMelton Thank you, but I can’t do it ... I don’t want my own error code or personalized error management! All I want is that when an error occurs in my powershell (code, scripts, etc.), the Dos error level receives this error code (I don’t want to make my own code). Can you illustrate with the code what you mean? I may not understand your comment? Thanks for trying to help your side.

Being that you call powershell.exe , it will return the exit code back to the command line, always as zero (0). It will always be zero, even if you execute the wrong PowerShell code. powershell.exe itself successfully executes any command that you pass, so if for some reason the executable itself does not make a mistake, you always get zero. If you want powershell.exe return something other than zero, you need to use exit xx in your PowerShell command, where xx is an integer. enter image description here

Which question, which didn't try to invoke PowerShell from the command line, still raises whether you want to be here or not. You are not guaranteed that even using something like exit 99 will always overwrite an executable that returns zero ... it's just the way it works. I got various results when I tried this on my laptop with Windows 10. I can say that I used the technique before production, when I had to call PowerShell scripts from SSIS packages, and that served the purpose. However, in this situation, I did not call it from the batch file, so it worked as expected.

0
source

If you use the external command last, it will set the error level. I quote pipe using "^".

 powershell echo hi ^| findstr hi2 

Or can you check $? and exit with a non-zero number:

 powershell 1/0; if (! $?) { exit 1 } 

In fact, if the LAST cmdlet throws an error, whether it completes or not, it should set the cmd error level.

You can do something like this and exit with a number of errors.

 powershell $errorcount = $error.count; 1/0; echo hi; exit $error.count - $errorcount 
0
source

The @majkinetor suggestion definitely works. I mean this:

 powershell -Command "try {(gc "C:\test.txt" -ea stop) -creplace 'test', 'work' | Out-File -encoding ASCII "C:\test.txt" -ea stop} catch{ exit 1}" 

If the file path is specified correctly, the string is replaced. If the file path is incorrect, the error level in the cmd session is set to 1 using the above snippet.

The problem I am facing is that I want this to not help build Jenkins. I use the build step Execute the Windows batch command, and the trick is that you only need the above command if you want it to fail when it fails. If you have another one and it is successful, the assembly is successful.

0
source

All Articles