MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System;5using System.Collections;6using System.Collections.Generic;7using System.ComponentModel;8using System.Diagnostics.CodeAnalysis;9using System.IO;10using System.Management.Automation;11using System.Management.Automation.Provider;12using System.Reflection;13using System.Runtime.CompilerServices;14using System.Runtime.InteropServices;15using System.Xml;16 17namespace Microsoft.WSMan.Management18{19 #region Set-WsManQuickConfig20 21 //22 23 /// <summary>24 /// Performs configuration actions to enable the local machine for remote25 /// management. Steps include:26 /// 1. Check if WinRM service is running. If not start the WinRM service27 /// 2. Set the WinRM service type to auto start28 /// 3. Create a listener to accept request on any IP address. By default29 /// transport is http30 /// 4. Enable firewall exception for WS-Management traffic.31 /// </summary>32 [Cmdlet(VerbsCommon.Set, "WSManQuickConfig", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097112")]33 [OutputType(typeof(string))]34 public class SetWSManQuickConfigCommand : PSCmdlet, IDisposable35 {36 /// <summary>37 /// The following is the definition of the input parameter "UseSSL".38 /// Indicates a https listener to be created. If this switch is not specified39 /// then by default a http listener will be created.40 /// </summary>41 [Parameter]42 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]43 public SwitchParameter UseSSL44 {45 get { return usessl; }46 47 set { usessl = value; }48 }49 50 private SwitchParameter usessl;51 52 // helper variable53 private WSManHelper helper;54 55 /// <summary>56 /// Property that sets force parameter. This will allow57 /// configuring WinRM without prompting the user.58 /// </summary>59 [Parameter]60 public SwitchParameter Force61 {62 get { return force; }63 64 set { force = value; }65 }66 67 private bool force = false;68 69 /// <summary>70 /// Property that will allow configuring WinRM with Public profile exception enabled.71 /// </summary>72 [Parameter]73 public SwitchParameter SkipNetworkProfileCheck74 {75 get { return skipNetworkProfileCheck; }76 77 set { skipNetworkProfileCheck = value; }78 }79 80 private bool skipNetworkProfileCheck = false;81 82 /// <summary>83 /// BeginProcessing method.84 /// </summary>85 protected override void BeginProcessing()86 {87 // If not running elevated, then throw an "elevation required" error message.88 WSManHelper.ThrowIfNotAdministrator();89 helper = new WSManHelper(this);90 string query = helper.GetResourceMsgFromResourcetext("QuickConfigContinueQuery");91 string caption = helper.GetResourceMsgFromResourcetext("QuickConfigContinueCaption");92 if (!force && !ShouldContinue(query, caption))93 {94 return;95 }96 97 QuickConfigRemoting(true);98 QuickConfigRemoting(false);99 }100 101 #region private102 103 private void QuickConfigRemoting(bool serviceonly)104 {105 IWSManSession m_SessionObj = null;106 try107 {108 string transport;109 IWSManEx wsmanObject = (IWSManEx)new WSManClass();110 m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);111 string xpathEnabled = string.Empty;112 string xpathText = string.Empty;113 string xpathUpdate = string.Empty;114 string analysisInputXml = string.Empty;115 string action = string.Empty;116 string xpathStatus = string.Empty;117 string xpathResult = string.Empty;118 119 if (!usessl)120 {121 transport = "http";122 }123 else124 {125 transport = "https";126 }127 128 if (serviceonly)129 {130 analysisInputXml = @"<AnalyzeService_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""></AnalyzeService_INPUT>";131 action = "AnalyzeService";132 }133 else134 {135 string openAllProfiles = skipNetworkProfileCheck ? "<Force/>" : string.Empty;136 analysisInputXml = @"<Analyze_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""><Transport>" + transport + "</Transport>" + openAllProfiles + "</Analyze_INPUT>";137 action = "Analyze";138 }139 140 string analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0);141 XmlDocument resultopxml = new XmlDocument();142 resultopxml.LoadXml(analysisOutputXml);143 144 if (serviceonly)145 {146 xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled";147 xpathText = "/cfg:AnalyzeService_OUTPUT/cfg:Results";148 xpathUpdate = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT";149 }150 else151 {152 xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled";153 xpathText = "/cfg:Analyze_OUTPUT/cfg:Results";154 xpathUpdate = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT";155 }156 157 XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);158 nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service");159 string enabled = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText;160 XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source");161 string source = null;162 if (sourceAttribute != null)163 {164 source = sourceAttribute.Value;165 }166 167 string rxml = string.Empty;168 if (enabled.Equals("true"))169 {170 string Err_Msg = string.Empty;171 if (serviceonly)172 {173 Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message");174 }175 else176 {177 Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message");178 }179 // ArgumentException e = new ArgumentException(Err_Msg);180 // ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);181 // WriteError(er);182 WriteObject(Err_Msg);183 return;184 }185 186 if (!enabled.Equals("false"))187 {188 ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage"));189 ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);190 WriteError(er);191 return;192 }193 194 string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText;195 if (source != null && source.Equals("GPO"))196 {197 string Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage");198 Info_Msg += " " + resultAction;199 ArgumentException e = new ArgumentException(Info_Msg);200 WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null));201 return;202 }203 204 string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml;205 if (resultAction.Equals(string.Empty) || inputXml.Equals(string.Empty))206 {207 ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage"));208 ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);209 WriteError(er);210 return;211 }212 213 if (serviceonly)214 {215 action = "EnableService";216 }217 else218 {219 action = "EnableRemoting";220 }221 222 rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0);223 XmlDocument finalxml = new XmlDocument();224 finalxml.LoadXml(rxml);225 226 if (serviceonly)227 {228 xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status";229 xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results";230 }231 else232 {233 xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status";234 xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results";235 }236 237 if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.Equals("succeeded"))238 {239 if (serviceonly)240 {241 WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message"));242 }243 else244 {245 WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message"));246 }247 248 WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText);249 }250 else251 {252 helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null);253 }254 }255 finally256 {257 if (!string.IsNullOrEmpty(m_SessionObj.Error))258 {259 helper.AssertError(m_SessionObj.Error, true, null);260 }261 262 if (m_SessionObj != null)263 Dispose(m_SessionObj);264 }265 }266 #endregion private267 268 #region IDisposable Members269 270 /// <summary>271 /// Public dispose method.272 /// </summary>273 public274 void275 Dispose()276 {277 // CleanUp();278 GC.SuppressFinalize(this);279 }280 /// <summary>281 /// Public dispose method.282 /// </summary>283 public284 void285 Dispose(IWSManSession sessionObject)286 {287 sessionObject = null;288 this.Dispose();289 }290 291 #endregion IDisposable Members292 }293 #endregion Set-WsManQuickConfig294}295 