protected void Page_Load(object sender, EventArgs e) { InvokeSystemPS("query user /server:192.168.1.222"); //test(); } public static void InvokeSystemPS(string cmd) { List<string> ps = new List<string>(); ps.Add("Set-ExecutionPolicy RemoteSigned"); ps.Add("Set-ExecutionPolicy -ExecutionPolicy Unrestricted"); ps.Add("& " + cmd); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); foreach (var scr in ps) { pipeline.Commands.AddScript(scr); } Collection<PSObject> psObjects= pipeline.Invoke();//Execute the ps script PSObject[] abc = psObjects.ToArray(); string [] ss=abc[1].BaseObject.ToString().Split(' '); runspace.Close(); }
public string GetFreeTime(string IPAddress) { string cmd = "query user /server:" + IPAddress; List<string> ps = new List<string>(); ps.Add("Set-ExecutionPolicy RemoteSigned"); ps.Add("Set-ExecutionPolicy -ExecutionPolicy Unrestricted"); ps.Add("& " + cmd); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); foreach (var scr in ps) { pipeline.Commands.AddScript(scr); } Collection<PSObject> psObjects = pipeline.Invoke();//Execute the ps script runspace.Close(); string[] arr = psObjects[1].BaseObject.ToString().Split(' '); StringBuilder str = new StringBuilder(); for (int i = 0; i < arr.Length; i++) { if (arr[i] != "") { str.Append(arr[i] + ","); } } string[] tmp = str.ToString().Split(','); return tmp[4]; }
在win7 中会报错,需要做如下修改
Solution
On the machine that you cannot message to:
Use regedit to navigate to: HKLMSYSTEMCurrentControlSetControlTerminal Server
Then change the following value:
Name : AllowRemoteRPC
Type : REG_DWORD
Value : 1
Reboot. Now it should work.
无法将“query”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后重试。
出现这个错误是这个方法的需要在IIS中运行,不能再本地调试,而且应用程序池的账号需要在被抓去机器的管理员组中(最好)