MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#if UNIX5 6using System;7using System.Diagnostics;8using System.IO;9using System.Management.Automation;10using System.Management.Automation.Internal;11using System.Runtime.InteropServices;12 13#nullable enable14 15namespace Microsoft.PowerShell.Commands16{17#region Restart-Computer18 19 /// <summary>20 /// Cmdlet to restart computer.21 /// </summary>22 [Cmdlet(VerbsLifecycle.Restart, "Computer", SupportsShouldProcess = true,23 HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097060", RemotingCapability = RemotingCapability.SupportedByCommand)]24 public sealed class RestartComputerCommand : CommandLineCmdletBase25 {26 // TODO: Support remote computers?27 28#region "Overrides"29 30 /// <summary>31 /// BeginProcessing.32 /// </summary>33 protected override void BeginProcessing()34 {35 if (InternalTestHooks.TestStopComputer)36 {37 var retVal = InternalTestHooks.TestStopComputerResults;38 if (retVal != 0)39 {40 string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal);41 ErrorRecord error = new ErrorRecord(42 new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost");43 WriteError(error);44 }45 return;46 }47 48 RunShutdown("-r now");49 }50#endregion "Overrides"51 }52#endregion Restart-Computer53 54#region Stop-Computer55 56 /// <summary>57 /// Cmdlet to stop computer.58 /// </summary>59 [Cmdlet(VerbsLifecycle.Stop, "Computer", SupportsShouldProcess = true,60 HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097151", RemotingCapability = RemotingCapability.SupportedByCommand)]61 public sealed class StopComputerCommand : CommandLineCmdletBase62 {63 // TODO: Support remote computers?64 65#region "Overrides"66 67 /// <summary>68 /// BeginProcessing.69 /// </summary>70 protected override void BeginProcessing()71 {72 var args = "-P now";73 if (Platform.IsMacOS)74 {75 args = "now";76 }77 if (InternalTestHooks.TestStopComputer)78 {79 var retVal = InternalTestHooks.TestStopComputerResults;80 if (retVal != 0)81 {82 string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal);83 ErrorRecord error = new ErrorRecord(84 new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost");85 WriteError(error);86 }87 return;88 }89 90 RunShutdown(args);91 }92#endregion "Overrides"93 }94 95 /// <summary>96 /// A base class for cmdlets that can run shell commands.97 /// </summary>98 public class CommandLineCmdletBase : PSCmdlet, IDisposable99 {100#region Private Members101 private Process? _process = null;102#endregion103 104#region "IDisposable Members"105 106 /// <summary>107 /// Releases all resources used by the <see cref="CommandLineCmdletBase"/>.108 /// </summary>109 public void Dispose()110 {111 Dispose(true);112 GC.SuppressFinalize(this);113 }114 115 /// <summary>116 /// Releases the unmanaged resources used by the <see cref="CommandLineCmdletBase"/>117 /// and optionally releases the managed resources.118 /// </summary>119 /// <param name="disposing">120 /// <see langword="true"/> to release both managed and unmanaged resources;121 /// <see langword="false"/> to release only unmanaged resources.122 /// </param>123 protected virtual void Dispose(bool disposing)124 {125 if (disposing)126 {127 _process?.Dispose();128 }129 }130 131#endregion "IDisposable Members"132 133#region "Overrides"134 /// <summary>135 /// To implement ^C.136 /// </summary>137 protected override void StopProcessing()138 {139 if (_process == null) {140 return;141 }142 143 try {144 if (!_process.HasExited) {145 _process.Kill();146 }147 WriteObject(_process.ExitCode);148 }149 catch (InvalidOperationException) {}150 catch (NotSupportedException) {}151 }152#endregion "Overrides"153 154#region "Internals"155 156 private static string? shutdownPath;157 158 /// <summary>159 /// Run shutdown command.160 /// </summary>161 protected void RunShutdown(string args)162 {163 if (shutdownPath is null)164 {165 CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo(166 "shutdown", CommandTypes.Application,167 SearchResolutionOptions.None, CommandOrigin.Internal, this.Context);168 169 if (cmdinfo is not null)170 {171 shutdownPath = cmdinfo.Definition;172 }173 else174 {175 ErrorRecord error = new ErrorRecord(176 new InvalidOperationException(ComputerResources.ShutdownCommandNotFound), "CommandNotFound", ErrorCategory.ObjectNotFound, targetObject: null);177 ThrowTerminatingError(error);178 }179 }180 181 _process = new Process()182 {183 StartInfo = new ProcessStartInfo184 {185 FileName = shutdownPath,186 Arguments = string.Empty,187 RedirectStandardOutput = false,188 RedirectStandardError = true,189 UseShellExecute = false,190 CreateNoWindow = true,191 }192 };193 _process.Start();194 _process.WaitForExit();195 if (_process.ExitCode != 0)196 {197 string stderr = _process.StandardError.ReadToEnd();198 ErrorRecord error = new ErrorRecord(199 new InvalidOperationException(stderr), "CommandFailed", ErrorCategory.OperationStopped, null);200 ThrowTerminatingError(error);201 }202 }203#endregion204 }205#endregion206}207#endif208 