Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
InvokeWSManAction.cs341 linesDownload Raw Back to Microsoft.WSMan.Management
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    /// <summary>20    /// Executes action on a target object specified by RESOURCE_URI, where21    /// parameters are specified by key value pairs.22    /// eg., Call StartService method on the spooler service23    /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service24    /// -SelectorSet {Name=Spooler}25    /// </summary>26    [Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096843")]27    [OutputType(typeof(XmlElement))]28    public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable29    {30        /// <summary>31        /// The following is the definition of the input parameter "Action".32        /// Indicates the method which needs to be executed on the management object33        /// specified by the ResourceURI and selectors.34        /// </summary>35        [Parameter(Mandatory = true,36                  Position = 1)]37        [ValidateNotNullOrEmpty]38        public string Action39        {40            get { return action; }41 42            set { action = value; }43        }44 45        private string action;46 47        /// <summary>48        /// The following is the definition of the input parameter "ApplicationName".49        /// ApplicationName identifies the remote endpoint.50        /// </summary>51        [Parameter(ParameterSetName = "ComputerName")]52        [ValidateNotNullOrEmpty]53        public string ApplicationName54        {55            get { return applicationname; }56 57            set { applicationname = value; }58        }59 60        private string applicationname = null;61 62        /// <summary>63        /// The following is the definition of the input parameter "ComputerName".64        /// Executes the management operation on the specified computer(s). The default65        /// is the local computer. Type the fully qualified domain name, NETBIOS name or66        /// IP address to indicate the remote host(s)67        /// </summary>68        [Parameter(ParameterSetName = "ComputerName")]69        [Alias("cn")]70        public string ComputerName71        {72            get73            {74                return computername;75            }76 77            set78            {79                computername = value;80                if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))81                {82                    computername = "localhost";83                }84            }85        }86 87        private string computername = null;88 89        /// <summary>90        /// The following is the definition of the input parameter "ConnectionURI".91        /// Specifies the transport, server, port, and ApplicationName of the new92        /// runspace. The format of this string is:93        /// transport://server:port/ApplicationName.94        /// </summary>95        [Parameter(ParameterSetName = "URI")]96        [ValidateNotNullOrEmpty]97        [Alias("CURI", "CU")]98        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]99        public Uri ConnectionURI100        {101            get { return connectionuri; }102 103            set { connectionuri = value; }104        }105 106        private Uri connectionuri;107 108        /// <summary>109        /// The following is the definition of the input parameter "FilePath".110        /// Updates the management resource specified by the ResourceURI and SelectorSet111        /// via this input file.112        /// </summary>113        [Parameter]114        [Alias("Path")]115        [ValidateNotNullOrEmpty]116        public string FilePath117        {118            get { return filepath; }119 120            set { filepath = value; }121        }122 123        private string filepath;124 125        /// <summary>126        /// The following is the definition of the input parameter "OptionSet".127        /// OptionSet is a hashtable and is used to pass a set of switches to the128        /// service to modify or refine the nature of the request.129        /// </summary>130        [Parameter(ValueFromPipeline = true,131                   ValueFromPipelineByPropertyName = true)]132        [ValidateNotNullOrEmpty]133        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]134        [Alias("os")]135        public Hashtable OptionSet136        {137            get { return optionset; }138 139            set { optionset = value; }140        }141 142        private Hashtable optionset;143 144        /// <summary>145        /// The following is the definition of the input parameter "Port".146        /// Specifies the port to be used when connecting to the ws management service.147        /// </summary>148        [Parameter(ParameterSetName = "ComputerName")]149        [ValidateNotNullOrEmpty]150        [ValidateRange(1, int.MaxValue)]151        public int Port152        {153            get { return port; }154 155            set { port = value; }156        }157 158        private int port = 0;159 160        /// <summary>161        /// The following is the definition of the input parameter "SelectorSet".162        /// SelectorSet is a hash table which helps in identify an instance of the163        /// management resource if there are more than 1 instance of the resource164        /// class.165        /// </summary>166        [Parameter(Position = 2,167                   ValueFromPipeline = true,168                   ValueFromPipelineByPropertyName = true)]169        [ValidateNotNullOrEmpty]170        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]171        public Hashtable SelectorSet172        {173            get { return selectorset; }174 175            set { selectorset = value; }176        }177 178        private Hashtable selectorset;179 180        /// <summary>181        /// The following is the definition of the input parameter "SessionOption".182        /// Defines a set of extended options for the WSMan session. This hashtable can183        /// be created using New-WSManSessionOption.184        /// </summary>185        [Parameter]186        [ValidateNotNullOrEmpty]187        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]188        [Alias("so")]189        public SessionOption SessionOption190        {191            get { return sessionoption; }192 193            set { sessionoption = value; }194        }195 196        private SessionOption sessionoption;197 198        /// <summary>199        /// The following is the definition of the input parameter "UseSSL".200        /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to201        /// the remote computer. If SSL is not available on the port specified by the202        /// Port parameter, the command fails.203        /// </summary>204        [Parameter(ParameterSetName = "ComputerName")]205        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]206        public SwitchParameter UseSSL207        {208            get { return usessl; }209 210            set { usessl = value; }211        }212 213        private SwitchParameter usessl;214 215        /// <summary>216        /// The following is the definition of the input parameter "ValueSet".217        /// ValueSet is a hahs table which helps to modify resource represented by the218        /// ResourceURI and SelectorSet.219        /// </summary>220        [Parameter]221        [ValidateNotNullOrEmpty]222        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]223        public Hashtable ValueSet224        {225            get { return valueset; }226 227            set { valueset = value; }228        }229 230        private Hashtable valueset;231 232        /// <summary>233        /// The following is the definition of the input parameter "ResourceURI".234        /// URI of the resource class/instance representation.235        /// </summary>236        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true,237                   ValueFromPipelineByPropertyName = true)]238        [ValidateNotNullOrEmpty]239        [Alias("ruri")]240        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]241        public Uri ResourceURI242        {243            get { return resourceuri; }244 245            set { resourceuri = value; }246        }247 248        private Uri resourceuri;249 250        private WSManHelper helper;251        private readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass();252        private IWSManSession m_session = null;253        private string connectionStr = string.Empty;254 255        /// <summary>256        /// BeginProcessing method.257        /// </summary>258        protected override void BeginProcessing()259        {260            helper = new WSManHelper(this);261 262            helper.WSManOp = "invoke";263 264            // create the connection string265            connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname);266        }267 268        /// <summary>269        /// ProcessRecord method.270        /// </summary>271        protected override void ProcessRecord()272        {273            try274            {275                // create the resourcelocator object276                IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri);277 278                // create the session object279                m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);280 281                string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action);282                string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session);283                string resultXml = m_session.Invoke(action, m_resource, input, 0);284 285                XmlDocument xmldoc = new XmlDocument();286                xmldoc.LoadXml(resultXml);287                WriteObject(xmldoc.DocumentElement);288            }289            finally290            {291                if (!string.IsNullOrEmpty(m_wsmanObject.Error))292                {293                    helper.AssertError(m_wsmanObject.Error, true, resourceuri);294                }295 296                if (!string.IsNullOrEmpty(m_session.Error))297                {298                    helper.AssertError(m_session.Error, true, resourceuri);299                }300 301                if (m_session != null)302                    Dispose(m_session);303            }304        }305 306        #region IDisposable Members307 308        /// <summary>309        /// Public dispose method.310        /// </summary>311        public312        void313        Dispose()314        {315            // CleanUp();316            GC.SuppressFinalize(this);317        }318        /// <summary>319        /// Public dispose method.320        /// </summary>321        public322        void323        Dispose(IWSManSession sessionObject)324        {325            sessionObject = null;326            this.Dispose();327        }328 329        #endregion IDisposable Members330 331        /// <summary>332        /// BeginProcessing method.333        /// </summary>334        protected override void EndProcessing()335        {336            //  WSManHelper helper = new WSManHelper();337            helper.CleanUp();338        }339    }340}341