MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#region Using directives5using System;6using System.Diagnostics.CodeAnalysis;7using System.Management.Automation;8using Microsoft.Management.Infrastructure.Options;9 10#endregion11 12namespace Microsoft.Management.Infrastructure.CimCmdlets13{14 /// <summary>15 /// This Cmdlet enables the IT Pro to create a CIM Session. CIM Session object16 /// is a client-side representation of the connection between the client and the17 /// server.18 /// The CimSession object returned by the Cmdlet is used by all other CIM19 /// cmdlets.20 /// </summary>21 [Alias("ncms")]22 [Cmdlet(VerbsCommon.New, "CimSession", DefaultParameterSetName = CredentialParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227967")]23 [OutputType(typeof(CimSession))]24 public sealed class NewCimSessionCommand : CimBaseCommand25 {26 #region cmdlet parameters27 28 /// <summary>29 /// The following is the definition of the input parameter "Authentication".30 /// The following is the validation set for allowed authentication types.31 /// </summary>32 [Parameter(ValueFromPipelineByPropertyName = true,33 ParameterSetName = CredentialParameterSet)]34 public PasswordAuthenticationMechanism Authentication35 {36 get37 {38 return authentication;39 }40 41 set42 {43 authentication = value;44 authenticationSet = true;45 }46 }47 48 private PasswordAuthenticationMechanism authentication;49 private bool authenticationSet = false;50 51 /// <summary>52 /// The following is the definition of the input parameter "Credential".53 /// Specifies a user account that has permission to perform this action.54 /// The default is the current user.55 /// </summary>56 [Parameter(Position = 1, ParameterSetName = CredentialParameterSet)]57 [Credential]58 public PSCredential Credential { get; set; }59 60 /// <summary>61 /// The following is the definition of the input parameter "CertificateThumbprint".62 /// This is specificly for wsman protocol.63 /// </summary>64 [Parameter(ValueFromPipelineByPropertyName = true,65 ParameterSetName = CertificateParameterSet)]66 public string CertificateThumbprint { get; set; }67 68 /// <summary>69 /// The following is the definition of the input parameter "ComputerName".70 /// Specifies the computer on which the commands associated with this session71 /// will run. The default value is LocalHost.72 /// </summary>73 [Alias(AliasCN, AliasServerName)]74 [Parameter(75 Position = 0,76 ValueFromPipelineByPropertyName = true)]77 [ValidateNotNullOrEmpty]78 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]79 public string[] ComputerName { get; set; }80 81 /// <summary>82 /// <para>83 /// The following is the definition of the input parameter "Name".84 /// Specifies a friendly name for the CIM Session connection.85 /// </para>86 /// <para>87 /// If a name is not passed, then the session is given the name CimSession<int>,88 /// where <int> is the next available session number. Example, CimSession1,89 /// CimSession2, etc...90 /// </para>91 /// </summary>92 [Parameter(ValueFromPipelineByPropertyName = true)]93 public string Name { get; set; }94 95 /// <summary>96 /// <para>97 /// The following is the definition of the input parameter "OperationTimeoutSec".98 /// Specifies the operation timeout for all operations in session. Individual99 /// operations can override this timeout.100 /// </para>101 /// <para>102 /// The unit is Second.103 /// </para>104 /// </summary>105 [Alias(AliasOT)]106 [Parameter(ValueFromPipelineByPropertyName = true)]107 public uint OperationTimeoutSec108 {109 get110 {111 return operationTimeout;112 }113 114 set115 {116 operationTimeout = value;117 operationTimeoutSet = true;118 }119 }120 121 private uint operationTimeout;122 internal bool operationTimeoutSet = false;123 124 /// <summary>125 /// <para>126 /// The following is the definition of the input parameter "SkipTestConnection".127 /// Specifies where test connection should be skipped128 /// </para>129 /// </summary>130 [Parameter(ValueFromPipelineByPropertyName = true)]131 public SwitchParameter SkipTestConnection { get; set; }132 133 /// <summary>134 /// The following is the definition of the input parameter "Port".135 /// Specifies the port number to use, if different than the default port number.136 /// This is specificly for wsman protocol.137 /// </summary>138 [Parameter(ValueFromPipelineByPropertyName = true)]139 public uint Port140 {141 get142 {143 return port;144 }145 146 set147 {148 port = value;149 portSet = true;150 }151 }152 153 private uint port;154 private bool portSet = false;155 156 /// <summary>157 /// <para>158 /// The following is the definition of the input parameter "SessionOption".159 /// Specifies the SessionOption object that is passed to the Cmdlet as argument.160 /// </para>161 /// <para>162 /// If the argument is not given, a default SessionOption will be created for163 /// the session in .NET API layer.164 /// </para>165 /// <para>166 /// If a <see cref="DCOMSessionOption"/> object is passed, then167 /// connection is made using DCOM. If a <see cref="WsManSessionOption"/>168 /// object is passed, then connection is made using WsMan.169 /// </para>170 /// </summary>171 [Parameter(ValueFromPipelineByPropertyName = true)]172 public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption { get; set; }173 174 #endregion175 176 #region cmdlet processing methods177 178 /// <summary>179 /// BeginProcessing method.180 /// </summary>181 protected override void BeginProcessing()182 {183 cimNewSession = new CimNewSession();184 this.CmdletOperation = new CmdletOperationTestCimSession(this, this.cimNewSession);185 this.AtBeginProcess = false;186 }187 188 /// <summary>189 /// ProcessRecord method.190 /// </summary>191 protected override void ProcessRecord()192 {193 CimSessionOptions outputOptions;194 CimCredential outputCredential;195 BuildSessionOptions(out outputOptions, out outputCredential);196 cimNewSession.NewCimSession(this, outputOptions, outputCredential);197 cimNewSession.ProcessActions(this.CmdletOperation);198 }199 200 /// <summary>201 /// EndProcessing method.202 /// </summary>203 protected override void EndProcessing()204 {205 cimNewSession.ProcessRemainActions(this.CmdletOperation);206 }207 #endregion208 209 #region helper methods210 211 /// <summary>212 /// Build a CimSessionOptions, used to create CimSession.213 /// </summary>214 /// <returns>Null means no prefer CimSessionOptions.</returns>215 internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential)216 {217 DebugHelper.WriteLogEx();218 219 CimSessionOptions options = null;220 if (this.SessionOption != null)221 {222 // clone the sessionOption object223 if (this.SessionOption is WSManSessionOptions)224 {225 options = new WSManSessionOptions(this.SessionOption as WSManSessionOptions);226 }227 else228 {229 options = new DComSessionOptions(this.SessionOption as DComSessionOptions);230 }231 }232 233 outputOptions = null;234 outputCredential = null;235 if (options != null)236 {237 if (options is DComSessionOptions dcomOptions)238 {239 bool conflict = false;240 string parameterName = string.Empty;241 if (this.CertificateThumbprint != null)242 {243 conflict = true;244 parameterName = @"CertificateThumbprint";245 }246 247 if (portSet)248 {249 conflict = true;250 parameterName = @"Port";251 }252 253 if (conflict)254 {255 ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions");256 return;257 }258 }259 }260 261 if (portSet || (this.CertificateThumbprint != null))262 {263 WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions;264 if (portSet)265 {266 wsmanOptions.DestinationPort = this.Port;267 portSet = false;268 }269 270 if (this.CertificateThumbprint != null)271 {272 CimCredential credentials = new(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint);273 wsmanOptions.AddDestinationCredentials(credentials);274 }275 276 options = wsmanOptions;277 }278 279 if (this.operationTimeoutSet)280 {281 if (options != null)282 {283 options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec);284 }285 }286 287 if (this.authenticationSet || (this.Credential != null))288 {289 PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default;290 if (this.authenticationSet)291 {292 this.authenticationSet = false;293 }294 295 CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication");296 if (credentials == null)297 {298 return;299 }300 301 DebugHelper.WriteLog("Credentials: {0}", 1, credentials);302 outputCredential = credentials;303 if (options != null)304 {305 DebugHelper.WriteLog("Add credentials to option: {0}", 1, options);306 options.AddDestinationCredentials(credentials);307 }308 }309 310 DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions);311 outputOptions = options;312 }313 314 #endregion315 316 #region private members317 318 /// <summary>319 /// <para>320 /// CimNewSession object321 /// </para>322 /// </summary>323 private CimNewSession cimNewSession;324 325 #endregion326 327 #region IDisposable328 /// <summary>329 /// Clean up resources.330 /// </summary>331 protected override void DisposeInternal()332 {333 base.DisposeInternal();334 335 // Dispose managed resources.336 this.cimNewSession?.Dispose();337 }338 #endregion339 }340}341 