1 public static void ExecuteRemoteCommand(string remoteComputer, string userName, string password, string command)
2 {
3 WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
4 connectionInfo.ComputerName = remoteComputer;
5 connectionInfo.Credential = new PSCredential(userName, ConvertToSecureString(password));
6
7 using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
8 {
9 runspace.Open();
10
11 using (PowerShell ps = PowerShell.Create())
12 {
13 ps.Runspace = runspace;
14 ps.AddScript(command);
15
16 Collection<PSObject> results = ps.Invoke();
17
18 foreach (var result in results)
19 {
20 Console.WriteLine(result);
21 }
22 }
23 runspace.Close();
24 }
25 }
public static void StopRemoteProcessByName(string remoteComputer, string userName, string password, string processName)
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = remoteComputer;
connectionInfo.Credential = new PSCredential(userName, ConvertToSecureString(password));
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
// 获取进程ID
ps.Runspace = runspace;
ps.AddScript($"$proc = Get-Process -Name {processName}; if ($proc) {{$proc.Id}}");
// 执行并获取进程ID
var results = ps.Invoke();
if (ps.HadErrors)
{
Console.WriteLine("Error retrieving process ID");
return;
}
// 如果找到了进程,关闭它
if (results.Count > 0)
{
int processId = (int)results[0].BaseObject;
ps.Commands.Clear();
ps.AddScript($"Stop-Process -Id {processId} -Force");
ps.Invoke();
if (ps.HadErrors)
{
Console.WriteLine("Error stopping process");
}
else
{
Console.WriteLine($"Process {processName} with ID {processId} stopped successfully.");
}
}
else
{
Console.WriteLine("No such process found.");
}
}
runspace.Close();
}
}
public static void StartRemoteProcess(string remoteComputer, string userName, string password, string processName)
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = remoteComputer;
connectionInfo.Credential = new PSCredential(userName, ConvertToSecureString(password));
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript($"$process = Start-Process {processName} -PassThru; $process.Id");
var results = ps.Invoke();
if (ps.HadErrors)
{
Console.WriteLine("Error starting process");
}
else if (results.Count > 0)
{
Console.WriteLine($"Process started successfully. Process ID: {results[0]}");
}
}
runspace.Close();
}
}
如果以上代码还不能满足你的好奇心,想要我本地测试的源码demo,可以在我的公众号【Dotnet Dancer】后台回复:【进程操控】 即可获取我的本地demo源码自行调试和把玩。
【备注】最近园子里面图片容易挂,如果挂掉了,可以查阅我发表其他地方的文章:https://mp.weixin.qq.com/s/-r9QQkvtBrTrReL5AQDNGQ