问题
I have a dynamically generated batch file that I push out to a remote PC and then execute it using PsExec. The issue I am facing is that as soon as that line is called, the PowerShell script moves on and doesn't wait for it to finish. Here is what I have:
psexec -accepteula \\$Server -u Username -p Password-d -i 2 cmd /c C:\Call.bat
Call.bat
calls an executable on the remote machine with a few parameters passed in. This file is dynamically generated and is different every time, but can look like this:
cd C:\20161212-175524
C:\20161212-175524\RE.exe /pa1 /pa2 /pa3 /pa4 /pa5 /pa6 /pa7 /pa8 /pa9 /pa10
The batch file needs to run as an interactive script as that specific user, but I need it to at least wait for the spawned process to finish. I have tried adding 2>&1
and | Out-Null
Ideally, I would like to retrieve the exit code returned by the spawned process, but that may be too much.
回答1:
Previously i have used something like this to achieve the waiting you are after:
Start-Process -FilePath 'c:\tools\PSexec.exe' -ArgumentList "-u MyUserName -p $password \\$Computer .\Run.bat $Var >> C:\Temp\$Computer.log" -Wait -Passthru -WindowStyle Hidden
What you need to focus on the line above is by using the Start-Process
cmdlet we can use the -Wait
parameter.
Hope this answers your question
回答2:
private static string ExecuteAndGetOutput(string command)
{
string resultFile = Path.GetTempFileName();
string commandFile = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(resultFile) + ".bat");
command += @" >""{0}""";
command = string.Format(command, resultFile);
File.WriteAllText(commandFile, command);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = commandFile;
psi.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(psi);
p.WaitForExit();
int exitCode = p.ExitCode;
return File.ReadAllText(resultFile);
}
来源:https://stackoverflow.com/questions/41111450/wait-for-psexec-calling-cmd-c-to-finish-in-powershell