|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +#if UNIX |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Diagnostics; |
| 8 | +using System.Management.Automation; |
| 9 | +using System.Runtime.InteropServices; |
| 10 | + |
| 11 | +namespace Microsoft.PowerShell.Commands |
| 12 | +{ |
| 13 | + #region Stop-Computer |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// Cmdlet to stop computer. |
| 17 | + /// </summary> |
| 18 | + [Cmdlet(VerbsLifecycle.Stop, "Computer", SupportsShouldProcess = true, |
| 19 | + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135263", RemotingCapability = RemotingCapability.SupportedByCommand)] |
| 20 | + public sealed class StopComputerCommand : PSCmdlet, IDisposable |
| 21 | + { |
| 22 | + #region Private Members |
| 23 | + |
| 24 | + private Process _process = null; |
| 25 | + |
| 26 | + #endregion |
| 27 | + |
| 28 | + // TODO: Support remote computers? |
| 29 | + |
| 30 | + #region "IDisposable Members" |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Dispose Method. |
| 34 | + /// </summary> |
| 35 | + public void Dispose() |
| 36 | + { |
| 37 | + _process.Dispose(); |
| 38 | + } |
| 39 | + |
| 40 | + #endregion "IDisposable Members" |
| 41 | + |
| 42 | + #region "Overrides" |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// BeginProcessing. |
| 46 | + /// </summary> |
| 47 | + protected override void BeginProcessing() |
| 48 | + { |
| 49 | + doShutdown(); |
| 50 | + } |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// To implement ^C. |
| 54 | + /// </summary> |
| 55 | + protected override void StopProcessing() |
| 56 | + { |
| 57 | + if (_process == null) { |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + try { |
| 62 | + if (!_process.HasExited) { |
| 63 | + _process.Kill(); |
| 64 | + } |
| 65 | + WriteObject(_process.ExitCode); |
| 66 | + } |
| 67 | + catch (InvalidOperationException) {} |
| 68 | + catch (NotSupportedException) {} |
| 69 | + } |
| 70 | + |
| 71 | + #endregion "Overrides" |
| 72 | + |
| 73 | + #region "Internals" |
| 74 | + |
| 75 | + private void doShutdown() { |
| 76 | + String cmd = ""; |
| 77 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) |
| 78 | + { |
| 79 | + cmd = "-P now"; |
| 80 | + } |
| 81 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| 82 | + { |
| 83 | + cmd = "now"; |
| 84 | + } |
| 85 | + |
| 86 | + _process = new Process() |
| 87 | + { |
| 88 | + StartInfo = new ProcessStartInfo |
| 89 | + { |
| 90 | + FileName = "/sbin/shutdown", |
| 91 | + Arguments = cmd, |
| 92 | + RedirectStandardOutput = false, |
| 93 | + UseShellExecute = false, |
| 94 | + CreateNoWindow = true, |
| 95 | + } |
| 96 | + }; |
| 97 | + _process.Start(); |
| 98 | + } |
| 99 | + #endregion |
| 100 | + } |
| 101 | + #endregion |
| 102 | +} |
| 103 | +#endif |
0 commit comments