我正在尝试做什么
我似乎无法弄清楚如何获取外卡使用的驱动器号。
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"\\Server\PStools\PSExec.exe";
p.StartInfo.Arguments = @"\\ComputerName -e -s cmd.exe ""/C Net USE * \\Server\Share /Persistent:NO""";
p.Start();
答案 0 :(得分:1)
带有通配符的net use
命令将从Z到A中选择序列中的第一个可用驱动器号。它会在控制台输出中报告所选的驱动器号,如下所示:
C:\>net use * \\server\share Drive Z: is now connected to \\server\share. The command completed successfully. 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
添加到输出的各行。