我有一个简单的代码,它使用 system() 通过变量 %APPDATA% 将文件下载到 AppData,我想使用 CreateProcessW 而不是系统,但出于某种原因,当我在 CreatProcess 下使用相同的命令时,它会查找"Working Dir"\%APPDATA% 而不是实际的 AppData 目录,并引发异常。
System() 工作代码:
system("powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%APPDATA%\\putty.exe'");
CreateProcessW代码:
wchar_t cmdArgs[] = L"powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%APPDATA%\\putty.exe'";
CreateProcessW(NULL, cmdArgs, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)
异常:
Invoke-WebRequest : Could not find a part of the path 'G:\Projects\C++\PS_Tries\PS_Tries\%APPDATA%\putty.exe'. At line:1 char:1 + Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/put ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], DirectoryNotFoundException + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
如何让它像 system() 那样扩展 %APPDATA%?
最佳答案
您可以使用 _wdupenv_s获取 appdata 路径的函数,然后将其与您的参数 concatenate
wchar_t *w_app_data_path;
size_t sz = 0;
errno_t err = _wdupenv_s(&w_app_data_path, &sz, L"APPDATA");
wchar_t cmdArgs[2048]{ 0 };
wsprintfW(cmdArgs, L"powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%s\\putty.exe'", w_app_data_path);
free(w_app_data_path);
CreateProcessW(NULL, cmdArgs, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)
关于c++ - 将 %APPDATA% 与 CreateProcessW 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740716/