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.Globalization;10using System.IO;11using System.Management.Automation;12using System.Management.Automation.Provider;13using System.Management.Automation.Runspaces;14using System.Reflection;15using System.Runtime.CompilerServices;16using System.Runtime.InteropServices;17using System.Xml;18 19using Dbg = System.Management.Automation;20 21namespace Microsoft.WSMan.Management22{23 #region Get-WSManInstance24 /// <summary>25 /// Executes action on a target object specified by RESOURCE_URI, where26 /// parameters are specified by key value pairs.27 /// eg., Call StartService method on the spooler service28 /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service29 /// -SelectorSet {Name=Spooler}30 /// </summary>31 [Cmdlet(VerbsCommon.Get, "WSManInstance", DefaultParameterSetName = "GetInstance", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096627")]32 [OutputType(typeof(XmlElement))]33 public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable34 {35 #region parameter36 /// <summary>37 /// The following is the definition of the input parameter "ApplicationName".38 /// ApplicationName identifies the remote endpoint.39 /// </summary>40 [Parameter(ParameterSetName = "GetInstance")]41 [Parameter(ParameterSetName = "Enumerate")]42 public string ApplicationName43 {44 get45 {46 return applicationname;47 }48 49 set50 {51 { applicationname = value; }52 }53 }54 55 private string applicationname = null;56 57 /// <summary>58 /// The following is the definition of the input parameter "BasePropertiesOnly".59 /// Enumerate only those properties that are part of the base class60 /// specification in the Resource URI. When61 /// Shallow is specified then this flag has no effect.62 /// </summary>63 [Parameter(ParameterSetName = "Enumerate")]64 [Alias("UBPO", "Base")]65 public SwitchParameter BasePropertiesOnly66 {67 get68 {69 return basepropertiesonly;70 }71 72 set73 {74 { basepropertiesonly = value; }75 }76 }77 78 private SwitchParameter basepropertiesonly;79 80 /// <summary>81 /// The following is the definition of the input parameter "ComputerName".82 /// Executes the management operation on the specified computer(s). The default83 /// is the local computer. Type the fully qualified domain name, NETBIOS name or84 /// IP address to indicate the remote host(s)85 /// </summary>86 [Parameter(ParameterSetName = "GetInstance")]87 [Parameter(ParameterSetName = "Enumerate")]88 [Alias("CN")]89 public string ComputerName90 {91 get92 {93 return computername;94 }95 96 set97 {98 computername = value;99 if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))100 {101 computername = "localhost";102 }103 }104 }105 106 private string computername = null;107 108 /// <summary>109 /// The following is the definition of the input parameter "ConnectionURI".110 /// Specifies the transport, server, port, and Prefix, needed to connect to the111 /// remote machine. The format of this string is:112 /// transport://server:port/Prefix.113 /// </summary>114 [Parameter(115 ParameterSetName = "GetInstance")]116 [Parameter(117 ParameterSetName = "Enumerate")]118 [Alias("CURI", "CU")]119 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]120 public Uri ConnectionURI121 {122 get123 {124 return connectionuri;125 }126 127 set128 {129 { connectionuri = value; }130 }131 }132 133 private Uri connectionuri;134 135 /// <summary>136 /// The following is the definition of the input parameter "Dialect".137 /// Defines the dialect for the filter predicate.138 /// </summary>139 [Parameter]140 public Uri Dialect141 {142 get143 {144 return dialect;145 }146 147 set148 {149 { dialect = value; }150 }151 }152 153 private Uri dialect;154 155 /// <summary>156 /// The following is the definition of the input parameter "Enumerate".157 /// Switch indicates list all instances of a management resource. Equivalent to158 /// WSManagement Enumerate.159 /// </summary>160 [Parameter(Mandatory = true,161 ParameterSetName = "Enumerate")]162 public SwitchParameter Enumerate163 {164 get165 {166 return enumerate;167 }168 169 set170 {171 { enumerate = value; }172 }173 }174 175 private SwitchParameter enumerate;176 177 /// <summary>178 /// The following is the definition of the input parameter "Filter".179 /// Indicates the filter expression for the enumeration.180 /// </summary>181 [Parameter(ParameterSetName = "Enumerate")]182 [ValidateNotNullOrEmpty]183 public string Filter184 {185 get186 {187 return filter;188 }189 190 set191 {192 { filter = value; }193 }194 }195 196 private string filter;197 198 /// <summary>199 /// The following is the definition of the input parameter "Fragment".200 /// Specifies a section inside the instance that is to be updated or retrieved201 /// for the given operation.202 /// </summary>203 [Parameter(ParameterSetName = "GetInstance")]204 [ValidateNotNullOrEmpty]205 public string Fragment206 {207 get208 {209 return fragment;210 }211 212 set213 {214 { fragment = value; }215 }216 }217 218 private string fragment;219 220 /// <summary>221 /// The following is the definition of the input parameter "OptionSet".222 /// OptionSet is a hashtable and is used to pass a set of switches to the223 /// service to modify or refine the nature of the request.224 /// </summary>225 [Parameter(ValueFromPipeline = true,226 ValueFromPipelineByPropertyName = true)]227 [ValidateNotNullOrEmpty]228 [Alias("OS")]229 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]230 public Hashtable OptionSet231 {232 get233 {234 return optionset;235 }236 237 set238 {239 { optionset = value; }240 }241 }242 243 private Hashtable optionset;244 245 /// <summary>246 /// The following is the definition of the input parameter "Port".247 /// Specifies the port to be used when connecting to the ws management service.248 /// </summary>249 [Parameter(ParameterSetName = "Enumerate")]250 [Parameter(ParameterSetName = "GetInstance")]251 public int Port252 {253 get254 {255 return port;256 }257 258 set259 {260 { port = value; }261 }262 }263 264 private int port = 0;265 266 /// <summary>267 /// The following is the definition of the input parameter "Associations".268 /// Associations indicates retrieval of association instances as opposed to269 /// associated instances. This can only be used when specifying the Dialect as270 /// Association.271 /// </summary>272 [Parameter(ParameterSetName = "Enumerate")]273 public SwitchParameter Associations274 {275 get276 {277 return associations;278 }279 280 set281 {282 { associations = value; }283 }284 }285 286 private SwitchParameter associations;287 288 /// <summary>289 /// The following is the definition of the input parameter "ResourceURI".290 /// URI of the resource class/instance representation.291 /// </summary>292 [Parameter(Mandatory = true,293 Position = 0,294 ValueFromPipeline = true,295 ValueFromPipelineByPropertyName = true)]296 297 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]298 [Alias("RURI")]299 public Uri ResourceURI300 {301 get302 {303 return resourceuri;304 }305 306 set307 {308 { resourceuri = value; }309 }310 }311 312 private Uri resourceuri;313 314 /// <summary>315 /// The following is the definition of the input parameter "ReturnType".316 /// Indicates the type of data returned. Possible options are 'Object', 'EPR',317 /// and 'ObjectAndEPR'. Default is Object.318 /// If Object is specified or if this parameter is absent then only the objects319 /// are returned320 /// If EPR is specified then only the EPRs of the objects321 /// are returned. EPRs contain information about the Resource URI and selectors322 /// for the instance323 /// If ObjectAndEPR is specified, then both the object and the associated EPRs324 /// are returned.325 /// </summary>326 [Parameter(ParameterSetName = "Enumerate")]327 328 [ValidateNotNullOrEmpty]329 [ValidateSet(new string[] { "object", "epr", "objectandepr" })]330 [Alias("RT")]331 public string ReturnType332 {333 get334 {335 return returntype;336 }337 338 set339 {340 { returntype = value; }341 }342 }343 344 private string returntype = "object";345 346 /// <summary>347 /// The following is the definition of the input parameter "SelectorSet".348 /// SelectorSet is a hash table which helps in identify an instance of the349 /// management resource if there are more than 1 instance of the resource350 /// class.351 /// </summary>352 [Parameter(353 ParameterSetName = "GetInstance")]354 355 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]356 public Hashtable SelectorSet357 {358 get359 {360 return selectorset;361 }362 363 set364 {365 { selectorset = value; }366 }367 }368 369 private Hashtable selectorset;370 371 /// <summary>372 /// The following is the definition of the input parameter "SessionOption".373 /// Defines a set of extended options for the WSMan session. This can be374 /// created by using the cmdlet New-WSManSessionOption.375 /// </summary>376 [Parameter]377 [ValidateNotNullOrEmpty]378 [Alias("SO")]379 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]380 public SessionOption SessionOption381 {382 get383 {384 return sessionoption;385 }386 387 set388 {389 { sessionoption = value; }390 }391 }392 393 private SessionOption sessionoption;394 395 /// <summary>396 /// The following is the definition of the input parameter "Shallow".397 /// Enumerate only instances of the base class specified in the resource URI. If398 /// this flag is not specified, instances of the base class specified in the URI399 /// and all its derived classes are returned.400 /// </summary>401 [Parameter(ParameterSetName = "Enumerate")]402 403 public SwitchParameter Shallow404 {405 get406 {407 return shallow;408 }409 410 set411 {412 { shallow = value; }413 }414 }415 416 private SwitchParameter shallow;417 418 /// <summary>419 /// The following is the definition of the input parameter "UseSSL".420 /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to421 /// the remote computer. If SSL is not available on the port specified by the422 /// Port parameter, the command fails.423 /// </summary>424 [Parameter(ParameterSetName = "GetInstance")]425 [Parameter(ParameterSetName = "Enumerate")]426 427 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]428 [Alias("SSL")]429 public SwitchParameter UseSSL430 {431 get432 {433 return usessl;434 }435 436 set437 {438 { usessl = value; }439 }440 }441 442 private SwitchParameter usessl;443 444 #endregion parameter445 446 #region private447 private WSManHelper helper;448 449 private string GetFilter()450 {451 string name;452 string value;453 string[] Split = filter.Trim().Split(new char[] { '=', ';' });454 if ((Split.Length) % 2 != 0)455 {456 // mismatched property name/value pair457 return null;458 }459 460 filter = "<wsman:SelectorSet xmlns:wsman='http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'>";461 for (int i = 0; i < Split.Length; i += 2)462 {463 value = Split[i + 1].Substring(1, Split[i + 1].Length - 2);464 name = Split[i];465 filter = filter + "<wsman:Selector Name='" + name + "'>" + value + "</wsman:Selector>";466 }467 468 filter += "</wsman:SelectorSet>";469 return (filter);470 }471 472 private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession)473 {474 string fragment;475 try476 {477 int flags = 0;478 IWSManEnumerator obj;479 if (returntype != null)480 {481 if (returntype.Equals("object", StringComparison.OrdinalIgnoreCase))482 {483 flags = wsmanObject.EnumerationFlagReturnObject();484 }485 else if (returntype.Equals("epr", StringComparison.OrdinalIgnoreCase))486 {487 flags = wsmanObject.EnumerationFlagReturnEPR();488 }489 else490 {491 flags = wsmanObject.EnumerationFlagReturnObjectAndEPR();492 }493 }494 495 if (shallow)496 {497 flags |= wsmanObject.EnumerationFlagHierarchyShallow();498 }499 else if (basepropertiesonly)500 {501 flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly();502 }503 else504 {505 flags |= wsmanObject.EnumerationFlagHierarchyDeep();506 }507 508 if (dialect != null && filter != null)509 {510 if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.OrdinalIgnoreCase))511 {512 fragment = helper.URI_WQL_DIALECT;513 dialect = new Uri(fragment);514 }515 else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.OrdinalIgnoreCase))516 {517 if (associations)518 {519 flags |= wsmanObject.EnumerationFlagAssociationInstance();520 }521 else522 {523 flags |= wsmanObject.EnumerationFlagAssociatedInstance();524 }525 526 fragment = helper.URI_ASSOCIATION_DIALECT;527 dialect = new Uri(fragment);528 }529 else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.OrdinalIgnoreCase))530 {531 filter = GetFilter();532 fragment = helper.URI_SELECTOR_DIALECT;533 dialect = new Uri(fragment);534 }535 536 obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags);537 }538 else if (filter != null)539 {540 fragment = helper.URI_WQL_DIALECT;541 dialect = new Uri(fragment);542 obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags);543 }544 else545 {546 obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags);547 }548 while (!obj.AtEndOfStream)549 {550 XmlDocument xmldoc = new XmlDocument();551 xmldoc.LoadXml(obj.ReadItem());552 WriteObject(xmldoc.FirstChild);553 }554 }555 catch (Exception ex)556 {557 ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null);558 WriteError(er);559 }560 }561 #endregion private562 #region override563 /// <summary>564 /// ProcessRecord method.565 /// </summary>566 protected override void ProcessRecord()567 {568 IWSManSession m_session = null;569 IWSManEx m_wsmanObject = (IWSManEx)new WSManClass();570 helper = new WSManHelper(this);571 helper.WSManOp = "Get";572 string connectionStr = null;573 connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname);574 if (connectionuri != null)575 {576 try577 {578 // in the format http(s)://server[:port/applicationname]579 string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None);580 string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None);581 computername = constrsplit1[1].Trim();582 }583 catch (IndexOutOfRangeException)584 {585 helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri);586 }587 }588 589 try590 {591 IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri);592 m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);593 594 if (!enumerate)595 {596 XmlDocument xmldoc = new XmlDocument();597 try598 {599 xmldoc.LoadXml(m_session.Get(m_resource, 0));600 }601 catch (XmlException ex)602 {603 helper.AssertError(ex.Message, false, computername);604 }605 606 if (!string.IsNullOrEmpty(fragment))607 {608 WriteObject(xmldoc.FirstChild.LocalName + "=" + xmldoc.FirstChild.InnerText);609 }610 else611 {612 WriteObject(xmldoc.FirstChild);613 }614 }615 else616 {617 try618 {619 ReturnEnumeration(m_wsmanObject, m_resource, m_session);620 }621 catch (Exception ex)622 {623 helper.AssertError(ex.Message, false, computername);624 }625 }626 }627 finally628 {629 if (!string.IsNullOrEmpty(m_wsmanObject.Error))630 {631 helper.AssertError(m_wsmanObject.Error, true, resourceuri);632 }633 634 if (!string.IsNullOrEmpty(m_session.Error))635 {636 helper.AssertError(m_session.Error, true, resourceuri);637 }638 639 if (m_session != null)640 Dispose(m_session);641 }642 }643 #endregion override644 #region IDisposable Members645 646 /// <summary>647 /// Public dispose method.648 /// </summary>649 public650 void651 Dispose()652 {653 // CleanUp();654 GC.SuppressFinalize(this);655 }656 /// <summary>657 /// Public dispose method.658 /// </summary>659 public660 void661 Dispose(IWSManSession sessionObject)662 {663 sessionObject = null;664 this.Dispose();665 }666 667 #endregion IDisposable Members668 669 /// <summary>670 /// BeginProcessing method.671 /// </summary>672 protected override void EndProcessing()673 {674 helper.CleanUp();675 }676 }677 #endregion678 679 #region Set-WsManInstance680 681 /// <summary>682 /// Executes action on a target object specified by RESOURCE_URI, where683 /// parameters are specified by key value pairs.684 /// eg., Call StartService method on the spooler service685 /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service686 /// -SelectorSet {Name=Spooler}687 /// </summary>688 [Cmdlet(VerbsCommon.Set, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096937")]689 [OutputType(typeof(XmlElement), typeof(string))]690 public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable691 {692 #region Parameters693 /// <summary>694 /// The following is the definition of the input parameter "ApplicationName".695 /// ApplicationName identifies the remote endpoint.696 /// </summary>697 [Parameter(ParameterSetName = "ComputerName")]698 [ValidateNotNullOrEmpty]699 public string ApplicationName700 {701 get { return applicationname; }702 703 set { applicationname = value; }704 }705 706 private string applicationname = null;707 708 /// <summary>709 /// The following is the definition of the input parameter "ComputerName".710 /// Executes the management operation on the specified computer(s). The default711 /// is the local computer. Type the fully qualified domain name, NETBIOS name or712 /// IP address to indicate the remote host(s)713 /// </summary>714 [Parameter(ParameterSetName = "ComputerName")]715 [Alias("cn")]716 public string ComputerName717 {718 get719 {720 return computername;721 }722 723 set724 {725 computername = value;726 if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))727 {728 computername = "localhost";729 }730 }731 }732 733 private string computername = null;734 735 /// <summary>736 /// The following is the definition of the input parameter "ConnectionURI".737 /// Specifies the transport, server, port, and ApplicationName of the new738 /// runspace. The format of this string is:739 /// transport://server:port/ApplicationName.740 /// </summary>741 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]742 [Parameter(ParameterSetName = "URI")]743 [ValidateNotNullOrEmpty]744 public Uri ConnectionURI745 {746 get { return connectionuri; }747 748 set { connectionuri = value; }749 }750 751 private Uri connectionuri;752 753 /// <summary>754 /// The following is the definition of the input parameter "Dialect".755 /// Defines the dialect for the filter predicate.756 /// </summary>757 [Parameter]758 [ValidateNotNullOrEmpty]759 public Uri Dialect760 {761 get { return dialect; }762 763 set { dialect = value; }764 }765 766 private Uri dialect;767 768 /// <summary>769 /// The following is the definition of the input parameter "FilePath".770 /// Updates the management resource specified by the ResourceURI and SelectorSet771 /// via this input file.772 /// </summary>773 [Parameter(ValueFromPipelineByPropertyName = true)]774 [Alias("Path")]775 [ValidateNotNullOrEmpty]776 public string FilePath777 {778 get { return filepath; }779 780 set { filepath = value; }781 }782 783 private string filepath;784 785 /// <summary>786 /// The following is the definition of the input parameter "Fragment".787 /// Specifies a section inside the instance that is to be updated or retrieved788 /// for the given operation.789 /// </summary>790 [Parameter(ParameterSetName = "ComputerName")]791 [Parameter(ParameterSetName = "URI")]792 [ValidateNotNullOrEmpty]793 public string Fragment794 {795 get { return fragment; }796 797 set { fragment = value; }798 }799 800 private string fragment;801 802 /// <summary>803 /// The following is the definition of the input parameter "OptionSet".804 /// OptionSet is a hahs table which help modify or refine the nature of the805 /// request. These are similar to switches used in command line shells in that806 /// they are service-specific.807 /// </summary>808 [Parameter]809 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]810 [Alias("os")]811 [ValidateNotNullOrEmpty]812 public Hashtable OptionSet813 {814 get { return optionset; }815 816 set { optionset = value; }817 }818 819 private Hashtable optionset;820 821 /// <summary>822 /// The following is the definition of the input parameter "Port".823 /// Specifies the port to be used when connecting to the ws management service.824 /// </summary>825 [Parameter(ParameterSetName = "ComputerName")]826 [ValidateNotNullOrEmpty]827 [ValidateRange(1, int.MaxValue)]828 public int Port829 {830 get { return port; }831 832 set { port = value; }833 }834 835 private int port = 0;836 837 /// <summary>838 /// The following is the definition of the input parameter "ResourceURI".839 /// URI of the resource class/instance representation.840 /// </summary>841 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]842 [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")]843 844 [Parameter(Mandatory = true, Position = 0)]845 [Alias("ruri")]846 [ValidateNotNullOrEmpty]847 public Uri ResourceURI848 {849 get { return resourceuri; }850 851 set { resourceuri = value; }852 }853 854 private Uri resourceuri;855 856 /// <summary>857 /// The following is the definition of the input parameter "SelectorSet".858 /// SelectorSet is a hash table which helps in identify an instance of the859 /// management resource if there are more than 1 instance of the resource860 /// class.861 /// </summary>862 [Parameter(Position = 1,863 ValueFromPipeline = true,864 ValueFromPipelineByPropertyName = true)]865 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]866 [ValidateNotNullOrEmpty]867 public Hashtable SelectorSet868 {869 get { return selectorset; }870 871 set { selectorset = value; }872 }873 874 private Hashtable selectorset;875 876 /// <summary>877 /// The following is the definition of the input parameter "SessionOption".878 /// Defines a set of extended options for the WSMan session. This can be created879 /// by using the cmdlet New-WSManSessionOption.880 /// </summary>881 [Parameter]882 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]883 [Alias("so")]884 [ValidateNotNullOrEmpty]885 public SessionOption SessionOption886 {887 get { return sessionoption; }888 889 set { sessionoption = value; }890 }891 892 private SessionOption sessionoption;893 894 /// <summary>895 /// The following is the definition of the input parameter "UseSSL".896 /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to897 /// the remote computer. If SSL is not available on the port specified by the898 /// Port parameter, the command fails.899 /// </summary>900 [Parameter(ParameterSetName = "ComputerName")]901 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]902 [Alias("ssl")]903 public SwitchParameter UseSSL904 {905 get { return usessl; }906 907 set { usessl = value; }908 }909 910 private SwitchParameter usessl;911 912 /// <summary>913 /// The following is the definition of the input parameter "ValueSet".914 /// ValueSet is a hash table which helps to modify resource represented by the915 /// ResourceURI and SelectorSet.916 /// </summary>917 [Parameter(ValueFromPipelineByPropertyName = true)]918 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]919 [ValidateNotNullOrEmpty]920 public Hashtable ValueSet921 {922 get { return valueset; }923 924 set { valueset = value; }925 }926 927 private Hashtable valueset;928 929 #endregion930 931 private WSManHelper helper;932 /// <summary>933 /// ProcessRecord method.934 /// </summary>935 protected override void ProcessRecord()936 {937 IWSManEx m_wsmanObject = (IWSManEx)new WSManClass();938 helper = new WSManHelper(this);939 helper.WSManOp = "set";940 IWSManSession m_session = null;941 942 if (dialect != null)943 {944 if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase))945 dialect = new Uri(helper.URI_WQL_DIALECT);946 if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase))947 dialect = new Uri(helper.URI_SELECTOR_DIALECT);948 if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase))949 dialect = new Uri(helper.URI_ASSOCIATION_DIALECT);950 }951 952 try953 {954 string connectionStr = string.Empty;955 connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname);956 if (connectionuri != null)957 {958 try959 {960 // in the format http(s)://server[:port/applicationname]961 string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None);962 string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None);963 computername = constrsplit1[1].Trim();964 }965 catch (IndexOutOfRangeException)966 {967 helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri);968 }969 }970 971 IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri);972 m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);973 string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null);974 string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session);975 976 XmlDocument xmldoc = new XmlDocument();977 try978 {979 xmldoc.LoadXml(m_session.Put(m_resource, input, 0));980 }981 catch (XmlException ex)982 {983 helper.AssertError(ex.Message, false, computername);984 }985 986 if (!string.IsNullOrEmpty(fragment))987 {988 if (xmldoc.DocumentElement.ChildNodes.Count > 0)989 {990 foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes)991 {992 if (node.Name.Equals(fragment, StringComparison.OrdinalIgnoreCase))993 WriteObject(node.Name + " = " + node.InnerText);994 }995 }996 }997 else998 WriteObject(xmldoc.DocumentElement);999 }1000 finally1001 {1002 if (!string.IsNullOrEmpty(m_wsmanObject.Error))1003 {1004 helper.AssertError(m_wsmanObject.Error, true, resourceuri);1005 }1006 1007 if (!string.IsNullOrEmpty(m_session.Error))1008 {1009 helper.AssertError(m_session.Error, true, resourceuri);1010 }1011 1012 if (m_session != null)1013 Dispose(m_session);1014 }1015 }1016 1017 #region IDisposable Members1018 1019 /// <summary>1020 /// Public dispose method.1021 /// </summary>1022 public1023 void1024 Dispose()1025 {1026 // CleanUp();1027 GC.SuppressFinalize(this);1028 }1029 /// <summary>1030 /// Public dispose method.1031 /// </summary>1032 public1033 void1034 Dispose(IWSManSession sessionObject)1035 {1036 sessionObject = null;1037 this.Dispose();1038 }1039 1040 #endregion IDisposable Members1041 1042 /// <summary>1043 /// BeginProcessing method.1044 /// </summary>1045 protected override void EndProcessing()1046 {1047 helper.CleanUp();1048 }1049 }1050 1051 #endregion1052 1053 #region Remove-WsManInstance1054 1055 /// <summary>1056 /// Executes action on a target object specified by RESOURCE_URI, where1057 /// parameters are specified by key value pairs.1058 /// eg., Call StartService method on the spooler service1059 /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service1060 /// -SelectorSet {Name=Spooler}1061 /// </summary>1062 [Cmdlet(VerbsCommon.Remove, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096721")]1063 public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable1064 {1065 #region Parameters1066 /// <summary>1067 /// The following is the definition of the input parameter "ApplicationName".1068 /// ApplicationName identifies the remote endpoint.1069 /// </summary>1070 [Parameter(ParameterSetName = "ComputerName")]1071 [ValidateNotNullOrEmpty]1072 public string ApplicationName1073 {1074 get { return applicationname; }1075 1076 set { applicationname = value; }1077 }1078 1079 private string applicationname = null;1080 1081 /// <summary>1082 /// The following is the definition of the input parameter "ComputerName".1083 /// Executes the management operation on the specified computer(s). The default1084 /// is the local computer. Type the fully qualified domain name, NETBIOS name or1085 /// IP address to indicate the remote host(s)1086 /// </summary>1087 [Parameter(ParameterSetName = "ComputerName")]1088 [Alias("cn")]1089 public string ComputerName1090 {1091 get1092 {1093 return computername;1094 }1095 1096 set1097 {1098 computername = value;1099 if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase)))1100 {1101 computername = "localhost";1102 }1103 }1104 }1105 1106 private string computername = null;1107 1108 /// <summary>1109 /// The following is the definition of the input parameter "ConnectionURI".1110 /// Specifies the transport, server, port, and ApplicationName of the new1111 /// runspace. The format of this string is:1112 /// transport://server:port/ApplicationName.1113 /// </summary>1114 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]1115 [Parameter(ParameterSetName = "URI")]1116 [ValidateNotNullOrEmpty]1117 public Uri ConnectionURI1118 {1119 get { return connectionuri; }1120 1121 set { connectionuri = value; }1122 }1123 1124 private Uri connectionuri;1125 1126 /// <summary>1127 /// The following is the definition of the input parameter "OptionSet".1128 /// OptionSet is a hahs table which help modify or refine the nature of the1129 /// request. These are similar to switches used in command line shells in that1130 /// they are service-specific.1131 /// </summary>1132 [Parameter]1133 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]1134 [Alias("os")]1135 [ValidateNotNullOrEmpty]1136 public Hashtable OptionSet1137 {1138 get { return optionset; }1139 1140 set { optionset = value; }1141 }1142 1143 private Hashtable optionset;1144 1145 /// <summary>1146 /// The following is the definition of the input parameter "Port".1147 /// Specifies the port to be used when connecting to the ws management service.1148 /// </summary>1149 [Parameter(ParameterSetName = "ComputerName")]1150 [ValidateNotNullOrEmpty]1151 [ValidateRange(1, int.MaxValue)]1152 public int Port1153 {1154 get { return port; }1155 1156 set { port = value; }1157 }1158 1159 private int port = 0;1160 1161 /// <summary>1162 /// The following is the definition of the input parameter "ResourceURI".1163 /// URI of the resource class/instance representation.1164 /// </summary>1165 [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]1166 [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")]1167 1168 [Parameter(Mandatory = true, Position = 0)]1169 [Alias("ruri")]1170 [ValidateNotNullOrEmpty]1171 public Uri ResourceURI1172 {1173 get { return resourceuri; }1174 1175 set { resourceuri = value; }1176 }1177 1178 private Uri resourceuri;1179 1180 /// <summary>1181 /// The following is the definition of the input parameter "SelectorSet".1182 /// SelectorSet is a hash table which helps in identify an instance of the1183 /// management resource if there are more than 1 instance of the resource1184 /// class.1185 /// </summary>1186 [Parameter(Position = 1, Mandatory = true,1187 ValueFromPipeline = true,1188 ValueFromPipelineByPropertyName = true)]1189 [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]1190 [ValidateNotNullOrEmpty]1191 public Hashtable SelectorSet1192 {1193 get { return selectorset; }1194 1195 set { selectorset = value; }1196 }1197 1198 private Hashtable selectorset;1199 1200 /// <summary>