退出子进程并让它更新父进程中的环境变量

问题描述 投票:0回答:1

因此,我尝试将批处理文件移植到 c# 或将批处理文件编译为 exe 并使其像批处理文件一样运行,但没有成功。这是一个可以批量运行但不能作为 exe 运行的代码片段。

:localNumber
if "%returnow%"=="overwrite" (
  set "return%1=[L]_%cd%"
  goto exitOK
)
call FunctionGetReturn %1
if errorlevel 1 goto makeLocal
call set /p returnDisk=<%appdata%\%sparstr%\returnDisk.txt
call set /p returnValue=<%appdata%\%sparstr%\returnValue.txt
if defined return%1 goto choiceNumberLocal
call set "%returnDisk%=[L]_%cd%"
goto exitNumber

我搜索了这个问题的链接,但没有看到任何解决方案。

我使用的批处理编译器是AdvancedBatToExe。至于c#,使用Visual Studio使用特殊的构建命令进行编译。

c# batch-file compiler-construction
1个回答
0
投票

也许试试这个(你可以将参数更改为你喜欢的任何内容)

// Create a new process to run the SETX command
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C setx Test_variable \"Variable value\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();

// Wait for the process to exit
process.WaitForExit();

// Get the value of the Test_variable from the system environment
string value = Environment.GetEnvironmentVariable("Test_variable", EnvironmentVariableTarget.Machine);

您也可以将它们包装在自己的函数中:

public string GetEnvVar(string name) {
    return Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Machine);
}

public void RunCommand(string command) {
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = command;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.Start();

    // Pause thread until completed
    process.WaitForExit();
}

如果您有任何问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.