2

I use this code C++ builder to execute batch file in remote computer

String PsExec = ExtractFilePath(Application->ExeName) + "PSTools\\PsExec.exe";
String lcParam = " \\"+gl_HostName+" cmd /c  "+TDirectory::GetParent(rootPath)+"\\...\\File1.bat "+IntToStr(8988) ;

SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = PsExec.c_str();
ShExecInfo.lpParameters = lcParam.c_str();
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_NORMAL;//SW_HIDE ;
ShExecInfo.hInstApp = NULL;

ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
bool res = ShellExecuteEx(&ShExecInfo); // Call to function
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);

It doesn't work!

But, when I run a cmd into console :

\PSTools> PsExec.exe \\x.y.z.w \\x.y.z.w\.....\File1.bat 8988

It works correctly and runs this batch in a remote computer!

What is wrong in my sample code?

1 Answers1

1

As Alex said, you are not providing enough slashes in your hostname. You are only providing 1 escaped slash, but you need 2 instead:

String lcParam = _D(" \\\\") + gl_HostName + _D(" cmd /c ") + TDirectory::GetParent(rootPath) + _D("\\...\\File1.bat ") + IntToStr(8988);

That being said, you should also be using CreateProcess() instead of ShellExecuteEx() to run an .exe file:

String PsExec = ExtractFilePath(Application->ExeName) + _D("PSTools\\PsExec.exe");
String lcParam = _D(" \\\\") + gl_HostName + _D(" cmd /c ") + TDirectory::GetParent(rootPath) + _D("\\...\\File1.bat ") + IntToStr(8988);
String CmdLine = AnsiQuotedStr(PsExec, _D('\"')) + _D(" ") + lcParam;

STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_NORMAL;

PROCESS_INFORMATION pi = {0};

if (CreateProcessW(NULL, CmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770