You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ShellExecuteExW以runas调用cmd执行复制命令成功但文件未复制

高权限Shell命令执行异常:复制文件到C:\Program Files失败

问题描述

我编写了一个单元测试,用于验证高权限执行Shell命令的功能,测试目标是将测试文件复制到C:\Program Files目录。测试代码通过调用C函数ShellExecuteExW,设置lpVerb = L"runas"以获取管理员权限,lpFile = L"cmd"执行命令。调用过程无报错,UAC权限提升提示正常弹出并确认,但执行完成后目标目录始终未出现测试文件。

手动以管理员权限打开命令提示符执行相同复制命令可成功完成操作,改用ShellExecute函数也出现同样问题。

环境信息

  • 操作系统:Windows 7
  • 编译器:Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64

相关C代码

#include <windows.h>
#include <Shellapi.h>

int main() {
    SHELLEXECUTEINFOAW shExecInfo = { 0 };

    // 设置结构体大小
    shExecInfo.cbSize = sizeof(SHELLEXECUTEINFOAW);

    // 指定操作:提升权限
    shExecInfo.lpVerb = L"runas"; 

    // 指定要执行的程序
    shExecInfo.lpFile = L"cmd";

    // 指定命令参数:复制文件并将错误输出到临时文件
    shExecInfo.lpParameters = L"/C /U copy data\\txt\\file.txt \"C:\\Program Files\" 2> %TEMP%\\copy-errors.txt";

    // 指定工作目录
    shExecInfo.lpDirectory = NULL;

    // 设置窗口显示方式
    shExecInfo.nShow = SW_HIDE;

    // 执行命令
    if (ShellExecuteExW(&shExecInfo) == FALSE) {
        // 错误处理
        DWORD dwError = GetLastError();
        if (dwError == ERROR_CANCELLED) {
            // 用户拒绝UAC提示
            printf("User refused the UAC prompt.\n");
        } else {
            // 其他错误
            printf("Error: %lu\n", dwError);
        }
        return 1;
    }

    return 0;
}

Eiffel单元测试代码

test_admin_level_execution
   -- OS_COMMAND_TEST_SET.test_admin_level_execution
   note
      testing: "[
         covers/{EL_WINDOWS_ADMIN_SHELL_COMMAND}.execute,
         covers/{EL_WINDOWS_ADMIN_SHELL_COMMAND}.set_command_and_parameters
      ]"
      status: "[
         Commented out in `make_named'. Failing on Windows
      ]"
   local
      command: EL_OS_COMMAND_I; destination_path: FILE_PATH
   do
      if Executable.Is_work_bench then
         create {EL_COPY_FILE_COMMAND_IMP} command.make ("data/txt/file.txt", Directory.applications)
         command.administrator.enable
         command.execute
         assert ("successful", not command.has_error)
         destination_path := Directory.applications + "file.txt"
         if destination_path.exists then
            create {EL_DELETE_FILE_COMMAND_IMP} command.make (destination_path)
            command.administrator.enable
            command.execute
            assert ("File deleted", not destination_path.exists)
         else
            failed ("File exists")
         end
      end
   end

内容的提问来源于stack exchange,提问作者Finnian Reilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:06:27