gpt4 book ai didi

c# - C#程序保持不变的错误级别

转载 作者:行者123 更新时间:2023-12-03 09:13:13 25 4
gpt4 key购买 nike

有没有办法从C#中读取ERRORLEVEL,以便您可以返回它并在完成后保持不变?

程序启动时,Environment.ExitCode似乎以0开头。该程序始终写入0。

To too lazy; didn't read people: the following code is not the program I want to write, but a test to prove that Environment.ExitCode is not inherited from errorlevel, %errorlevel% or any previous exit code just in case of doubt.


using System;

namespace test {
class Program {
static void Main() {
Console.WriteLine("{0}",Environment.ExitCode);
}
}
}

我的目标是编写一个程序,当批量使用该程序时,它不会干扰当前的错误级别,因此可以在以后使用。我知道您可以保存它并将其还原到批处理中...
...
command1 with options "or not"
set elsaved=%errorlevel%
my_cs_program run without telling it which errorlevel is
REM Damn, I cleared errorlevel, thank science I saved it before
call :setel %elsaved%
...
goto :eof

:setel
exit /b %1

...但是很麻烦。如果调用仅保留错误级别,那将更好。
...
static void Main() {
...
var parent_cmd_errorlevel=exotic_funtion();
...
Environment.ExitCode = parent_cmd_errorlevel;
...

这样,我不必在批处理中考虑它。

tl;博士:是否可以将C#程序 透明编写为错误级别?如果不是使用C#,是否还有其他语言?哪一个更笼统地说:cmd.exe子进程可以获取其父级的错误级别吗?也许 wmic会有所帮助?

要向 投票者/ 重复投票者:我知道如何在.NET中指定控制台应用程序的退出代码:
...
static void Main() {
...
Environment.ExitCode = whatever;
...

要么
...
static int Main() {
...
return(whatever);
...

我错了吗?如果您对这个问题不感兴趣,请不要理会这个问题,但是在SO或其他SE KB中没有问过AFAIK。

最佳答案

您无法从上一个程序读取ERRORLEVEL,但可以将其作为参数传递,然后再次进行设置:

class Program
{
static void Main(string[] args)
{
Environment.ExitCode = int.Parse(args[0]);
}
}

然后像这样在批量中调用它:
cd "some path that returns an error"
.\Console1App.exe %errorlevel%

REM Print the error code of the cd command
echo %errorlevel%

请注意,这仅在未设置%errorlevel%环境变量的情况下有效。 CMD的工作方式是,当未设置%errorlevel%时,它将通过实际的错误级别作为后备

关于c# - C#程序保持不变的错误级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com