带有通配符的net use 命令将选择从 Z 到 A 序列中的第一个可用驱动器号。它在控制台输出中报告所选驱动器号,如下所示:
C:\>网络使用 * \\server\share
驱动器 Z:现在已连接到 \\server\share。
命令成功完成。
C:\>_
所以您需要捕获PSExec 命令的输出并对其进行解析以找到分配的驱动器号。
我还没有用PSExec 尝试过这个,但这是我用来通过cmd.exe 捕获命令输出的代码:
static class CommandRunner
{
static StringBuilder cmdOutput = new StringBuilder();
public static string Run(string command)
{
if (string.IsNullOrWhiteSpace(command))
return null;
using (var proc = new Process())
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/c " + command;
proc.StartInfo.LoadUserProfile = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += proc_DataReceived;
proc.ErrorDataReceived += proc_DataReceived;
try
{
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
catch (Exception e)
{
cmdOutput.AppendLine("***Exception during command exection***");
cmdOutput.AppendLine(e.Message);
cmdOutput.AppendLine("*** ***");
}
}
return cmdOutput.ToString();
}
static void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
cmdOutput.AppendLine(e.Data);
}
}
要在本地机器上获取命令的输出,请像这样调用它:
string output = CommandRunner.Run("net use");
添加一个使用PSExec 而不是本地cmd.exe 在远程PC 上执行命令的方法应该不会太难。类似于以下内容:
public static string Remote(string target, string command, string peFlags = "-e -s")
{
if (string.IsNullOrWhiteSpace(command))
return null;
using (var proc = new Process())
{
proc.StartInfo.FileName = @"C:\PSTools\PSExec.exe";
proc.StartInfo.Arguments = string.Format(@"\\{0}{1} cmd.exe ""/c {2}""", target, peFlags == null ? "" : " " + peFlags, command);
proc.StartInfo.LoadUserProfile = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += proc_DataReceived;
try
{
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
catch
{ }
}
return cmdOutput.ToString();
}
注意:我在这里删除了stderr 重定向,因为我只想要远程程序的输出,而不是PSExec 添加到输出的各种行。