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
添加在远程 PC 上使用而不是本地执行命令的方法应该不会太难cmd.exe
。类似于以下内容:
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
.