Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
WSManConnections.cs388 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.Management.Automation.Runspaces;13using System.Reflection;14using System.Runtime.CompilerServices;15using System.Runtime.InteropServices;16using System.Xml;17 18using Dbg = System.Management.Automation;19 20namespace Microsoft.WSMan.Management21{22    #region Base class for cmdlets taking credential, authentication, certificatethumbprint23 24    /// <summary>25    /// Common base class for all WSMan cmdlets that26    /// take Authentication, CertificateThumbprint and Credential parameters.27    /// </summary>28    public class AuthenticatingWSManCommand : PSCmdlet29    {30        /// <summary>31        /// The following is the definition of the input parameter "Credential".32        /// Specifies a user account that has permission to perform this action. The33        /// default is the current user.34        /// </summary>35        [Parameter(ValueFromPipelineByPropertyName = true)]36        [ValidateNotNullOrEmpty]37        [Credential]38        [Alias("cred", "c")]39        public virtual PSCredential Credential40        {41            get42            {43                return credential;44            }45 46            set47            {48                credential = value;49                ValidateSpecifiedAuthentication();50            }51        }52 53        private PSCredential credential;54 55        /// <summary>56        /// The following is the definition of the input parameter "Authentication".57        /// This parameter takes a set of authentication methods the user can select58        /// from. The available method are an enum called Authentication in the59        /// System.Management.Automation.Runspaces namespace. The available options60        /// should be as follows:61        /// - Default : Use the default authentication (ad defined by the underlying62        /// protocol) for establishing a remote connection.63        /// - Negotiate64        /// - Kerberos65        /// - Basic:  Use basic authentication for establishing a remote connection.66        /// -CredSSP: Use CredSSP authentication for establishing a remote connection67        /// which will enable the user to perform credential delegation. (i.e. second68        /// hop)69        /// </summary>70        [Parameter]71        [ValidateNotNullOrEmpty]72        [Alias("auth", "am")]73        public virtual AuthenticationMechanism Authentication74        {75            get76            {77                return authentication;78            }79 80            set81            {82                authentication = value;83                ValidateSpecifiedAuthentication();84            }85        }86 87        private AuthenticationMechanism authentication = AuthenticationMechanism.Default;88 89        /// <summary>90        /// Specifies the certificate thumbprint to be used to impersonate the user on the91        /// remote machine.92        /// </summary>93        [Parameter]94        [ValidateNotNullOrEmpty]95        public virtual string CertificateThumbprint96        {97            get98            {99                return thumbPrint;100            }101 102            set103            {104                thumbPrint = value;105                ValidateSpecifiedAuthentication();106            }107        }108 109        private string thumbPrint = null;110 111        internal void ValidateSpecifiedAuthentication()112        {113            WSManHelper.ValidateSpecifiedAuthentication(114                this.Authentication,115                this.Credential,116                this.CertificateThumbprint);117        }118    }119 120    #endregion121 122    #region Connect-WsMan123    /// <summary>124    /// Connect wsman cmdlet.125    /// </summary>126    [Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096841")]127    public class ConnectWSManCommand : AuthenticatingWSManCommand128    {129        #region Parameters130 131        /// <summary>132        /// The following is the definition of the input parameter "ApplicationName".133        /// ApplicationName identifies the remote endpoint.134        /// </summary>135        [Parameter(ParameterSetName = "ComputerName")]136        [ValidateNotNullOrEmpty]137        public string ApplicationName138        {139            get { return applicationname; }140 141            set { applicationname = value; }142        }143 144        private string applicationname = null;145 146        /// <summary>147        /// The following is the definition of the input parameter "ComputerName".148        /// Executes the management operation on the specified computer(s). The default149        /// is the local computer. Type the fully qualified domain name, NETBIOS name or150        /// IP address to indicate the remote host(s)151        /// </summary>152        [Parameter(ParameterSetName = "ComputerName", Position = 0)]153        [Alias("cn")]154        public string ComputerName155        {156            get157            {158                return computername;159            }160 161            set162            {163                computername = value;164                if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))165                {166                    computername = "localhost";167                }168            }169        }170 171        private string computername = null;172 173        /// <summary>174        /// The following is the definition of the input parameter "ConnectionURI".175        /// Specifies the transport, server, port, and ApplicationName of the new176        /// runspace. The format of this string is:177        /// transport://server:port/ApplicationName.178        /// </summary>179        [Parameter(ParameterSetName = "URI")]180        [ValidateNotNullOrEmpty]181        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]182        public Uri ConnectionURI183        {184            get { return connectionuri; }185 186            set { connectionuri = value; }187        }188 189        private Uri connectionuri;190 191        /// <summary>192        /// The following is the definition of the input parameter "OptionSet".193        /// OptionSet is a hash table and is used to pass a set of switches to the194        /// service to modify or refine the nature of the request.195        /// </summary>196        [Parameter]197        [ValidateNotNullOrEmpty]198        [Alias("os")]199        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]200        public Hashtable OptionSet201        {202            get { return optionset; }203 204            set { optionset = value; }205        }206 207        private Hashtable optionset;208 209        /// <summary>210        /// The following is the definition of the input parameter "Port".211        /// Specifies the port to be used when connecting to the ws management service.212        /// </summary>213        [Parameter]214        [ValidateNotNullOrEmpty]215        [Parameter(ParameterSetName = "ComputerName")]216        [ValidateRange(1, int.MaxValue)]217        public int Port218        {219            get { return port; }220 221            set { port = value; }222        }223 224        private int port = 0;225 226        /// <summary>227        /// The following is the definition of the input parameter "SessionOption".228        /// Defines a set of extended options for the WSMan session.  This hashtable can229        /// be created using New-WSManSessionOption.230        /// </summary>231        [Parameter]232        [ValidateNotNullOrEmpty]233        [Alias("so")]234        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]235        public SessionOption SessionOption236        {237            get { return sessionoption; }238 239            set { sessionoption = value; }240        }241 242        private SessionOption sessionoption;243 244        /// <summary>245        /// The following is the definition of the input parameter "UseSSL".246        /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to247        /// the remote computer. If SSL is not available on the port specified by the248        /// Port parameter, the command fails.249        /// </summary>250        [Parameter(ParameterSetName = "ComputerName")]251        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]252        public SwitchParameter UseSSL253        {254            get { return usessl; }255 256            set { usessl = value; }257        }258 259        private SwitchParameter usessl;260 261        #endregion262 263        /// <summary>264        /// BeginProcessing method.265        /// </summary>266        protected override void BeginProcessing()267        {268            WSManHelper helper = new WSManHelper(this);269            if (connectionuri != null)270            {271                try272                {273                    // always in the format http://server:port/applicationname274                    string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None);275                    string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None);276                    computername = constrsplit1[1].Trim();277                }278                catch (IndexOutOfRangeException)279                {280                    helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri);281                }282            }283 284            string crtComputerName = computername ?? "localhost";285 286            if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.OrdinalIgnoreCase))287            {288                helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername);289            }290 291            helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint);292        }293    }294    #endregion295 296    #region Disconnect-WSMAN297    /// <summary>298    /// The following is the definition of the input parameter "ComputerName".299    /// Executes the management operation on the specified computer(s). The default300    /// is the local computer. Type the fully qualified domain name, NETBIOS name or301    /// IP address to indicate the remote host(s)302    /// </summary>303    [Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096839")]304    public class DisconnectWSManCommand : PSCmdlet, IDisposable305    {306        /// <summary>307        /// The following is the definition of the input parameter "ComputerName".308        /// Executes the management operation on the specified computer(s). The default309        /// is the local computer. Type the fully qualified domain name, NETBIOS name or310        /// IP address to indicate the remote host(s)311        /// </summary>312        [Parameter(Position = 0)]313        public string ComputerName314        {315            get316            {317                return computername;318            }319 320            set321            {322                computername = value;323                if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))324                {325                    computername = "localhost";326                }327            }328        }329 330        private string computername = null;331 332        #region IDisposable Members333 334        /// <summary>335        /// Public dispose method.336        /// </summary>337        public338        void339        Dispose()340        {341            // CleanUp();342            GC.SuppressFinalize(this);343        }344        /// <summary>345        /// Public dispose method.346        /// </summary>347        public348        void349        Dispose(object session)350        {351            session = null;352            this.Dispose();353        }354 355        #endregion IDisposable Members356 357        /// <summary>358        /// BeginProcessing method.359        /// </summary>360        protected override void BeginProcessing()361        {362            WSManHelper helper = new WSManHelper(this);363            computername ??= "localhost";364 365            if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.OrdinalIgnoreCase))366            {367                helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername);368            }369 370            if (computername.Equals("localhost", StringComparison.OrdinalIgnoreCase))371            {372                helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername);373            }374 375            object _ws = helper.RemoveFromDictionary(computername);376            if (_ws != null)377            {378                Dispose(_ws);379            }380            else381            {382                helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername);383            }384        }385    }386    #endregion Disconnect-WSMAN387}388