本帖最后由 apull 于 2022-12-13 20:42 编辑
可以把执行内容写到ps1文件里,用-File t.ps1的参数执行。
[C#] 纯文本查看 复制代码
StringBuilder script = new StringBuilder();
script.AppendLine(string.Format("$Processes = Get-WmiObject -Class Win32_Process -ComputerName {0} -Filter 'name = \"{1}\"';", "DSK0550", "LabelPrinting.exe"));
script.AppendLine("foreach ($process in $Processes) {");
script.AppendLine("$returnval = $process.terminate()");
script.AppendLine("if($returnval.returnvalue -eq 0) {");
script.AppendLine("write-host \"Closed\"");
script.AppendLine("} else {");
script.AppendLine("write-host \"Failed\"");
script.AppendLine("}");
script.AppendLine("}");
string file = Path.GetTempPath() + "t.ps1";
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(script.ToString());
}
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = @"powershell.exe";
//processInfo.Arguments = script.ToString();
processInfo.Arguments = string.Format("-File {0}", file);
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = true;
//start powershell process using process start info
Process process = new Process();
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());
File.Delete(file);
|