将%APPDATA%与CreateProcessW一起使用

时间:2018-12-12 10:14:43

标签: c++ windows winapi createprocess

我有一个简单的代码,使用system()将变量为%APPDATA%的文件下载到AppData,我想使用CreateProcessW而不是system,但是由于某些原因,当我在CreatProcess下使用相同的命令时,它会寻找“工作目录” \%APPDATA%而不是实际的AppData目录,并引发异常。

System()工作代码:

SELECT Enterprise_ID, Date, Attendance 
FROM attendanceData natural 
    join (  SELECT Enterprise_ID 
            FROM attendanceData 
            group BY Enterprise_ID
        ) 
pivot (max(P) for Attendance in ('P' as P, 'WO' as WO)

CreateProcessW代码:

system("powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%APPDATA%\\putty.exe'");

例外:

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%?

1 个答案:

答案 0 :(得分:1)

您可以使用_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)