From 6b494be1c7b4543237352ee703372225768b309a Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:17 -0800 Subject: [PATCH 01/81] Update TestService --- test/tools/TestService/Program.cs | 2 +- test/tools/TestService/Service1.Designer.cs | 3 ++- test/tools/TestService/Service1.cs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/test/tools/TestService/Program.cs b/test/tools/TestService/Program.cs index f3a5c5d53b4..6be04aac653 100644 --- a/test/tools/TestService/Program.cs +++ b/test/tools/TestService/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.ServiceProcess; diff --git a/test/tools/TestService/Service1.Designer.cs b/test/tools/TestService/Service1.Designer.cs index b8210d468c9..8ec66d05df5 100644 --- a/test/tools/TestService/Service1.Designer.cs +++ b/test/tools/TestService/Service1.Designer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace TestService { @@ -12,6 +12,7 @@ protected override void Dispose(bool disposing) { components.Dispose(); } + base.Dispose(disposing); } diff --git a/test/tools/TestService/Service1.cs b/test/tools/TestService/Service1.cs index 36f680fa5f9..2a5e5c18f6b 100644 --- a/test/tools/TestService/Service1.cs +++ b/test/tools/TestService/Service1.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.ServiceProcess; From f3f173eaf6bf304b4b5dbd37a407055ba90d2332 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:17 -0800 Subject: [PATCH 02/81] Update WebListener --- test/tools/WebListener/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/test/tools/WebListener/Program.cs b/test/tools/WebListener/Program.cs index 74135b2f2ce..a5535500fc2 100644 --- a/test/tools/WebListener/Program.cs +++ b/test/tools/WebListener/Program.cs @@ -25,6 +25,7 @@ public static void Main(string[] args) System.Console.WriteLine("Required: "); Environment.Exit(1); } + BuildWebHost(args).Run(); } From 088dfd2c6ad405236ecc04fbb14b68842feca202 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:18 -0800 Subject: [PATCH 03/81] Update Controllers --- test/tools/WebListener/Controllers/CertController.cs | 1 + test/tools/WebListener/Controllers/DelayController.cs | 1 + test/tools/WebListener/Controllers/GetController.cs | 4 ++++ test/tools/WebListener/Controllers/HomeController.cs | 1 + test/tools/WebListener/Controllers/LinkController.cs | 2 ++ test/tools/WebListener/Controllers/MultipartController.cs | 5 +++++ test/tools/WebListener/Controllers/RedirectController.cs | 1 + test/tools/WebListener/Controllers/ResponseController.cs | 1 + .../WebListener/Controllers/ResponseHeadersController.cs | 1 + test/tools/WebListener/Controllers/ResumeController.cs | 2 ++ 10 files changed, 19 insertions(+) diff --git a/test/tools/WebListener/Controllers/CertController.cs b/test/tools/WebListener/Controllers/CertController.cs index 0e7eda84992..e2bca31cd32 100644 --- a/test/tools/WebListener/Controllers/CertController.cs +++ b/test/tools/WebListener/Controllers/CertController.cs @@ -34,6 +34,7 @@ public JsonResult Index() {"NotBefore" , HttpContext.Connection.ClientCertificate.NotBefore} }; } + return Json(output); } diff --git a/test/tools/WebListener/Controllers/DelayController.cs b/test/tools/WebListener/Controllers/DelayController.cs index 2298c892540..c64fb2490b9 100644 --- a/test/tools/WebListener/Controllers/DelayController.cs +++ b/test/tools/WebListener/Controllers/DelayController.cs @@ -21,6 +21,7 @@ public JsonResult Index(int seconds) int milliseconds = seconds * 1000; Thread.Sleep(milliseconds); } + var getController = new GetController(); getController.ControllerContext = this.ControllerContext; return getController.Index(); diff --git a/test/tools/WebListener/Controllers/GetController.cs b/test/tools/WebListener/Controllers/GetController.cs index 24a3edb3bfe..0cf6cb9a8c1 100644 --- a/test/tools/WebListener/Controllers/GetController.cs +++ b/test/tools/WebListener/Controllers/GetController.cs @@ -22,11 +22,13 @@ public JsonResult Index() { args.Add(key, String.Join(Constants.HeaderSeparator, Request.Query[key])); } + Hashtable headers = new Hashtable(); foreach (var key in Request.Headers.Keys) { headers.Add(key, String.Join(Constants.HeaderSeparator, Request.Headers[key])); } + Hashtable output = new Hashtable { {"args" , args}, @@ -43,6 +45,7 @@ public JsonResult Index() { form.Add(key,Request.Form[key]); } + output["form"] = form; } @@ -54,6 +57,7 @@ public JsonResult Index() return Json(output); } + public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); diff --git a/test/tools/WebListener/Controllers/HomeController.cs b/test/tools/WebListener/Controllers/HomeController.cs index 88c12d7ebd4..3341ff11f6a 100644 --- a/test/tools/WebListener/Controllers/HomeController.cs +++ b/test/tools/WebListener/Controllers/HomeController.cs @@ -16,6 +16,7 @@ public IActionResult Index() { return View(); } + public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); diff --git a/test/tools/WebListener/Controllers/LinkController.cs b/test/tools/WebListener/Controllers/LinkController.cs index e699dd325ca..e70a75f66be 100644 --- a/test/tools/WebListener/Controllers/LinkController.cs +++ b/test/tools/WebListener/Controllers/LinkController.cs @@ -46,6 +46,7 @@ public JsonResult Index() { linkList.Add(GetLink(baseUri: baseUri, maxLinks: maxLinks, linkNumber: linkNumber - 1, type: type, whitespace: whitespace, rel: "prev")); } + linkList.Add(GetLink(baseUri: baseUri, maxLinks: maxLinks, linkNumber: maxLinks, type: type, whitespace: whitespace, rel: "last")); linkList.Add(GetLink(baseUri: baseUri, maxLinks: maxLinks, linkNumber: 1, type: type, whitespace: whitespace, rel: "first")); linkList.Add(GetLink(baseUri: baseUri, maxLinks: maxLinks, linkNumber: linkNumber, type: type, whitespace: whitespace, rel: "self")); @@ -87,6 +88,7 @@ public JsonResult Index() { linkHeader = String.Join(",", linkList); } + Response.Headers.Add("Link", linkHeader); // Generate /Get/ result and append linknumber, maxlinks, and type diff --git a/test/tools/WebListener/Controllers/MultipartController.cs b/test/tools/WebListener/Controllers/MultipartController.cs index f94e539893e..959c081d66d 100644 --- a/test/tools/WebListener/Controllers/MultipartController.cs +++ b/test/tools/WebListener/Controllers/MultipartController.cs @@ -23,6 +23,7 @@ public MultipartController(IHostingEnvironment environment) { _environment = environment; } + public ActionResult Index() { return View(); @@ -49,6 +50,7 @@ public JsonResult Index(IFormCollection collection) result = reader.ReadToEnd(); } } + Hashtable fileHash = new Hashtable { {"ContentDisposition" , file.ContentDisposition}, @@ -61,17 +63,20 @@ public JsonResult Index(IFormCollection collection) }; fileList.Add(fileHash); } + Hashtable itemsHash = new Hashtable(); foreach (var key in collection.Keys) { itemsHash.Add(key,collection[key]); } + MediaTypeHeaderValue mediaContentType = MediaTypeHeaderValue.Parse(Request.ContentType); Hashtable headers = new Hashtable(); foreach (var key in Request.Headers.Keys) { headers.Add(key, String.Join(Constants.HeaderSeparator, Request.Headers[key])); } + Hashtable output = new Hashtable { {"Files" , fileList}, diff --git a/test/tools/WebListener/Controllers/RedirectController.cs b/test/tools/WebListener/Controllers/RedirectController.cs index b32722b3822..3e9a14f9806 100644 --- a/test/tools/WebListener/Controllers/RedirectController.cs +++ b/test/tools/WebListener/Controllers/RedirectController.cs @@ -52,6 +52,7 @@ public IActionResult Index(int count) return View(); } + public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); diff --git a/test/tools/WebListener/Controllers/ResponseController.cs b/test/tools/WebListener/Controllers/ResponseController.cs index 23c0a461ff9..339b60bdb25 100644 --- a/test/tools/WebListener/Controllers/ResponseController.cs +++ b/test/tools/WebListener/Controllers/ResponseController.cs @@ -65,6 +65,7 @@ public String Index() { continue; } + foreach (string entry in GetSingleOrArray(property.Value)) { Response.Headers.Append(property.Name,entry); diff --git a/test/tools/WebListener/Controllers/ResponseHeadersController.cs b/test/tools/WebListener/Controllers/ResponseHeadersController.cs index e53f10f6271..5eab3c82640 100644 --- a/test/tools/WebListener/Controllers/ResponseHeadersController.cs +++ b/test/tools/WebListener/Controllers/ResponseHeadersController.cs @@ -40,6 +40,7 @@ public string Index() Response.Headers.TryAdd(key, Request.Query[key]); } } + return JsonConvert.SerializeObject(headers); } diff --git a/test/tools/WebListener/Controllers/ResumeController.cs b/test/tools/WebListener/Controllers/ResumeController.cs index d3f8944a45c..aaaf962a8b0 100644 --- a/test/tools/WebListener/Controllers/ResumeController.cs +++ b/test/tools/WebListener/Controllers/ResumeController.cs @@ -34,6 +34,7 @@ public async void Index() { from = (int)range.From; } + if(range.To != null) { to = (int)range.To; @@ -79,6 +80,7 @@ public async void Bytes(int NumberBytes) { NumberBytes = FileBytes.Length; } + Response.ContentType = MediaTypeNames.Application.Octet; Response.ContentLength = NumberBytes; await Response.Body.WriteAsync(FileBytes, 0, NumberBytes); From 86eb91692b14622d21536444eb94cd66e746d016 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:24 -0800 Subject: [PATCH 04/81] Update ExpTest --- .../engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs b/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs index a73b649f48c..3d38dd57145 100644 --- a/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs +++ b/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs @@ -62,8 +62,10 @@ protected override void EndProcessing() if (ExperimentalFeature.IsEnabled("ExpTest.FeatureOne")) { if (SwitchOne.IsPresent) { message += "-SwitchOne is on."; } + if (SwitchTwo.IsPresent) { message += "-SwitchTwo is on."; } } + WriteObject(message); } } From b111f3a657c64ea25ae6ec5f71bf759895c2d2b8 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:25 -0800 Subject: [PATCH 05/81] Update MyApp --- .../sample-dotnet2.0-powershell-crossplatform/MyApp/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/host-powershell/sample-dotnet2.0-powershell-crossplatform/MyApp/Program.cs b/docs/host-powershell/sample-dotnet2.0-powershell-crossplatform/MyApp/Program.cs index 74676efba24..6553363d94f 100644 --- a/docs/host-powershell/sample-dotnet2.0-powershell-crossplatform/MyApp/Program.cs +++ b/docs/host-powershell/sample-dotnet2.0-powershell-crossplatform/MyApp/Program.cs @@ -19,6 +19,7 @@ public static int Main(string[] args) var results = ps.AddScript("Get-Command Write-Output").Invoke(); Console.WriteLine(results[0].ToString()); } + return 0; } } From 74dbb95319e7c6780e9d7b67189256a2e4792c6c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:25 -0800 Subject: [PATCH 06/81] Update Logic --- .../sample-dotnet2.0-powershell.beta.1/Logic/UseRunspace.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/host-powershell/sample-dotnet2.0-powershell.beta.1/Logic/UseRunspace.cs b/docs/host-powershell/sample-dotnet2.0-powershell.beta.1/Logic/UseRunspace.cs index e126fd28a3a..8d91e9cc252 100644 --- a/docs/host-powershell/sample-dotnet2.0-powershell.beta.1/Logic/UseRunspace.cs +++ b/docs/host-powershell/sample-dotnet2.0-powershell.beta.1/Logic/UseRunspace.cs @@ -29,6 +29,7 @@ public static int Start(string[] args) Console.WriteLine(result.ToString()); } } + return 0; } } From 59125f25ed350c45dcb9787b3fb6ecae27502db0 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:25 -0800 Subject: [PATCH 07/81] Update Logic --- docs/host-powershell/sample-dotnet1.1/Logic/UseRunspace.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/host-powershell/sample-dotnet1.1/Logic/UseRunspace.cs b/docs/host-powershell/sample-dotnet1.1/Logic/UseRunspace.cs index e126fd28a3a..8d91e9cc252 100644 --- a/docs/host-powershell/sample-dotnet1.1/Logic/UseRunspace.cs +++ b/docs/host-powershell/sample-dotnet1.1/Logic/UseRunspace.cs @@ -29,6 +29,7 @@ public static int Start(string[] args) Console.WriteLine(result.ToString()); } } + return 0; } } From 4b8c59cb2cee629cc069ac58e56c486eb61c21fb Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:26 -0800 Subject: [PATCH 08/81] Update MyApp --- .../sample-dotnet2.0-powershell.beta.3/MyApp/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/host-powershell/sample-dotnet2.0-powershell.beta.3/MyApp/Program.cs b/docs/host-powershell/sample-dotnet2.0-powershell.beta.3/MyApp/Program.cs index ec88a87b6e4..0413e5d8ab4 100644 --- a/docs/host-powershell/sample-dotnet2.0-powershell.beta.3/MyApp/Program.cs +++ b/docs/host-powershell/sample-dotnet2.0-powershell.beta.3/MyApp/Program.cs @@ -28,6 +28,7 @@ public static int Main(string[] args) Console.WriteLine(result.ToString()); } } + return 0; } } From 21b00338b6447156f00a2a651058153e430fd3b7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:28 -0800 Subject: [PATCH 09/81] Update Microsoft.Management.Infrastructure.CimCmdlets --- .../CimAsyncOperation.cs | 12 ++++ .../CimBaseAction.cs | 2 + .../CimCmdletModuleInitialize.cs | 4 ++ .../CimCommandBase.cs | 31 ++++++++++ .../CimGetAssociatedInstance.cs | 4 ++ .../CimGetCimClass.cs | 7 +++ .../CimGetInstance.cs | 25 ++++++++ .../CimIndicationWatcher.cs | 6 ++ .../CimInvokeCimMethod.cs | 18 ++++++ .../CimNewCimInstance.cs | 10 ++++ .../CimPromptUser.cs | 4 ++ .../CimRegisterCimIndication.cs | 8 +++ .../CimRemoveCimInstance.cs | 6 ++ .../CimResultObserver.cs | 4 ++ .../CimSessionOperations.cs | 37 ++++++++++++ .../CimSessionProxy.cs | 43 ++++++++++++++ .../CimSetCimInstance.cs | 14 +++++ .../CimWriteError.cs | 4 ++ .../CimWriteProgress.cs | 1 + .../CimWriteResultObject.cs | 1 + .../CmdletOperation.cs | 15 +++++ .../GetCimAssociatedInstanceCommand.cs | 19 ++++++ .../GetCimClassCommand.cs | 17 ++++++ .../GetCimInstanceCommand.cs | 27 +++++++++ .../GetCimSessionCommand.cs | 8 +++ .../InvokeCimMethodCommand.cs | 25 ++++++++ .../NewCimInstanceCommand.cs | 22 +++++++ .../NewCimSessionCommand.cs | 28 +++++++++ .../NewCimSessionOptionCommand.cs | 59 +++++++++++++++++++ .../RegisterCimIndicationCommand.cs | 21 +++++++ .../RemoveCimInstanceCommand.cs | 17 ++++++ .../RemoveCimSessionCommand.cs | 10 ++++ .../SetCimInstanceCommand.cs | 21 +++++++ .../Utils.cs | 9 +++ 34 files changed, 539 insertions(+) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 8e575e235a9..a12ec7c90d5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -62,6 +62,7 @@ protected void NewCmdletActionHandler(object cimSession, CmdletActionEventArgs a // unblock the thread waiting for response (actionArgs.Action as CimSyncAction).OnComplete(); } + return; } @@ -164,6 +165,7 @@ public void ProcessRemainActions(CmdletOperationBase cmdletOperation) DebugHelper.WriteLogEx("Either disposed or all operations completed.", 2); break; } + try { this.moreActionEvent.Wait(); @@ -177,6 +179,7 @@ public void ProcessRemainActions(CmdletOperationBase cmdletOperation) break; } } + ProcessActions(cmdletOperation); } @@ -209,6 +212,7 @@ protected void AddCimSessionProxy(CimSessionProxy sessionproxy) { this.cimSessionProxyCache = new List(); } + if (!this.cimSessionProxyCache.Contains(sessionproxy)) { this.cimSessionProxyCache.Add(sessionproxy); @@ -366,6 +370,7 @@ protected object GetBaseObject(object value) { arraybaseObject[i] = GetBaseObject(arrayObject[i]); } + return arraybaseObject; } } @@ -390,6 +395,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re { return null; } + referenceType = CimType.Reference; return cimInstance; } @@ -404,6 +410,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re { return null; } + CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length]; for (int i = 0; i < cimReferenceArray.Length; i++) { @@ -412,6 +419,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re { return null; } + object baseObject = GetBaseObject(tempCimReference.Value); cimInstanceArray[i] = baseObject as CimInstance; if (cimInstanceArray[i] == null) @@ -419,6 +427,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re return null; } } + referenceType = CimType.ReferenceArray; return cimInstanceArray; } @@ -439,6 +448,7 @@ protected bool Disposed return (Interlocked.Read(ref this._disposed) == 1); } } + private long _disposed; /// @@ -506,6 +516,7 @@ private void Cleanup() (action as CimSyncAction).OnComplete(); } } + if (this.cimSessionProxyCache != null) { List temporaryProxy; @@ -527,6 +538,7 @@ private void Cleanup() { this.ackedEvent.Dispose(); } + DebugHelper.WriteLog("Cleanup complete.", 2); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index fad68f72b47..0f0d21d639e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -50,11 +50,13 @@ protected XOperationContextBase Context { return this.context; } + set { this.context = value; } } + private XOperationContextBase context; }//End Class diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs index b496a963d93..9dfd6aa1036 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs @@ -46,6 +46,7 @@ public void OnImport() invoker.AddScript(string.Format(CultureInfo.CurrentUICulture, "Set-Alias -Name {0} -Value {1} -Option {2} -ErrorAction SilentlyContinue", alias.Name, alias.Value, alias.Options)); DebugHelper.WriteLog(@"Add commands {0} of {1} with option {2} to current runspace.", 1, alias.Name, alias.Value, alias.Options); } + System.Collections.ObjectModel.Collection psObjects = invoker.Invoke(); DebugHelper.WriteLog(@"Invoke results {0}.", 1, psObjects.Count); } @@ -77,18 +78,21 @@ internal CimCmdletAliasEntry(string name, string value) /// The string defining the name of this alias /// internal string Name { get { return this._name; } } + private string _name; /// /// The string defining real cmdlet name /// internal string Value { get { return this._value; } } + private string _value = String.Empty; /// /// The string defining real cmdlet name /// internal ScopedItemOptions Options { get { return this._options; } } + private ScopedItemOptions _options = ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index b3fb43ba926..0b970304ece 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -45,6 +45,7 @@ internal string ParameterSetName return this.parameterSetName; } } + private readonly string parameterSetName = null; /// @@ -57,6 +58,7 @@ internal bool IsMandatory return this.mandatory; } } + private readonly bool mandatory = false; } @@ -120,6 +122,7 @@ internal bool IsDefaultParameterSet return this.isDefaultParameterSet; } } + private readonly bool isDefaultParameterSet = false; /// @@ -132,6 +135,7 @@ internal UInt32 MandatoryParameterCount return this.mandatoryParameterCount; } } + private readonly UInt32 mandatoryParameterCount = 0; /// @@ -143,11 +147,13 @@ internal bool IsValueSet { return this.isValueSet; } + set { this.isValueSet = value; } } + private bool isValueSet = false; /// @@ -159,11 +165,13 @@ internal bool IsValueSetAtBeginProcess { return this.isValueSetAtBeginProcess; } + set { this.isValueSetAtBeginProcess = value; } } + private bool isValueSetAtBeginProcess = false; /// @@ -175,11 +183,13 @@ internal UInt32 SetMandatoryParameterCount { return this.setMandatoryParameterCount; } + set { this.setMandatoryParameterCount = value; } } + private UInt32 setMandatoryParameterCount = 0; /// @@ -191,11 +201,13 @@ internal UInt32 SetMandatoryParameterCountAtBeginProcess { return this.setMandatoryParameterCountAtBeginProcess; } + set { this.setMandatoryParameterCountAtBeginProcess = value; } } + private UInt32 setMandatoryParameterCountAtBeginProcess = 0; } @@ -334,8 +346,10 @@ internal void SetParameter(string parameterName, bool isBeginProcess) { psEntry.SetMandatoryParameterCountAtBeginProcess++; } + DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, psEntry.SetMandatoryParameterCount); } + if (!psEntry.IsValueSet) { psEntry.IsValueSet = true; @@ -344,8 +358,10 @@ internal void SetParameter(string parameterName, bool isBeginProcess) psEntry.IsValueSetAtBeginProcess = true; } } + nameset.Add(parameterDefinitionEntry.ParameterSetName); } + this.parametersetNamesList = nameset; if (isBeginProcess) { @@ -368,6 +384,7 @@ internal void SetParameter(string parameterName, bool isBeginProcess) { psEntry.SetMandatoryParameterCountAtBeginProcess++; } + DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'", 1, entry.ParameterSetName, @@ -375,6 +392,7 @@ internal void SetParameter(string parameterName, bool isBeginProcess) } } } + if (nameset.Count == 0) { throw new PSArgumentException(Strings.UnableToResolveParameterSetName); @@ -420,12 +438,15 @@ internal string GetParameterSet() { defaultParameterSetName = parameterSetName; } + if (entry.IsValueSet) { noMandatoryParameterSet.Add(parameterSetName); } + continue; } + if ((entry.SetMandatoryParameterCount == entry.MandatoryParameterCount) && this.parametersetNamesList.Contains(parameterSetName)) { @@ -433,6 +454,7 @@ internal string GetParameterSet() { throw new PSArgumentException(Strings.UnableToResolveParameterSetName); } + boundParameterSetName = parameterSetName; } } @@ -462,6 +484,7 @@ internal string GetParameterSet() { throw new PSArgumentException(Strings.UnableToResolveParameterSetName); } + return boundParameterSetName; } @@ -516,6 +539,7 @@ internal void CheckParameterSet() this.parameterBinder.reset(); } } + DebugHelper.WriteLog("current parameterset is: " + this.parameterSetName, 4); } @@ -533,6 +557,7 @@ internal void SetParameter(object value, string parameterName) { return; } + if (this.parameterBinder != null) { this.parameterBinder.SetParameter(parameterName, this.AtBeginProcess); @@ -684,6 +709,7 @@ internal bool AtBeginProcess { return this.atBeginProcess; } + set { this.atBeginProcess = value; @@ -709,6 +735,7 @@ internal CimAsyncOperation AsyncOperation this.operation = value; } } + get { return this.operation; @@ -924,8 +951,10 @@ internal void ThrowInvalidProperty( { propList.Append(","); } + propList.Append(property); } + string message = String.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindPropertyFromGivenClass, className, propList); PSArgumentOutOfRangeException exception = new PSArgumentOutOfRangeException( @@ -975,8 +1004,10 @@ internal CimCredential CreateCimCredentials(PSCredential psCredentials, ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); return null; } + credentials = new CimCredential(impersonatedAuthentication); } + DebugHelper.WriteLogEx("return credential {0}", 1, credentials); return credentials; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs index 524f1c928ad..64c2e3b31e8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -44,6 +44,7 @@ public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet) // try to use namespace of ciminstance, then fall back to default namespace nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace); } + List proxys = new List(); switch (cmdlet.ParameterSetName) { @@ -53,6 +54,7 @@ public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet) CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet); proxys.Add(proxy); } + break; case CimBaseCommand.SessionSetName: foreach (CimSession session in cmdlet.CimSession) @@ -60,10 +62,12 @@ public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet) CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); proxys.Add(proxy); } + break; default: return; } + foreach (CimSessionProxy proxy in proxys) { proxy.EnumerateAssociatedInstancesAsync( diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index 61a1fbcdd02..2965cac5ba6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -50,8 +50,10 @@ internal CimGetCimClassContext( public String ClassName { get { return className; } + set { className = value; } } + private String className; /// @@ -65,6 +67,7 @@ internal String MethodName { get { return methodName; } } + private String methodName; /// @@ -78,6 +81,7 @@ internal String PropertyName { get { return propertyName; } } + private String propertyName; /// @@ -91,6 +95,7 @@ internal String QualifierName { get { return qualifierName; } } + private String qualifierName; } @@ -140,6 +145,7 @@ public void GetCimClass(GetCimClassCommand cmdlet) proxys.Add(proxy); } } + break; case CimBaseCommand.SessionSetName: { @@ -150,6 +156,7 @@ public void GetCimClass(GetCimClassCommand cmdlet) proxys.Add(proxy); } } + break; default: return; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 41b6434ad0f..e0fecd62101 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -40,6 +40,7 @@ public object Process(object resultObject) obj.TypeNames.Insert(0, PartialPSTypeName); return obj; } + return resultObject; } } @@ -96,8 +97,10 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) { this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); } + proxys.Add(proxy); } + break; case CimBaseCommand.ClassNameComputerSet: case CimBaseCommand.QueryComputerSet: @@ -109,8 +112,10 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) { this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); } + proxys.Add(proxy); } + break; case CimBaseCommand.ClassNameSessionSet: case CimBaseCommand.CimInstanceSessionSet: @@ -123,12 +128,15 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) { this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand); } + proxys.Add(proxy); } + break; default: break; } + switch (cmdlet.ParameterSetName) { case CimBaseCommand.ClassNameComputerSet: @@ -152,6 +160,7 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) proxy.EnumerateInstancesAsync(nameSpace, GetClassName(cmdlet)); } } + break; case CimBaseCommand.CimInstanceComputerSet: case CimBaseCommand.CimInstanceSessionSet: @@ -163,6 +172,7 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) proxy.GetInstanceAsync(nameSpace, instance); } } + break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: @@ -173,6 +183,7 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)), GetQuery(cmdlet)); } + break; case CimBaseCommand.ResourceUriSessionSet: case CimBaseCommand.ResourceUriComputerSet: @@ -180,6 +191,7 @@ protected void GetCimInstanceInternal(CimBaseCommand cmdlet) { proxy.EnumerateInstancesAsync(GetNamespace(cmdlet), GetClassName(cmdlet)); } + break; default: break; @@ -202,6 +214,7 @@ protected static String[] GetComputerName(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).ComputerName; } + return null; } @@ -219,6 +232,7 @@ protected static String GetNamespace(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).Namespace; } + return null; } @@ -236,6 +250,7 @@ protected static CimSession[] GetCimSession(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).CimSession; } + return null; } @@ -245,6 +260,7 @@ protected static String GetClassName(CimBaseCommand cmdlet) { return (cmdlet as GetCimInstanceCommand).ClassName; } + return null; } @@ -262,6 +278,7 @@ protected static String GetQuery(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).Query; } + return null; } @@ -276,6 +293,7 @@ internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) return true; } } + return false; } @@ -298,13 +316,16 @@ protected static String CreateQuery(CimBaseCommand cmdlet) { propertyList.Append(","); } + propertyList.Append(property); } } + return (cmd.Filter == null) ? String.Format(CultureInfo.CurrentUICulture, queryWithoutWhere, propertyList, cmd.ClassName) : String.Format(CultureInfo.CurrentUICulture, queryWithWhere, propertyList, cmd.ClassName, cmd.Filter); } + return null; } @@ -322,6 +343,7 @@ protected static String GetQueryDialect(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).QueryDialect; } + return null; } @@ -339,6 +361,7 @@ protected static CimInstance GetCimInstanceParameter(CimBaseCommand cmdlet) { return (cmdlet as SetCimInstanceCommand).CimInstance; } + return null; } #endregion @@ -375,6 +398,7 @@ private void SetSessionProxyProperties( { proxy.ResourceUri = removeCimInstance.ResourceUri; } + CimRemoveCimInstanceContext context = new CimRemoveCimInstanceContext( ConstValue.GetNamespace(removeCimInstance.Namespace), proxy); @@ -388,6 +412,7 @@ private void SetSessionProxyProperties( { proxy.ResourceUri = setCimInstance.ResourceUri; } + CimSetCimInstanceContext context = new CimSetCimInstanceContext( ConstValue.GetNamespace(setCimInstance.Namespace), setCimInstance.Property, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index c32c1f3a7b5..888a1efff4a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -31,6 +31,7 @@ public Object Context return context; } } + internal Object context; } @@ -51,6 +52,7 @@ public Exception Exception return exception; } } + private Exception exception; /// @@ -263,6 +265,7 @@ public bool EnableRaisingEvents { return enableRaisingEvents; } + set { DebugHelper.WriteLogEx(); @@ -273,6 +276,7 @@ public bool EnableRaisingEvents } } } + private bool enableRaisingEvents; /// @@ -306,6 +310,7 @@ public void Start() this.queryExpression, this.operationTimeout); } + status = Status.Started; } } @@ -329,6 +334,7 @@ public void Stop() DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4); this.cimRegisterCimIndication.Dispose(); } + status = Status.Stopped; } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index 33e7e1e9fc0..2c59d1d32cf 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -56,6 +56,7 @@ internal string MethodName return this.methodName; } } + private string methodName; /// @@ -68,6 +69,7 @@ internal CimMethodParametersCollection ParametersCollection return this.collection; } } + private CimMethodParametersCollection collection; } @@ -101,6 +103,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) { proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet)); } + break; case CimBaseCommand.ClassNameComputerSet: case CimBaseCommand.CimClassComputerSet: @@ -110,6 +113,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) { proxys.Add(CreateSessionProxy(computerName, cmdlet)); } + break; case CimBaseCommand.ClassNameSessionSet: case CimBaseCommand.CimClassSessionSet: @@ -121,10 +125,12 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) CimSessionProxy proxy = CreateSessionProxy(session, cmdlet); proxys.Add(proxy); } + break; default: break; } + CimMethodParametersCollection paramsCollection = CreateParametersCollection(cmdlet.Arguments, cmdlet.CimClass, cmdlet.CimInstance, cmdlet.MethodName); @@ -145,12 +151,14 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) { nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); } + foreach (CimSessionProxy proxy in proxys) { if (!cmdlet.ShouldProcess(target, action)) { return; } + proxy.InvokeMethodAsync( nameSpace, cmdlet.ClassName, @@ -158,6 +166,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) paramsCollection); } } + break; case CimBaseCommand.CimClassComputerSet: case CimBaseCommand.CimClassSessionSet: @@ -170,6 +179,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) { return; } + proxy.InvokeMethodAsync( nameSpace, cmdlet.CimClass.CimSystemProperties.ClassName, @@ -177,6 +187,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) paramsCollection); } } + break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: @@ -193,6 +204,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) // firstly query instance and then invoke method upon returned instances proxy.QueryInstancesAsync(nameSpace, ConstValue.GetQueryDialectWithDefault(cmdlet.QueryDialect), cmdlet.Query); } + break; case CimBaseCommand.CimInstanceComputerSet: case CimBaseCommand.CimInstanceSessionSet: @@ -206,12 +218,14 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) { nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace); } + foreach (CimSessionProxy proxy in proxys) { if (!cmdlet.ShouldProcess(target, action)) { return; } + proxy.InvokeMethodAsync( nameSpace, cmdlet.CimInstance, @@ -219,6 +233,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) paramsCollection); } } + break; default: break; @@ -394,6 +409,7 @@ private CimMethodParametersCollection CreateParametersCollection( throw new ArgumentException(String.Format( CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, parameterName, methodName, className)); } + parameter = CimMethodParameter.Create( parameterName, parameterValue, @@ -434,9 +450,11 @@ private CimMethodParametersCollection CreateParametersCollection( } } } + if (parameter != null) collection.Add(parameter); } + return collection; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index 7543e21a184..2babc5e2484 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -81,6 +81,7 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cmdlet); } + break; case CimBaseCommand.ResourceUriSessionSet: case CimBaseCommand.ResourceUriComputerSet: @@ -93,6 +94,7 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cmdlet); } + break; case CimBaseCommand.CimClassComputerSet: case CimBaseCommand.CimClassSessionSet: @@ -103,6 +105,7 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cmdlet); } + break; default: return; @@ -148,6 +151,7 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) proxys.Add(CreateSessionProxy(computerName, cmdlet)); } } + break; case CimBaseCommand.CimClassSessionSet: case CimBaseCommand.ClassNameSessionSet: @@ -156,6 +160,7 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) { proxys.Add(CreateSessionProxy(session, cmdlet)); } + break; } @@ -289,6 +294,7 @@ private CimInstance CreateCimInstance( { flag = CimFlags.Key; } + object propertyValue = GetBaseObject(enumerator.Value); DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); @@ -309,6 +315,7 @@ private CimInstance CreateCimInstance( } } + return cimInstance; } @@ -333,6 +340,7 @@ private CimInstance CreateCimInstance( { return cimInstance; } + List notfoundProperties = new List(); foreach (string property in properties.Keys) { @@ -342,9 +350,11 @@ private CimInstance CreateCimInstance( cmdlet.ThrowInvalidProperty(notfoundProperties, cmdlet.CimClass.CimSystemProperties.ClassName, @"Property", action, properties); return null; } + object propertyValue = GetBaseObject(properties[property]); cimInstance.CimInstanceProperties[property].Value = propertyValue; } + return cimInstance; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs index d8a49bd9857..6f5e5e07369 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -82,6 +82,7 @@ public override void Execute(CmdletOperationBase cmdlet) // unblocking the waiting thread this.OnComplete(); } + break; case CimPromptType.Normal: try @@ -106,10 +107,12 @@ public override void Execute(CmdletOperationBase cmdlet) // unblocking the waiting thread this.OnComplete(); } + break; default: break; } + this.OnComplete(); } @@ -125,6 +128,7 @@ public string Message return message; } } + private string message; /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 909f994a445..127489f66f9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -32,6 +32,7 @@ public Object Context return context; } } + protected Object context; } @@ -54,6 +55,7 @@ public CimSubscriptionResult Result return result; } } + private CimSubscriptionResult result; /// @@ -87,6 +89,7 @@ public Exception Exception return exception; } } + private Exception exception; /// @@ -169,6 +172,7 @@ public void RegisterCimIndication( { throw new ArgumentNullException(String.Format(CultureInfo.CurrentUICulture, Strings.NullArgument, @"cimSession")); } + this.TargetComputerName = cimSession.ComputerName; CimSessionProxy proxy = CreateSessionProxy(cimSession, operationTimeout); proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression); @@ -224,6 +228,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio this.ackedEvent.Set(); return; } + EventHandler temp = this.OnNewSubscriptionResult; if (temp != null) { @@ -231,6 +236,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio temp(this, new CimSubscriptionExceptionEventArgs(this.exception)); } + DebugHelper.WriteLog("Got an exception: {0}", 2, exception); } @@ -290,6 +296,7 @@ private void WaitForAckMessage() throw this.exception; } } + DebugHelper.WriteLogEx("ACK happened", 0); } #endregion @@ -364,6 +371,7 @@ internal Exception Exception return exception; } } + private Exception exception; #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs index c9454f8e6c8..9c6d5687667 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs @@ -70,16 +70,19 @@ public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet) { proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet)); } + break; case CimBaseCommand.CimInstanceSessionSet: foreach (CimSession session in GetCimSession(cmdlet)) { proxys.Add(CreateSessionProxy(session, cmdlet)); } + break; default: break; } + switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: @@ -93,6 +96,7 @@ public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet) { nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace); } + string target = cmdlet.CimInstance.ToString(); foreach (CimSessionProxy proxy in proxys) { @@ -100,8 +104,10 @@ public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet) { return; } + proxy.DeleteInstanceAsync(nameSpace, cmdlet.CimInstance); } + break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 8939e6d64e0..cc7ee1f35d8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -50,6 +50,7 @@ internal object ErrorSource return this.errorSource; } } + private object errorSource; } #endregion @@ -334,6 +335,7 @@ public virtual void OnNext(T value) { return; } + this.OnNextCore(value); } @@ -349,6 +351,7 @@ protected CimSession CurrentSession return session; } } + private CimSession session; /// @@ -466,6 +469,7 @@ public override void OnNext(CimMethodResultBase value) resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue)); } } + if (resultObject != null) { resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName)); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index c020ab6d5b8..deecc99f951 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -31,6 +31,7 @@ public uint SessionId return this.sessionId; } } + private uint sessionId; /// @@ -43,6 +44,7 @@ public Guid InstanceId return this.instanceId; } } + private Guid instanceId; /// @@ -55,6 +57,7 @@ public string Name return this.name; } } + private string name; /// @@ -67,6 +70,7 @@ public string ComputerName return this.computerName; } } + private string computerName; /// @@ -79,6 +83,7 @@ public CimSession CimSession return this.cimSession; } } + private CimSession cimSession; /// @@ -99,10 +104,12 @@ public string Protocol } } } + internal ProtocolType GetProtocolType() { return protocol; } + private ProtocolType protocol; /// @@ -148,6 +155,7 @@ internal PSObject GetPSObject() psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName; psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol; } + return psObject; } } @@ -358,6 +366,7 @@ public void Cleanup() { session.Dispose(); } + curCimSessionWrapper.Clear(); curCimSessionsByName.Clear(); curCimSessionsByComputerName.Clear(); @@ -397,6 +406,7 @@ internal PSObject AddObjectToCache( objects = new HashSet(); this.curCimSessionsByComputerName.Add(computerName, objects); } + objects.Add(wrapper); if (!this.curCimSessionsByName.TryGetValue(name, out objects)) @@ -404,6 +414,7 @@ internal PSObject AddObjectToCache( objects = new HashSet(); this.curCimSessionsByName.Add(name, objects); } + objects.Add(wrapper); this.curCimSessionsByInstanceId.Add(instanceId, wrapper); @@ -431,20 +442,25 @@ internal string GetRemoveSessionObjectTarget(PSObject psObject) { id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null); } + if (psObject.Properties[instanceidPropName].Value is Guid) { instanceId = (Guid)psObject.Properties[instanceidPropName].Value; } + if (psObject.Properties[namePropName].Value is String) { name = (String)psObject.Properties[namePropName].Value; } + if (psObject.Properties[computernamePropName].Value is String) { computerName = (String)psObject.Properties[computernamePropName].Value; } + message = String.Format(CultureInfo.CurrentUICulture, SessionObjectPath, id, instanceId, name, computerName); } + return message; } @@ -478,6 +494,7 @@ internal void RemoveOneSessionObjectFromCache(CimSession session) { return; } + CimSessionWrapper wrapper = this.curCimSessionWrapper[session]; String name = wrapper.Name; String computerName = wrapper.ComputerName; @@ -489,10 +506,12 @@ internal void RemoveOneSessionObjectFromCache(CimSession session) { objects.Remove(wrapper); } + if (this.curCimSessionsByName.TryGetValue(name, out objects)) { objects.Remove(wrapper); } + RemoveSessionInternal(session, wrapper); } @@ -566,6 +585,7 @@ internal IEnumerable QuerySession(IEnumerable ids, AddErrorRecord(ref errRecords, idPropName, id); } } + return sessions; } @@ -597,6 +617,7 @@ internal IEnumerable QuerySession(IEnumerable instanceIds, AddErrorRecord(ref errRecords, instanceidPropName, instanceid); } } + return sessions; } @@ -632,11 +653,13 @@ internal IEnumerable QuerySession(IEnumerable nameArray, } } } + if (!foundSession && !WildcardPattern.ContainsWildcardCharacters(name)) { AddErrorRecord(ref errRecords, namePropName, name); } } + return sessions; } @@ -669,11 +692,13 @@ internal IEnumerable QuerySessionByComputerName( } } } + if (!foundSession) { AddErrorRecord(ref errRecords, computernamePropName, computername); } } + return sessions; } @@ -705,6 +730,7 @@ internal IEnumerable QuerySession(IEnumerable cimsessions, AddErrorRecord(ref errRecords, CimSessionClassName, CimSessionObject); } } + return sessions; } @@ -732,6 +758,7 @@ internal CimSession QuerySession(Guid cimSessionInstanceId) CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[cimSessionInstanceId]; return wrapper.CimSession; } + return null; } #endregion @@ -766,6 +793,7 @@ public CimSessionBase() { Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged; } + return new CimSessionState(); }); } @@ -845,6 +873,7 @@ private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEve DebugHelper.WriteLog(String.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State)); state.Dispose(); } + runspace.StateChanged -= DefaultRunspace_StateChanged; break; default: @@ -900,6 +929,7 @@ internal CimSessionWrapper CimSessionWrapper return this.cimSessionWrapper; } } + private CimSessionWrapper cimSessionWrapper; } @@ -937,6 +967,7 @@ internal void NewCimSession(NewCimSessionCommand cmdlet, sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } + proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); @@ -1034,6 +1065,7 @@ protected bool Disposed return _disposed; } } + private bool _disposed; /// @@ -1122,6 +1154,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) { sessionToGet = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); } + break; case CimBaseCommand.SessionIdSet: sessionToGet = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); @@ -1135,6 +1168,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) default: break; } + if (sessionToGet != null) { foreach(PSObject psobject in sessionToGet) @@ -1142,6 +1176,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) cmdlet.WriteObject(psobject); } } + if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) @@ -1210,6 +1245,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) default: break; } + if (sessionToRemove != null) { foreach (PSObject psobject in sessionToRemove) @@ -1220,6 +1256,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) } } } + if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index b084c3408ca..aba1e469cd7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -39,6 +39,7 @@ internal string Namespace return this.nameSpace; } } + protected string nameSpace; /// @@ -53,6 +54,7 @@ internal CimSessionProxy Proxy return this.proxy; } } + protected CimSessionProxy proxy; } @@ -148,6 +150,7 @@ public CmdletActionEventArgs(CimBaseAction action) { this.Action = action; } + public readonly CimBaseAction Action; } @@ -169,6 +172,7 @@ public OperationEventArgs(IDisposable operationCancellation, this.operation = operation; this.success = theSuccess; } + public readonly IDisposable operationCancellation; public readonly IObservable operation; public readonly bool success; @@ -412,6 +416,7 @@ public CimSessionProxy(string computerName, CimInstance cimInstance) return; } } + String cimsessionComputerName = cimInstance.GetCimSessionComputerName(); CreateSetSession(cimsessionComputerName, null, null, null, false); this.isDefaultSession = (cimsessionComputerName == ConstValue.NullComputerName); @@ -484,6 +489,7 @@ private void CreateSetSession( this.CancelOperation = null; this.operation = null; } + InitOption(operOptions); this.protocol = ProtocolType.Wsman; this.isTemporaryCimSession = temporaryCimSession; @@ -520,6 +526,7 @@ private void CreateSetSession( { this.session = CreateCimSessionByComputerName(computerName); } + this.isTemporaryCimSession = true; } @@ -527,6 +534,7 @@ private void CreateSetSession( { AddCimSessionToTemporaryCache(this.session); } + this.invocationContextObject = new InvocationContext(this); DebugHelper.WriteLog("Protocol {0}, Is temporary session ? {1}", 1, this.protocol, this.isTemporaryCimSession); } @@ -546,6 +554,7 @@ public UInt32 OperationTimeout this.options.Timeout = TimeSpan.FromSeconds((double)value); } + get { return (UInt32)this.options.Timeout.TotalSeconds; @@ -563,6 +572,7 @@ public Uri ResourceUri this.options.ResourceUri= value; } + get { return this.options.ResourceUri; @@ -579,6 +589,7 @@ public bool EnableMethodResultStreaming { return this.options.EnableMethodResultStreaming; } + set { DebugHelper.WriteLogEx("EnableMethodResultStreaming {0}", 0, value); @@ -663,6 +674,7 @@ private void InitOption(CimOperationOptions operOptions) { this.options = new CimOperationOptions(); } + this.EnableMethodResultStreaming = true; this.EnablePSSemantics(); } @@ -722,6 +734,7 @@ private void RemoveOperation(IObservable operation) { this.operation = null; } + if (this.session != null && this.ContextObject == null) { DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation"); @@ -755,6 +768,7 @@ protected void FireNewActionEvent(CimBaseAction action) { DebugHelper.WriteLog("Ignore action since OnNewCmdletAction is null.", 5); } + this.PostNewActionEvent(actionArgs); } @@ -778,6 +792,7 @@ private void FireOperationCreatedEvent( { temp(this.session, args); } + this.PostOperationCreateEvent(args); } @@ -801,6 +816,7 @@ private void FireOperationDeletedEvent( { temp(this.session, args); } + this.PostOperationDeleteEvent(args); this.RemoveOperation(operation); this.operationName = null; @@ -850,9 +866,11 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi { parameters.Append(","); } + parameters.Append(string.Format(CultureInfo.CurrentUICulture, @"'{0}' = {1}", key, parameterList[key])); } } + string operationStartMessage = string.Format(CultureInfo.CurrentUICulture, Strings.CimOperationStart, operation, @@ -980,6 +998,7 @@ internal void ResultEventHandler( AsyncResultCompleteEventArgs args = resultArgs as AsyncResultCompleteEventArgs; this.FireOperationDeletedEvent(args.observable, true); } + break; case AsyncResultType.Exception: { @@ -990,8 +1009,10 @@ internal void ResultEventHandler( { this.FireNewActionEvent(action); } + this.FireOperationDeletedEvent(args.observable, false); } + break; case AsyncResultType.Result: { @@ -1002,6 +1023,7 @@ internal void ResultEventHandler( { AddShowComputerNameMarker(resultObject); } + if (this.ObjectPreProcess != null) { resultObject = this.ObjectPreProcess.Process(resultObject); @@ -1012,6 +1034,7 @@ internal void ResultEventHandler( CimWriteResultObject action = new CimWriteResultObject(resultObject, this.ContextObject); this.FireNewActionEvent(action); } + break; default: break; @@ -1047,6 +1070,7 @@ private static bool GetIsCliXmlTestabilityHookActive() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CDXML_CLIXML_TEST")); } + private object PostProcessCimInstance(object resultObject) { DebugHelper.WriteLogEx(); @@ -1058,6 +1082,7 @@ private object PostProcessCimInstance(object resultObject) DebugHelper.WriteLogEx("Deserialized Object is {0}, type {1}", 1, returnObject, returnObject.GetType()); return returnObject; } + return resultObject; } #endif @@ -1468,6 +1493,7 @@ internal CimSession CimSession return this.session; } } + private CimSession session; /// @@ -1481,6 +1507,7 @@ internal CimInstance TargetCimInstance return this.targetCimInstance; } } + private CimInstance targetCimInstance = null; /// @@ -1510,6 +1537,7 @@ internal CimOperationOptions OperationOptions return this.options; } } + private CimOperationOptions options; /// @@ -1579,6 +1607,7 @@ private IDisposable CancelOperation this._cancelOperation = value; Interlocked.Exchange(ref this._cancelOperationDisposed, 0); } + get { return this._cancelOperation; @@ -1596,6 +1625,7 @@ internal ProtocolType Protocol return protocol; } } + private ProtocolType protocol; /// @@ -1607,11 +1637,13 @@ internal XOperationContextBase ContextObject { this.contextObject = value; } + get { return this.contextObject; } } + private XOperationContextBase contextObject; /// @@ -1629,11 +1661,13 @@ internal IObjectPreProcess ObjectPreProcess { this.objectPreprocess = value; } + get { return this.objectPreprocess; } } + private IObjectPreProcess objectPreprocess; /// @@ -1689,6 +1723,7 @@ protected virtual void Dispose(bool disposing) this.options.Dispose(); this.options = null; } + DisposeTemporaryCimSession(); } } @@ -1870,6 +1905,7 @@ private void CheckAvailability() throw new InvalidOperationException(Strings.OperationInProgress); } } + DebugHelper.WriteLog("KeyOnly {0},", 1, this.options.KeysOnly); } @@ -1937,14 +1973,17 @@ internal static CimSessionOptions CreateCimSessionOption(string computerName, DebugHelper.WriteLog("<<<<<<<<<< Use protocol WSMAN {0}", 1, computerName); option = new WSManSessionOptions(); } + if (timeout != 0) { option.Timeout = TimeSpan.FromSeconds((double)timeout); } + if (credential != null) { option.AddDestinationCredentials(credential); } + DebugHelper.WriteLogEx("returned option :{0}.", 1, option); return option; } @@ -2072,6 +2111,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) return false; } } + if (context.PropertyName != null) { pattern = new WildcardPattern(context.PropertyName, WildcardOptions.IgnoreCase); @@ -2095,6 +2135,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) return match; } } + if (context.MethodName != null) { pattern = new WildcardPattern(context.MethodName, WildcardOptions.IgnoreCase); @@ -2118,6 +2159,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) return match; } } + if (context.QualifierName != null) { pattern = new WildcardPattern(context.QualifierName, WildcardOptions.IgnoreCase); @@ -2141,6 +2183,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) return match; } } + DebugHelper.WriteLog("CimClass '{0}' is qualified.", 1, cimClass.CimSystemProperties.ClassName); return true; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index c8ab7fa01b2..aba46b4095b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -50,6 +50,7 @@ internal IDictionary Property return this.property; } } + private IDictionary property; /// @@ -62,6 +63,7 @@ internal string ParameterSetName return this.parameterSetName; } } + private string parameterSetName; /// @@ -74,6 +76,7 @@ internal bool PassThru return this.passThru; } } + private bool passThru; } @@ -113,6 +116,7 @@ public void SetCimInstance(SetCimInstanceCommand cmdlet) // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet, cmdlet.PassThru)); } + break; case CimBaseCommand.CimInstanceSessionSet: foreach (CimSession session in GetCimSession(cmdlet)) @@ -120,10 +124,12 @@ public void SetCimInstance(SetCimInstanceCommand cmdlet) // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(session, cmdlet, cmdlet.PassThru)); } + break; default: break; } + switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: @@ -148,8 +154,10 @@ public void SetCimInstance(SetCimInstanceCommand cmdlet) return; } } + proxy.ModifyInstanceAsync(nameSpace, instance); } + break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: @@ -181,6 +189,7 @@ public void SetCimInstance(CimInstance cimInstance, CimSetCimInstanceContext con cmdlet.ThrowTerminatingError(exception, action); return; } + CimSessionProxy proxy = CreateCimSessionProxy(context.Proxy, context.PassThru); proxy.ModifyInstanceAsync(cimInstance.CimSystemProperties.Namespace, cimInstance); } @@ -205,6 +214,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re // simply ignore if empty properties was provided return true; } + IDictionaryEnumerator enumerator = properties.GetEnumerator(); while (enumerator.MoveNext()) { @@ -261,6 +271,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re CimFlags.Property); } } + try { cimInstance.CimInstanceProperties.Add(newProperty); @@ -279,8 +290,10 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re { exception = e; } + return false; } + DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value); } } @@ -291,6 +304,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re return false; } } + return true; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index 90d893e6910..ac2bb33f001 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -129,6 +129,7 @@ internal static ErrorRecord InitializeErrorRecord( { errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; } + return errorRecord; } @@ -153,6 +154,7 @@ internal static ErrorRecord InitializeErrorRecordCore( { theTargetObject = cimResultContext.ErrorSource; } + if (theTargetObject == null) { if (context != null) @@ -163,6 +165,7 @@ internal static ErrorRecord InitializeErrorRecordCore( } } } + ErrorRecord coreErrorRecord = new ErrorRecord( exception: exception, errorId: errorId, @@ -394,6 +397,7 @@ internal Exception Exception return exception; } } + private Exception exception; /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 67f3250c282..507a6b37f2b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -54,6 +54,7 @@ public CimWriteProgress( { this.statusDescription = theStatusDescription; } + this.percentageCompleted = thePercentageCompleted; this.secondsRemaining = theSecondsRemaining; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs index 48310add1a2..86dcf89244b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -46,6 +46,7 @@ internal object Result return result; } } + private object result; #endregion }//End Class diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index ab87b0676ab..80ea2dd0e66 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -40,58 +40,72 @@ public virtual bool ShouldContinue(string query, string caption) { return cmdlet.ShouldContinue(query, caption); } + public virtual bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) { return cmdlet.ShouldContinue(query, caption, ref yesToAll, ref noToAll); } + public virtual bool ShouldProcess(string target) { return cmdlet.ShouldProcess(target); } + public virtual bool ShouldProcess(string target, string action) { return cmdlet.ShouldProcess(target, action); } + public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) { return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption); } + public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); } + public virtual void ThrowTerminatingError(ErrorRecord errorRecord) { cmdlet.ThrowTerminatingError(errorRecord); } + public virtual void WriteCommandDetail(string text) { cmdlet.WriteCommandDetail(text); } + public virtual void WriteDebug(string text) { cmdlet.WriteDebug(text); } + public virtual void WriteError(ErrorRecord errorRecord) { cmdlet.WriteError(errorRecord); } + public virtual void WriteObject(object sendToPipeline, XOperationContextBase context) { cmdlet.WriteObject(sendToPipeline); } + public virtual void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context) { cmdlet.WriteObject(sendToPipeline, enumerateCollection); } + public virtual void WriteProgress(ProgressRecord progressRecord) { cmdlet.WriteProgress(progressRecord); } + public virtual void WriteVerbose(string text) { cmdlet.WriteVerbose(text); } + public virtual void WriteWarning(string text) { cmdlet.WriteWarning(text); @@ -236,6 +250,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co DebugHelper.WriteLog("Assert. CimSetCimInstance::SetCimInstance has NULL CimSetCimInstanceContext", 4); } } + base.WriteObject(sendToPipeline, context); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index babb12d0403..2fa2a9140b8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -55,8 +55,10 @@ public GetCimAssociatedInstanceCommand() public String Association { get { return association; } + set { association = value; } } + private String association; /// @@ -68,8 +70,10 @@ public String Association public String ResultClassName { get { return resultClassName; } + set { resultClassName = value; } } + private String resultClassName; /// @@ -86,6 +90,7 @@ public String ResultClassName public CimInstance InputObject { get { return cimInstance; } + set { cimInstance = value; @@ -100,6 +105,7 @@ internal CimInstance CimInstance { get { return cimInstance; } } + private CimInstance cimInstance; /// @@ -111,8 +117,10 @@ internal CimInstance CimInstance public String Namespace { get { return nameSpace; } + set { nameSpace = value; } } + private String nameSpace; /// @@ -127,8 +135,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -141,12 +151,14 @@ public UInt32 OperationTimeoutSec public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -167,12 +179,14 @@ public Uri ResourceUri public String[] ComputerName { get { return computerName; } + set { computerName = value; base.SetParameter(value, nameComputerName); } } + private String[] computerName; /// @@ -187,12 +201,14 @@ public String[] ComputerName public Microsoft.Management.Infrastructure.CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private Microsoft.Management.Infrastructure.CimSession[] cimSession; /// @@ -206,8 +222,10 @@ public Microsoft.Management.Infrastructure.CimSession[] CimSession public SwitchParameter KeyOnly { get { return keyOnly; } + set { keyOnly = value; } } + private SwitchParameter keyOnly; #endregion @@ -234,6 +252,7 @@ protected override void ProcessRecord() { operation = this.CreateOperationAgent(); } + operation.GetCimAssociatedInstance(this); operation.ProcessActions(this.CmdletOperation); }//End ProcessRecord() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index 21425d7b63a..c1471321101 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -56,8 +56,10 @@ public GetCimClassCommand() public String ClassName { get { return className; } + set { className = value; } } + private String className; /// @@ -77,8 +79,10 @@ public String ClassName public String Namespace { get { return nameSpace; } + set { nameSpace = value; } } + private String nameSpace; /// @@ -91,8 +95,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout;} + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -107,12 +113,14 @@ public UInt32 OperationTimeoutSec public CimSession[] CimSession { get { return cimSession;} + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -131,12 +139,14 @@ public CimSession[] CimSession public String[] ComputerName { get { return computerName; } + set { computerName = value; base.SetParameter(value, nameComputerName); } } + private String[] computerName; /// @@ -150,8 +160,10 @@ public String[] ComputerName public String MethodName { get { return methodName; } + set { methodName = value; } } + private String methodName; /// @@ -165,8 +177,10 @@ public String MethodName public String PropertyName { get { return propertyName; } + set { propertyName = value; } } + private String propertyName; /// @@ -180,8 +194,10 @@ public String PropertyName public String QualifierName { get { return qualifierName; } + set { qualifierName = value; } } + private String qualifierName; #endregion @@ -208,6 +224,7 @@ protected override void ProcessRecord() { cimGetCimClass = CreateOperationAgent(); } + cimGetCimClass.GetCimClass(this); cimGetCimClass.ProcessActions(this.CmdletOperation); }//End ProcessRecord() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index f9a3b21db4a..0b7c579e7a2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -63,12 +63,14 @@ public GetCimInstanceCommand() public CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -88,12 +90,14 @@ public CimSession[] CimSession public String ClassName { get { return className; } + set { this.className = value; base.SetParameter(value, nameClassName); } } + private String className; /// @@ -121,12 +125,14 @@ public String ClassName public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -155,12 +161,14 @@ public Uri ResourceUri public String[] ComputerName { get { return computerName; } + set { computerName = value; base.SetParameter(value, nameComputerName); } } + private String[] computerName; /// @@ -177,12 +185,14 @@ public String[] ComputerName public SwitchParameter KeyOnly { get { return keyOnly; } + set { keyOnly = value; base.SetParameter(value, nameKeyOnly); } } + private SwitchParameter keyOnly; /// @@ -210,12 +220,14 @@ public SwitchParameter KeyOnly public String Namespace { get { return nameSpace; } + set { nameSpace = value; base.SetParameter(value, nameNamespace); } } + private String nameSpace; /// @@ -232,8 +244,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -263,6 +277,7 @@ public UInt32 OperationTimeoutSec public CimInstance InputObject { get { return cimInstance; } + set { cimInstance = value; @@ -277,6 +292,7 @@ internal CimInstance CimInstance { get { return cimInstance; } } + private CimInstance cimInstance; /// @@ -293,12 +309,14 @@ internal CimInstance CimInstance public String Query { get { return query; } + set { query = value; base.SetParameter(value, nameQuery); } } + private String query; /// @@ -320,12 +338,14 @@ public String Query public String QueryDialect { get { return queryDialect; } + set { queryDialect = value; base.SetParameter(value, nameQueryDialect); } } + private String queryDialect; /// @@ -346,12 +366,14 @@ public String QueryDialect public SwitchParameter Shallow { get { return shallow; } + set { shallow = value; base.SetParameter(value, nameShallow); } } + private SwitchParameter shallow; /// @@ -371,12 +393,14 @@ public SwitchParameter Shallow public String Filter { get { return filter; } + set { filter = value; base.SetParameter(value, nameFilter); } } + private String filter; /// @@ -398,6 +422,7 @@ public String Filter public String[] Property { get { return property; } + set { property = value; @@ -411,6 +436,7 @@ internal String[] SelectProperties { get { return property; } } + private String[] property; #endregion @@ -438,6 +464,7 @@ protected override void ProcessRecord() { cimGetInstance = CreateOperationAgent(); } + cimGetInstance.GetCimInstance(this); cimGetInstance.ProcessActions(this.CmdletOperation); }//End ProcessRecord() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index 628ea348115..a4e1013bd78 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -59,12 +59,14 @@ public GetCimSessionCommand() public String[] ComputerName { get { return computername;} + set { computername = value; base.SetParameter(value, nameComputerName); } } + private String[] computername; /// @@ -79,12 +81,14 @@ public String[] ComputerName public UInt32[] Id { get { return id;} + set { id = value; base.SetParameter(value, nameId); } } + private UInt32[] id; /// @@ -98,12 +102,14 @@ public UInt32[] Id public Guid[] InstanceId { get { return instanceid;} + set { instanceid = value; base.SetParameter(value, nameInstanceId); } } + private Guid[] instanceid; /// @@ -118,12 +124,14 @@ public Guid[] InstanceId public String[] Name { get { return name;} + set { name = value; base.SetParameter(value, nameName); } } + private String[] name; #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index 0b619f87a7a..09270d218fb 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -55,12 +55,14 @@ public InvokeCimMethodCommand() public String ClassName { get { return className; } + set { className = value; base.SetParameter(value, nameClassName); } } + private String className; /// @@ -82,12 +84,14 @@ public String ClassName public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -105,12 +109,14 @@ public Uri ResourceUri public CimClass CimClass { get { return cimClass; } + set { cimClass = value; base.SetParameter(value, nameCimClass); } } + private CimClass cimClass; /// @@ -126,12 +132,14 @@ public CimClass CimClass public string Query { get { return query; } + set { query = value; base.SetParameter(value, nameQuery); } } + private string query; /// @@ -148,12 +156,14 @@ public string Query public String QueryDialect { get { return queryDialect; } + set { queryDialect = value; base.SetParameter(value, nameQueryDialect); } } + private String queryDialect; /// @@ -173,6 +183,7 @@ public String QueryDialect public CimInstance InputObject { get { return cimInstance; } + set { cimInstance = value; @@ -187,6 +198,7 @@ internal CimInstance CimInstance { get { return cimInstance; } } + private CimInstance cimInstance; /// @@ -218,6 +230,7 @@ internal CimInstance CimInstance public String[] ComputerName { get { return computerName; } + set { DebugHelper.WriteLogEx(); @@ -225,6 +238,7 @@ public String[] ComputerName base.SetParameter(value, nameComputerName); } } + private String[] computerName; /// @@ -256,12 +270,14 @@ public String[] ComputerName public CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -274,8 +290,10 @@ public CimSession[] CimSession public IDictionary Arguments { get { return arguments; } + set { arguments = value; } } + private IDictionary arguments; /// @@ -289,12 +307,14 @@ public IDictionary Arguments public String MethodName { get { return methodName; } + set { methodName = value; base.SetParameter(value, nameMethodName); } } + private String methodName; /// @@ -318,12 +338,14 @@ public String MethodName public String Namespace { get { return nameSpace; } + set { nameSpace = value; base.SetParameter(value, nameNamespace); } } + private String nameSpace; /// @@ -336,8 +358,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; #endregion @@ -354,6 +378,7 @@ protected override void BeginProcessing() { cimInvokeMethod = CreateOperationAgent(); } + this.CmdletOperation = new CmdletOperationInvokeCimMethod(this, cimInvokeMethod); this.AtBeginProcess = false; }//End BeginProcessing() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index b4fa211dbef..06b267d9da2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -57,12 +57,14 @@ public NewCimInstanceCommand() public String ClassName { get { return className; } + set { className = value; base.SetParameter(value, nameClassName); } } + private String className; /// @@ -80,12 +82,14 @@ public String ClassName public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -113,12 +117,14 @@ public Uri ResourceUri public String[] Key { get { return key; } + set { key = value; base.SetParameter(value, nameKey); } } + private String[] key; /// @@ -138,12 +144,14 @@ public String[] Key public CimClass CimClass { get { return cimClass; } + set { cimClass = value; base.SetParameter(value, nameCimClass); } } + private CimClass cimClass; /// @@ -163,8 +171,10 @@ public CimClass CimClass public IDictionary Property { get { return property; } + set { property = value; } } + private IDictionary property; /// @@ -187,12 +197,14 @@ public IDictionary Property public String Namespace { get { return nameSpace; } + set { nameSpace = value; base.SetParameter(value, nameNamespace); } } + private String nameSpace; /// @@ -205,8 +217,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -231,12 +245,14 @@ public UInt32 OperationTimeoutSec public CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -261,12 +277,14 @@ public CimSession[] CimSession public String[] ComputerName { get { return computerName; } + set { computerName = value; base.SetParameter(value, nameComputerName); } } + private String[] computerName; /// @@ -287,11 +305,13 @@ public String[] ComputerName public SwitchParameter ClientOnly { get { return clientOnly; } + set { clientOnly = value; base.SetParameter(value, nameClientOnly); } } + private SwitchParameter clientOnly; #endregion @@ -325,6 +345,7 @@ protected override void ProcessRecord() { conflictParameterName = @"CimSession"; } + if (conflictParameterName != null) { ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly"); @@ -337,6 +358,7 @@ protected override void ProcessRecord() { cimNewCimInstance = CreateOperationAgent(); } + cimNewCimInstance.NewCimInstance(this); cimNewCimInstance.ProcessActions(this.CmdletOperation); }//End ProcessRecord() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index a9cfe00ee49..eb8935b2b79 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -33,12 +33,14 @@ public sealed class NewCimSessionCommand : CimBaseCommand public PasswordAuthenticationMechanism Authentication { get { return authentication;} + set { authentication = value; authenticationSet = true; } } + private PasswordAuthenticationMechanism authentication; private bool authenticationSet = false; @@ -52,8 +54,10 @@ public PasswordAuthenticationMechanism Authentication public PSCredential Credential { get { return credential; } + set { credential = value; } } + private PSCredential credential; /// @@ -65,8 +69,10 @@ public PSCredential Credential public String CertificateThumbprint { get { return certificatethumbprint; } + set { certificatethumbprint = value; } } + private String certificatethumbprint; /// @@ -83,8 +89,10 @@ public String CertificateThumbprint public String[] ComputerName { get { return computername;} + set { computername = value; } } + private String[] computername; /// @@ -102,8 +110,10 @@ public String[] ComputerName public String Name { get { return name;} + set { name = value; } } + private String name; /// @@ -121,12 +131,14 @@ public String Name public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; operationTimeoutSet = true; } } + private UInt32 operationTimeout; internal bool operationTimeoutSet = false; @@ -140,11 +152,13 @@ public UInt32 OperationTimeoutSec public SwitchParameter SkipTestConnection { get { return skipTestConnection; } + set { skipTestConnection = value; } } + private SwitchParameter skipTestConnection; /// @@ -156,12 +170,14 @@ public SwitchParameter SkipTestConnection public UInt32 Port { get { return port; } + set { port = value; portSet = true; } } + private UInt32 port; private bool portSet = false; @@ -182,8 +198,10 @@ public UInt32 Port public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption { get { return sessionOption; } + set { sessionOption = value; } } + private Microsoft.Management.Infrastructure.Options.CimSessionOptions sessionOption; #endregion @@ -244,6 +262,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr options = new DComSessionOptions(this.sessionOption as DComSessionOptions); } } + outputOptions = null; outputCredential = null; if (options != null) @@ -258,11 +277,13 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr conflict = true; parameterName = @"CertificateThumbprint"; } + if (portSet) { conflict = true; parameterName = @"Port"; } + if (conflict) { ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions"); @@ -270,6 +291,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr } } } + if (portSet || (this.CertificateThumbprint != null)) { WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions; @@ -278,13 +300,16 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr wsmanOptions.DestinationPort = this.Port; portSet = false; } + if (this.CertificateThumbprint != null) { CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint); wsmanOptions.AddDestinationCredentials(credentials); } + options = wsmanOptions; } + if (this.operationTimeoutSet) { if (options != null) @@ -292,6 +317,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec); } } + if (this.authenticationSet || (this.credential != null)) { PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default; @@ -299,6 +325,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr { this.authenticationSet = false; } + CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication"); if (credentials == null) { @@ -313,6 +340,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr options.AddDestinationCredentials(credentials); } } + DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions); outputOptions = options; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index 9bdc9c6c608..d50a90df261 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -62,6 +62,7 @@ public NewCimSessionOptionCommand() public SwitchParameter NoEncryption { get { return noEncryption; } + set { noEncryption = value; @@ -69,6 +70,7 @@ public SwitchParameter NoEncryption base.SetParameter(value, nameNoEncryption); } } + private SwitchParameter noEncryption; private bool noEncryptionSet = false; @@ -81,6 +83,7 @@ public SwitchParameter NoEncryption public SwitchParameter SkipCACheck { get { return skipCACheck; } + set { skipCACheck = value; @@ -88,6 +91,7 @@ public SwitchParameter SkipCACheck base.SetParameter(value, nameSkipCACheck); } } + private SwitchParameter skipCACheck; private bool skipCACheckSet = false; @@ -100,6 +104,7 @@ public SwitchParameter SkipCACheck public SwitchParameter SkipCNCheck { get { return skipCNCheck; } + set { skipCNCheck = value; @@ -107,6 +112,7 @@ public SwitchParameter SkipCNCheck base.SetParameter(value, nameSkipCNCheck); } } + private SwitchParameter skipCNCheck; private bool skipCNCheckSet = false; @@ -119,6 +125,7 @@ public SwitchParameter SkipCNCheck public SwitchParameter SkipRevocationCheck { get { return skipRevocationCheck; } + set { skipRevocationCheck = value; @@ -126,6 +133,7 @@ public SwitchParameter SkipRevocationCheck base.SetParameter(value, nameSkipRevocationCheck); } } + private SwitchParameter skipRevocationCheck; private bool skipRevocationCheckSet = false; @@ -138,6 +146,7 @@ public SwitchParameter SkipRevocationCheck public SwitchParameter EncodePortInServicePrincipalName { get { return encodeportinserviceprincipalname; } + set { encodeportinserviceprincipalname = value; @@ -145,6 +154,7 @@ public SwitchParameter EncodePortInServicePrincipalName base.SetParameter(value, nameEncodePortInServicePrincipalName); } } + private SwitchParameter encodeportinserviceprincipalname; private bool encodeportinserviceprincipalnameSet = false; @@ -159,6 +169,7 @@ public SwitchParameter EncodePortInServicePrincipalName public PacketEncoding Encoding { get { return encoding; } + set { encoding = value; @@ -166,6 +177,7 @@ public PacketEncoding Encoding base.SetParameter(value, nameEncoding); } } + private PacketEncoding encoding; private bool encodingSet = false; @@ -179,12 +191,14 @@ public PacketEncoding Encoding public Uri HttpPrefix { get { return httpprefix; } + set { httpprefix = value; base.SetParameter(value, nameHttpPrefix); } } + private Uri httpprefix; /// @@ -196,6 +210,7 @@ public Uri HttpPrefix public UInt32 MaxEnvelopeSizeKB { get { return maxenvelopesizekb; } + set { maxenvelopesizekb = value; @@ -203,6 +218,7 @@ public UInt32 MaxEnvelopeSizeKB base.SetParameter(value, nameMaxEnvelopeSizeKB); } } + private UInt32 maxenvelopesizekb; private bool maxenvelopesizekbSet = false; @@ -215,6 +231,7 @@ public UInt32 MaxEnvelopeSizeKB public PasswordAuthenticationMechanism ProxyAuthentication { get { return proxyAuthentication; } + set { proxyAuthentication = value; @@ -222,6 +239,7 @@ public PasswordAuthenticationMechanism ProxyAuthentication base.SetParameter(value, nameProxyAuthentication); } } + private PasswordAuthenticationMechanism proxyAuthentication; private bool proxyauthenticationSet = false; @@ -233,12 +251,14 @@ public PasswordAuthenticationMechanism ProxyAuthentication public String ProxyCertificateThumbprint { get { return proxycertificatethumbprint; } + set { proxycertificatethumbprint = value; base.SetParameter(value, nameProxyCertificateThumbprint); } } + private String proxycertificatethumbprint; /// @@ -250,12 +270,14 @@ public String ProxyCertificateThumbprint public PSCredential ProxyCredential { get { return proxycredential; } + set { proxycredential = value; base.SetParameter(value, nameProxyCredential); } } + private PSCredential proxycredential; /// @@ -268,6 +290,7 @@ public PSCredential ProxyCredential public ProxyType ProxyType { get { return proxytype; } + set { proxytype = value; @@ -275,6 +298,7 @@ public ProxyType ProxyType base.SetParameter(value, nameProxyType); } } + private ProxyType proxytype; private bool proxytypeSet = false; @@ -287,6 +311,7 @@ public ProxyType ProxyType public SwitchParameter UseSsl { get { return usessl; } + set { usessl = value; @@ -294,6 +319,7 @@ public SwitchParameter UseSsl base.SetParameter(value, nameUseSsl); } } + private SwitchParameter usessl; private bool usesslSet = false; @@ -306,6 +332,7 @@ public SwitchParameter UseSsl public ImpersonationType Impersonation { get { return impersonation; } + set { impersonation = value; @@ -313,6 +340,7 @@ public ImpersonationType Impersonation base.SetParameter(value, nameImpersonation); } } + private ImpersonationType impersonation; private bool impersonationSet = false; @@ -325,6 +353,7 @@ public ImpersonationType Impersonation public SwitchParameter PacketIntegrity { get { return packetintegrity; } + set { packetintegrity = value; @@ -332,6 +361,7 @@ public SwitchParameter PacketIntegrity base.SetParameter(value, namePacketIntegrity); } } + private SwitchParameter packetintegrity; private bool packetintegritySet = false; @@ -344,6 +374,7 @@ public SwitchParameter PacketIntegrity public SwitchParameter PacketPrivacy { get { return packetprivacy; } + set { packetprivacy = value; @@ -351,6 +382,7 @@ public SwitchParameter PacketPrivacy base.SetParameter(value, namePacketPrivacy); } } + private SwitchParameter packetprivacy; private bool packetprivacySet = false; @@ -366,12 +398,14 @@ public SwitchParameter PacketPrivacy public ProtocolType Protocol { get { return protocol; } + set { protocol = value; base.SetParameter(value, nameProtocol); } } + private ProtocolType protocol; /// @@ -382,8 +416,10 @@ public ProtocolType Protocol public CultureInfo UICulture { get { return uiculture; } + set { uiculture = value; } } + private CultureInfo uiculture; /// @@ -394,8 +430,10 @@ public CultureInfo UICulture public CultureInfo Culture { get { return culture; } + set { culture = value; } } + private CultureInfo culture; #endregion @@ -424,11 +462,13 @@ protected override void ProcessRecord() { options = CreateWSMANSessionOptions(); } + break; case DcomParameterSet: { options = CreateDComSessionOptions(); } + break; case ProtocolNameParameterSet: switch (Protocol) @@ -441,20 +481,24 @@ protected override void ProcessRecord() options = CreateWSMANSessionOptions(); break; } + break; default: return; } + if (options != null) { if (this.Culture != null) { options.Culture = this.Culture; } + if (this.UICulture != null) { options.UICulture = this.UICulture; } + this.WriteObject(options); } }//End ProcessRecord() @@ -485,6 +529,7 @@ internal DComSessionOptions CreateDComSessionOptions() { dcomoptions.Impersonation = ImpersonationType.Impersonate; } + if (this.packetintegritySet) { dcomoptions.PacketIntegrity = this.packetintegrity; @@ -494,6 +539,7 @@ internal DComSessionOptions CreateDComSessionOptions() { dcomoptions.PacketIntegrity = true; } + if (this.packetprivacySet) { dcomoptions.PacketPrivacy = this.PacketPrivacy; @@ -503,6 +549,7 @@ internal DComSessionOptions CreateDComSessionOptions() { dcomoptions.PacketPrivacy = true; } + return dcomoptions; } @@ -522,6 +569,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.NoEncryption = false; } + if (this.skipCACheckSet) { wsmanoptions.CertCACheck = false; @@ -531,6 +579,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.CertCACheck = true; } + if (this.skipCNCheckSet) { wsmanoptions.CertCNCheck = false; @@ -540,6 +589,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.CertCNCheck = true; } + if (this.skipRevocationCheckSet) { wsmanoptions.CertRevocationCheck = false; @@ -549,6 +599,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.CertRevocationCheck = true; } + if (this.encodeportinserviceprincipalnameSet) { wsmanoptions.EncodePortInServicePrincipalName = this.EncodePortInServicePrincipalName; @@ -558,6 +609,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.EncodePortInServicePrincipalName = false; } + if (this.encodingSet) { wsmanoptions.PacketEncoding = this.Encoding; @@ -566,10 +618,12 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.PacketEncoding = PacketEncoding.Utf8; } + if (this.HttpPrefix != null) { wsmanoptions.HttpUrlPrefix = this.HttpPrefix; } + if (this.maxenvelopesizekbSet) { wsmanoptions.MaxEnvelopeSize = this.MaxEnvelopeSizeKB; @@ -578,11 +632,13 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.MaxEnvelopeSize = 0; } + if (!String.IsNullOrWhiteSpace(this.ProxyCertificateThumbprint)) { CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.ProxyCertificateThumbprint); wsmanoptions.AddProxyCredentials(credentials); } + if (this.proxyauthenticationSet) { this.proxyauthenticationSet = false; @@ -602,6 +658,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() } } } + if (this.proxytypeSet) { wsmanoptions.ProxyType = this.ProxyType; @@ -611,6 +668,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.ProxyType = Options.ProxyType.WinHttp; } + if (this.usesslSet) { wsmanoptions.UseSsl = this.UseSsl; @@ -620,6 +678,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() { wsmanoptions.UseSsl = false; } + wsmanoptions.DestinationPort = 0; return wsmanoptions; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index ec3005062b8..dd73cb44762 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -37,8 +37,10 @@ public class RegisterCimIndicationCommand : ObjectEventRegistrationBase public String Namespace { get { return nameSpace; } + set { nameSpace = value; } } + private String nameSpace; /// @@ -55,12 +57,14 @@ public String Namespace public String ClassName { get { return className; } + set { className = value; this.SetParameter(value, nameClassName); } } + private String className; /// @@ -78,12 +82,14 @@ public String ClassName public String Query { get { return query; } + set { query = value; this.SetParameter(value, nameQuery); } } + private String query; /// @@ -98,12 +104,14 @@ public String Query public String QueryDialect { get { return queryDialect; } + set { queryDialect = value; this.SetParameter(value, nameQueryDialect); } } + private String queryDialect; /// @@ -116,8 +124,10 @@ public String QueryDialect public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -133,12 +143,14 @@ public UInt32 OperationTimeoutSec public CimSession CimSession { get { return cimSession; } + set { cimSession = value; this.SetParameter(value, nameCimSession); } } + private CimSession cimSession; /// @@ -152,12 +164,14 @@ public CimSession CimSession public String ComputerName { get { return computername; } + set { computername = value; this.SetParameter(value, nameComputerName); } } + private String computername; #endregion @@ -177,6 +191,7 @@ protected override Object GetSourceObject() { this.parameterBinder.reset(); } + string tempQueryExpression = string.Empty; switch (parameterSetName) { @@ -191,6 +206,7 @@ protected override Object GetSourceObject() tempQueryExpression = String.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); break; } + switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: @@ -198,18 +214,22 @@ protected override Object GetSourceObject() { watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } + break; case CimBaseCommand.QueryExpressionComputerSet: case CimBaseCommand.ClassNameComputerSet: { watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } + break; } + if (watcher != null) { watcher.SetCmdlet(this); } + return watcher; } @@ -284,6 +304,7 @@ private void SetParameter(object value, string parameterName) { return; } + this.parameterBinder.SetParameter(parameterName, true); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index eb815411193..ef255288d7f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -53,12 +53,14 @@ public RemoveCimInstanceCommand() public CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -74,12 +76,14 @@ public CimSession[] CimSession public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -95,12 +99,14 @@ public Uri ResourceUri public String[] ComputerName { get { return computername; } + set { computername = value; base.SetParameter(value, nameComputerName); } } + private String[] computername; /// @@ -118,12 +124,14 @@ public String[] ComputerName public String Namespace { get { return nameSpace; } + set { nameSpace = value; base.SetParameter(value, nameNamespace); } } + private String nameSpace; /// @@ -136,8 +144,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout;} + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -158,6 +168,7 @@ public UInt32 OperationTimeoutSec public CimInstance InputObject { get { return cimInstance; } + set { cimInstance = value; @@ -172,6 +183,7 @@ internal CimInstance CimInstance { get { return cimInstance; } } + private CimInstance cimInstance; /// @@ -190,12 +202,14 @@ internal CimInstance CimInstance public String Query { get { return query;} + set { query = value; base.SetParameter(value, nameQuery); } } + private String query; /// @@ -210,12 +224,14 @@ public String Query public String QueryDialect { get { return querydialect;} + set { querydialect = value; base.SetParameter(value, nameQueryDialect); } } + private String querydialect; #endregion @@ -232,6 +248,7 @@ protected override void BeginProcessing() { cimRemoveInstance = CreateOperationAgent(); } + this.CmdletOperation = new CmdletOperationRemoveCimInstance(this, cimRemoveInstance); this.AtBeginProcess = false; }//End BeginProcessing() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index fbefb223027..34ac78fd826 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -55,12 +55,14 @@ public RemoveCimSessionCommand() public CimSession[] CimSession { get { return cimsession;} + set { cimsession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimsession; /// @@ -80,12 +82,14 @@ public CimSession[] CimSession public String[] ComputerName { get { return computername; } + set { computername = value; base.SetParameter(value, nameComputerName); } } + private String[] computername; /// @@ -101,12 +105,14 @@ public String[] ComputerName public UInt32[] Id { get { return id;} + set { id = value; base.SetParameter(value, nameId); } } + private UInt32[] id; /// @@ -122,12 +128,14 @@ public UInt32[] Id public Guid[] InstanceId { get { return instanceid;} + set { instanceid = value; base.SetParameter(value, nameInstanceId); } } + private Guid[] instanceid; /// @@ -143,12 +151,14 @@ public Guid[] InstanceId public String[] Name { get { return name;} + set { name = value; base.SetParameter(value, nameName); } } + private String[] name; #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index e1a85f30b21..df0bd5b1519 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -54,12 +54,14 @@ public SetCimInstanceCommand() public CimSession[] CimSession { get { return cimSession; } + set { cimSession = value; base.SetParameter(value, nameCimSession); } } + private CimSession[] cimSession; /// @@ -75,12 +77,14 @@ public CimSession[] CimSession public String[] ComputerName { get { return computername; } + set { computername = value; base.SetParameter(value, nameComputerName); } } + private String[] computername; /// @@ -96,12 +100,14 @@ public String[] ComputerName public Uri ResourceUri { get { return resourceUri; } + set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } + private Uri resourceUri; /// @@ -115,12 +121,14 @@ public Uri ResourceUri public String Namespace { get { return nameSpace; } + set { nameSpace = value; base.SetParameter(value, nameNamespace); } } + private String nameSpace; /// @@ -133,8 +141,10 @@ public String Namespace public UInt32 OperationTimeoutSec { get { return operationTimeout; } + set { operationTimeout = value; } } + private UInt32 operationTimeout; /// @@ -155,6 +165,7 @@ public UInt32 OperationTimeoutSec public CimInstance InputObject { get { return cimInstance; } + set { cimInstance = value; @@ -169,6 +180,7 @@ internal CimInstance CimInstance { get { return cimInstance; } } + private CimInstance cimInstance; /// @@ -187,12 +199,14 @@ internal CimInstance CimInstance public String Query { get { return query; } + set { query = value; base.SetParameter(value, nameQuery); } } + private String query; /// @@ -207,12 +221,14 @@ public String Query public String QueryDialect { get { return querydialect; } + set { querydialect = value; base.SetParameter(value, nameQueryDialect); } } + private String querydialect; /// @@ -240,12 +256,14 @@ public String QueryDialect public IDictionary Property { get { return property; } + set { property = value; base.SetParameter(value, nameProperty); } } + private IDictionary property; /// @@ -264,11 +282,13 @@ public SwitchParameter PassThru { this.passThru = value; } + get { return this.passThru; } } + private SwitchParameter passThru; #endregion @@ -285,6 +305,7 @@ protected override void BeginProcessing() { cimSetCimInstance = CreateOperationAgent(); } + this.CmdletOperation = new CmdletOperationSetCimInstance(this, cimSetCimInstance); this.AtBeginProcess = false; }//End BeginProcessing() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 95d9efdc270..29355086902 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -144,6 +144,7 @@ internal static class DebugHelper internal static bool GenerateLog { get { return generateLog; } + set { generateLog = value; } } @@ -159,6 +160,7 @@ internal static bool GenerateLog internal static bool GenerateVerboseMessage { get { return generateVerboseMessage; } + set { generateVerboseMessage = value; } } @@ -222,6 +224,7 @@ internal static string GetSourceCodeInformation(bool withFileName, int depth) //{ // return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod()); //} + return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ", frame.GetMethod().DeclaringType.Name, frame.GetMethod().Name); @@ -340,10 +343,12 @@ private static void WriteLogInternal(string message, int indent, int depth) { indent = 0; } + if (indent > 5) { indent = 5; } + string sourceInformation = string.Empty; if (depth != -1) { @@ -356,6 +361,7 @@ private static void WriteLogInternal(string message, int indent, int depth) DateTime.Now.Second, GetSourceCodeInformation(true, depth)); } + lock (logLock) { using (FileStream fs = new FileStream(logFile,FileMode.OpenOrCreate)) @@ -425,6 +431,7 @@ public static string ValidateArgumentIsValidName(string parameterName, string va return trimed; } } + DebugHelper.WriteLogEx("An invalid name: {0}={1}", 0, parameterName, value); throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Strings.InvalidParameterValue, value, parameterName)); } @@ -448,9 +455,11 @@ public static String[] ValidateArgumentIsValidName(string parameterName, String[ { continue; } + ValidationHelper.ValidateArgumentIsValidName(parameterName, propertyName); } } + return value; } } From 9e355b686aab5d9c44e44cc95ecb9d4c76b13e3c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:28 -0800 Subject: [PATCH 10/81] Update Microsoft.PowerShell.Commands.Diagnostics --- .../CommonUtils.cs | 1 + .../CounterFileInfo.cs | 3 + .../CounterSample.cs | 28 ++++++++++ .../CounterSet.cs | 8 +++ .../ExportCounterCommand.cs | 15 +++++ .../GetCounterCommand.cs | 17 ++++++ .../GetEventCommand.cs | 56 +++++++++++++++++++ .../GetEventSnapin.cs | 1 + .../ImportCounterCommand.cs | 20 +++++++ .../NewWinEventCommand.cs | 13 +++++ .../PdhHelper.cs | 14 +++++ 11 files changed, 176 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index ba18db34943..68c3f76536d 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -132,6 +132,7 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou { FreeLibrary(moduleHandle); } + return formatError; } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs index f41e26a3a88..83cf235330b 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs @@ -30,6 +30,7 @@ public DateTime OldestRecord return _oldestRecord; } } + private DateTime _oldestRecord = DateTime.MinValue; public DateTime NewestRecord @@ -39,6 +40,7 @@ public DateTime NewestRecord return _newestRecord; } } + private DateTime _newestRecord = DateTime.MaxValue; public UInt32 SampleCount @@ -48,6 +50,7 @@ public UInt32 SampleCount return _sampleCount; } } + private UInt32 _sampleCount = 0; } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs index 572284b8953..877d37f1fe8 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs @@ -49,85 +49,109 @@ internal PerformanceCounterSample(string path, public string Path { get { return _path; } + set { _path = value; } } + private string _path = string.Empty; public string InstanceName { get { return _instanceName; } + set { _instanceName = value; } } + private string _instanceName = string.Empty; public double CookedValue { get { return _cookedValue; } + set { _cookedValue = value; } } + private double _cookedValue = 0; public UInt64 RawValue { get { return _rawValue; } + set { _rawValue = value; } } + private UInt64 _rawValue = 0; public UInt64 SecondValue { get { return _secondValue; } + set { _secondValue = value; } } + private UInt64 _secondValue = 0; public uint MultipleCount { get { return _multiCount; } + set { _multiCount = value; } } + private uint _multiCount = 0; public PerformanceCounterType CounterType { get { return _counterType; } + set { _counterType = value; } } + private PerformanceCounterType _counterType = 0; public DateTime Timestamp { get { return _timeStamp; } + set { _timeStamp = value; } } + private DateTime _timeStamp = DateTime.MinValue; public UInt64 Timestamp100NSec { get { return _timeStamp100nSec; } + set { _timeStamp100nSec = value; } } + private UInt64 _timeStamp100nSec = 0; public UInt32 Status { get { return _status; } + set { _status = value; } } + private UInt32 _status = 0; public UInt32 DefaultScale { get { return _defaultScale; } + set { _defaultScale = value; } } + private UInt32 _defaultScale = 0; public UInt64 TimeBase { get { return _timeBase; } + set { _timeBase = value; } } + private UInt64 _timeBase = 0; } @@ -149,8 +173,10 @@ internal PerformanceCounterSampleSet(DateTime timeStamp, public DateTime Timestamp { get { return _timeStamp; } + set { _timeStamp = value; } } + private DateTime _timeStamp = DateTime.MinValue; [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", @@ -160,8 +186,10 @@ public DateTime Timestamp public PerformanceCounterSample[] CounterSamples { get { return _counterSamples; } + set { _counterSamples = value; } } + private PerformanceCounterSample[] _counterSamples = null; private ResourceManager _resourceMgr = null; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs index c7c304558b5..c05c5f7edaa 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -31,6 +31,7 @@ internal CounterSet(string setName, _machineName = @"\\" + _machineName; } } + _counterSetType = categoryType; _description = setHelp; _counterInstanceMapping = counterInstanceMapping; @@ -43,6 +44,7 @@ public string CounterSetName return _counterSetName; } } + private string _counterSetName = string.Empty; public string MachineName @@ -52,6 +54,7 @@ public string MachineName return _machineName; } } + private string _machineName = "."; public PerformanceCounterCategoryType CounterSetType @@ -61,6 +64,7 @@ public PerformanceCounterCategoryType CounterSetType return _counterSetType; } } + private PerformanceCounterCategoryType _counterSetType; public string Description @@ -70,6 +74,7 @@ public string Description return _description; } } + private string _description = string.Empty; internal Dictionary CounterInstanceMapping @@ -79,6 +84,7 @@ internal Dictionary CounterInstanceMapping return _counterInstanceMapping; } } + private Dictionary _counterInstanceMapping; public StringCollection Paths @@ -101,6 +107,7 @@ public StringCollection Paths ("\\" + _counterSetName + "\\" + counterName) : (_machineName + "\\" + _counterSetName + "\\" + counterName); } + retColl.Add(path); } @@ -123,6 +130,7 @@ public StringCollection PathsWithInstances retColl.Add(path); } } + return retColl; } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs index 2769277e590..fee398230ed 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs @@ -46,8 +46,10 @@ public sealed class ExportCounterCommand : PSCmdlet public string Path { get { return _path; } + set { _path = value; } } + private string _path; private string _resolvedPath; @@ -65,8 +67,10 @@ public string Path public string FileFormat { get { return _format; } + set { _format = value; } } + private string _format = "blg"; // @@ -78,8 +82,10 @@ public string FileFormat public UInt32 MaxSize { get { return _maxSize; } + set { _maxSize = value; } } + private UInt32 _maxSize = 0; // @@ -98,8 +104,10 @@ public UInt32 MaxSize public PerformanceCounterSampleSet[] InputObject { get { return _counterSampleSets; } + set { _counterSampleSets = value; } } + private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0]; // @@ -110,8 +118,10 @@ public PerformanceCounterSampleSet[] InputObject public SwitchParameter Force { get { return _force; } + set { _force = value; } } + private SwitchParameter _force; // @@ -122,8 +132,10 @@ public SwitchParameter Force public SwitchParameter Circular { get { return _circular; } + set { _circular = value; } } + private SwitchParameter _circular; private ResourceManager _resourceMgr = null; @@ -236,6 +248,7 @@ protected override void ProcessRecord() { res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]); } + if (res != 0) { ReportPdhError(res, true); @@ -287,6 +300,7 @@ protected override void ProcessRecord() ReportPdhError(res, true); } } + res = _pdhHelper.WriteRelogSample(set.Timestamp); if (res != 0) { @@ -353,6 +367,7 @@ private void ReportPdhError(uint res, bool bTerminate) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } + Exception exc = new Exception(msg); if (bTerminate) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 50d099b25f8..63d262f4b2b 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -52,8 +52,10 @@ public sealed class GetCounterCommand : PSCmdlet public string[] ListSet { get { return _listSet; } + set { _listSet = value; } } + private string[] _listSet = { "*" }; // @@ -73,12 +75,14 @@ public string[] ListSet public string[] Counter { get { return _counter; } + set { _counter = value; _defaultCounters = false; } } + private string[] _counter = {@"\network interface(*)\bytes total/sec", @"\processor(_total)\% processor time", @"\memory\% committed bytes in use", @@ -102,8 +106,10 @@ public string[] Counter public int SampleInterval { get { return _sampleInterval; } + set { _sampleInterval = value; } } + private int _sampleInterval = 1; // @@ -119,12 +125,14 @@ public int SampleInterval public Int64 MaxSamples { get { return _maxSamples; } + set { _maxSamples = value; _maxSamplesSpecified = true; } } + private Int64 _maxSamples = 1; private bool _maxSamplesSpecified = false; @@ -135,8 +143,10 @@ public Int64 MaxSamples public SwitchParameter Continuous { get { return _continuous; } + set { _continuous = value; } } + private bool _continuous = false; // @@ -157,8 +167,10 @@ public SwitchParameter Continuous public string[] ComputerName { get { return _computerName; } + set { _computerName = value; } } + private string[] _computerName = new string[0]; private ResourceManager _resourceMgr = null; @@ -482,9 +494,11 @@ private void ProcessGetCounter() continue; } + allExpandedPaths.Add(expandedPath); } } + if (allExpandedPaths.Count == 0) { return; @@ -495,6 +509,7 @@ private void ProcessGetCounter() { ReportPdhError(res, false); } + res = _pdhHelper.AddCounters(ref allExpandedPaths, true); if (res != 0) { @@ -575,6 +590,7 @@ private void ReportPdhError(uint res, bool bTerminate) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } + Exception exc = new Exception(msg); if (bTerminate) { @@ -643,6 +659,7 @@ private void WriteSampleSetObject(PerformanceCounterSampleSet set) break; } } + WriteObject(set); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 13c49286859..0c93663f1ed 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -47,8 +47,10 @@ public sealed class GetWinEventCommand : PSCmdlet public string[] ListLog { get { return _listLog; } + set { _listLog = value; } } + private string[] _listLog = { "*" }; /// @@ -68,8 +70,10 @@ public string[] ListLog public string[] LogName { get { return _logName; } + set { _logName = value; } } + private string[] _logName = { "*" }; /// @@ -93,8 +97,10 @@ public string[] LogName public string[] ListProvider { get { return _listProvider; } + set { _listProvider = value; } } + private string[] _listProvider = { "*" }; /// @@ -116,8 +122,10 @@ public string[] ListProvider public string[] ProviderName { get { return _providerName; } + set { _providerName = value; } } + private string[] _providerName; /// @@ -139,8 +147,10 @@ public string[] ProviderName public string[] Path { get { return _path; } + set { _path = value; } } + private string[] _path; /// @@ -180,8 +190,10 @@ public string[] Path public Int64 MaxEvents { get { return _maxEvents; } + set { _maxEvents = value; } } + private Int64 _maxEvents = -1; /// @@ -217,8 +229,10 @@ public Int64 MaxEvents public string ComputerName { get { return _computerName; } + set { _computerName = value; } } + private string _computerName = string.Empty; /// @@ -235,8 +249,10 @@ public string ComputerName public PSCredential Credential { get { return _credential; } + set { _credential = value; } } + private PSCredential _credential = PSCredential.Empty; /// @@ -261,8 +277,10 @@ public PSCredential Credential public string FilterXPath { get { return _filter; } + set { _filter = value; } } + private string _filter = "*"; /// @@ -284,8 +302,10 @@ public string FilterXPath public XmlDocument FilterXml { get { return _xmlQuery; } + set { _xmlQuery = value; } } + private XmlDocument _xmlQuery = null; /// @@ -307,8 +327,10 @@ public XmlDocument FilterXml public Hashtable[] FilterHashtable { get { return _selector; } + set { _selector = value; } } + private Hashtable[] _selector; /// @@ -322,8 +344,10 @@ public Hashtable[] FilterHashtable public SwitchParameter Force { get { return _force; } + set { _force = value; } } + private SwitchParameter _force; /// @@ -338,8 +362,10 @@ public SwitchParameter Force public SwitchParameter Oldest { get { return _oldest; } + set { _oldest = value; } } + private bool _oldest = false; // @@ -521,6 +547,7 @@ private void ProcessGetLog() { logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, _filter); } + logQuery.Session = eventLogSession; logQuery.ReverseDirection = !_oldest; @@ -563,6 +590,7 @@ private void ProcessGetProvider() WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); } } + logQuery.Session = eventLogSession; logQuery.ReverseDirection = !_oldest; ; @@ -630,6 +658,7 @@ private void ProcessListLog() } } } + if (!bMatchFound) { string msg = _resourceMgr.GetString("NoMatchingLogsFound"); @@ -767,6 +796,7 @@ private void ProcessFile() { logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, _filter); } + logQuery.Session = eventLogSession; logQuery.ReverseDirection = !_oldest; @@ -862,10 +892,12 @@ private void ReadEvents(EventLogQuery logQuery) WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); continue; } + if (evtObj == null) { break; } + if (_maxEvents != -1 && numEvents >= _maxEvents) { break; @@ -882,6 +914,7 @@ private void ReadEvents(EventLogQuery logQuery) { WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); } + outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); // @@ -925,8 +958,10 @@ private string BuildStructuredQuery(EventLogSession eventLogSession) string providerFilter = AddProviderPredicatesToFilter(_providersByLogMap[log]); result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, providerFilter }); } + result.Append(queryListClose); } + break; case "GetLogSet": @@ -937,8 +972,10 @@ private string BuildStructuredQuery(EventLogSession eventLogSession) { result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, _filter }); } + result.Append(queryListClose); } + break; case "FileSet": @@ -950,8 +987,10 @@ private string BuildStructuredQuery(EventLogSession eventLogSession) string properFilePath = filePrefix + filePath; result.AppendFormat(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, properFilePath, _filter }); } + result.Append(queryListClose); } + break; case "HashQuerySet": @@ -1039,6 +1078,7 @@ private string BuildXPathFromHashTable(Hashtable hash) added = HandleNamedDataHashValue(key, hash[key]); } + break; } @@ -1048,6 +1088,7 @@ private string BuildXPathFromHashTable(Hashtable hash) { xpathString.Append(" and "); } + xpathString.Append(added); } @@ -1118,6 +1159,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession string.Format(CultureInfo.InvariantCulture, suppressOpener, queryId++, logName)); } } + if (hash.ContainsKey(hashkey_path_lc)) { if (hash[hashkey_path_lc] is Array) @@ -1146,6 +1188,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession } } } + if (hash.ContainsKey(hashkey_providername_lc)) { List provPatterns = new List(); @@ -1273,6 +1316,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession { result.Append(" and ").Append(xpathString); } + result.Append(propClose); } @@ -1315,6 +1359,7 @@ private string HandleEventIdHashValue(Object value) ret.Append(" or "); } } + ret.Append(")"); } else @@ -1344,6 +1389,7 @@ private string HandleLevelHashValue(Object value) ret.Append(" or "); } } + ret.Append(")"); } else @@ -1380,6 +1426,7 @@ private string HandleKeywordHashValue(Object value) { return string.Empty; } + keywordsMask |= keywordLong; } @@ -1530,6 +1577,7 @@ private string HandleDataHashValue(Object value) ret.Append(" or "); } } + ret.Append(")"); } else @@ -1562,6 +1610,7 @@ private string HandleNamedDataHashValue(String key, Object value) ret.Append(" or "); } } + ret.Append(")"); } else @@ -1636,6 +1685,7 @@ private bool ValidateLogName(string logName, EventLogSession eventLogSession) WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); return false; } + if (!Oldest.IsPresent) { if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) @@ -1645,6 +1695,7 @@ private bool ValidateLogName(string logName, EventLogSession eventLogSession) ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForLog", ErrorCategory.InvalidArgument, logName)); } } + return true; } @@ -1761,6 +1812,7 @@ private StringCollection ValidateAndResolveFilePath(string path) Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, pi.ProviderPath)); WriteError(new ErrorRecord(exc, "NotALogFile", ErrorCategory.InvalidArgument, path)); } + continue; } @@ -1871,6 +1923,7 @@ private string BuildProvidersPredicate(StringCollection providers) predicate.Append(" or "); } } + predicate.Append("]"); return predicate.ToString(); @@ -2051,9 +2104,11 @@ private void FindLogNamesMatchingWildcards(EventLogSession eventLogSession, IEnu { _logNamesMatchingWildcard.Add(actualLogName.ToLowerInvariant()); } + bMatched = true; } } + if (!bMatched) { string msg = _resourceMgr.GetString("NoMatchingLogsFound"); @@ -2090,6 +2145,7 @@ private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSessi bMatched = true; } } + if (!bMatched) { string msg = _resourceMgr.GetString("NoMatchingProvidersFound"); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs index a4483c7497f..d5c4e696c43 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs @@ -90,6 +90,7 @@ public override string[] Types return _types; } } + private string[] _types = new string[] { "getevent.types.ps1xml" }; /// diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs index a2728e7a4e5..a6bd86dd8ed 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs @@ -51,8 +51,10 @@ public sealed class ImportCounterCommand : PSCmdlet public string[] Path { get { return _path; } + set { _path = value; } } + private string[] _path; private StringCollection _resolvedPaths = new StringCollection(); @@ -76,8 +78,10 @@ public string[] Path public string[] ListSet { get { return _listSet; } + set { _listSet = value; } } + private string[] _listSet = new string[0]; // @@ -91,8 +95,10 @@ public string[] ListSet public DateTime StartTime { get { return _startTime; } + set { _startTime = value; } } + private DateTime _startTime = DateTime.MinValue; // @@ -106,8 +112,10 @@ public DateTime StartTime public DateTime EndTime { get { return _endTime; } + set { _endTime = value; } } + private DateTime _endTime = DateTime.MaxValue; // @@ -126,8 +134,10 @@ public DateTime EndTime public string[] Counter { get { return _counter; } + set { _counter = value; } } + private string[] _counter = new string[0]; // @@ -137,8 +147,10 @@ public string[] Counter public SwitchParameter Summary { get { return _summary; } + set { _summary = value; } } + private SwitchParameter _summary; // @@ -154,8 +166,10 @@ public SwitchParameter Summary public Int64 MaxSamples { get { return _maxSamples; } + set { _maxSamples = value; } } + private Int64 _maxSamples = KEEP_ON_SAMPLING; private ResourceManager _resourceMgr = null; @@ -207,6 +221,7 @@ protected override void EndProcessing() { return; } + ValidateFilePaths(); switch (ParameterSetName) @@ -358,6 +373,7 @@ private void ProcessListSet() WriteObject(setObj); bMatched = true; } + if (!bMatched) { string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile"); @@ -419,9 +435,11 @@ private void ProcessGetCounter() continue; } + validPaths.Add(expandedPath); } } + if (validPaths.Count == 0) { return; @@ -475,6 +493,7 @@ private void ProcessGetCounter() { break; } + if (res != 0 && res != PdhResults.PDH_INVALID_DATA) { ReportPdhError(res, false); @@ -620,6 +639,7 @@ private void ReportPdhError(uint res, bool bTerminate) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } + Exception exc = new Exception(msg); if (bTerminate) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 3fdf5b73a69..bb678efdb39 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -42,11 +42,13 @@ public string ProviderName { return _providerName; } + set { _providerName = value; } } + private string _providerName; /// @@ -62,12 +64,14 @@ public int Id { return _id; } + set { _id = value; _idSpecified = true; } } + private int _id; private bool _idSpecified = false; @@ -83,12 +87,14 @@ public byte Version { return _version; } + set { _version = value; _versionSpecified = true; } } + private byte _version; private bool _versionSpecified = false; @@ -109,11 +115,13 @@ public object[] Payload { return _payload; } + set { _payload = value; } } + private object[] _payload; /// @@ -149,6 +157,7 @@ private void LoadProvider() string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message); throw new Exception(msg, exc); } + break; } } @@ -200,6 +209,7 @@ private void LoadEventDescriptor() break; } } + if (matchedEvent == null) { string msg = string.Format(CultureInfo.InvariantCulture, @@ -268,6 +278,7 @@ private bool VerifyTemplate(EventMetadata emd) return false; } } + return true; } @@ -315,6 +326,7 @@ protected override void ProcessRecord() _payload[i] = string.Empty; } } + provider.WriteEvent(ref ed, _payload); } else @@ -322,6 +334,7 @@ protected override void ProcessRecord() provider.WriteEvent(ref ed); } } + base.ProcessRecord(); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 9a569f3c004..5987ec67d30 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -570,6 +570,7 @@ public uint ConnectToDataSource(string dataSourceName) { //Console.WriteLine("error in PdhBindInputDataSource: " + res); } + return res; } @@ -599,6 +600,7 @@ public uint OpenQuery() { //Console.WriteLine("error in PdhOpenQueryH: " + res); } + return res; } @@ -632,12 +634,14 @@ public uint SetQueryTimeRange(DateTime startTime, DateTime endTime) { startTime = new DateTime(startTime.Ticks, DateTimeKind.Utc); } + pTimeInfo.StartTime = (startTime == DateTime.MinValue) ? 0 : startTime.ToFileTimeUtc(); if (endTime != DateTime.MaxValue && endTime.Kind == DateTimeKind.Local) { endTime = new DateTime(endTime.Ticks, DateTimeKind.Utc); } + pTimeInfo.EndTime = (endTime == DateTime.MaxValue) ? Int64.MaxValue : endTime.ToFileTimeUtc(); pTimeInfo.SampleCount = 0; @@ -771,6 +775,7 @@ public uint EnumObjectItems(string machineName, string objectName, ref StringCol { Marshal.FreeHGlobal(strCountersList); } + if (strInstancesList != IntPtr.Zero) { Marshal.FreeHGlobal(strInstancesList); @@ -820,6 +825,7 @@ public uint GetValidPathsFromFiles(ref StringCollection validPaths) } } } + return res; } @@ -1032,6 +1038,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa return (uint)PdhResults.PDH_INVALID_PATH; } } + if (counterIndex != -1 && objIndex != -1) { break; @@ -1050,6 +1057,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa { return res; } + pathElts.ObjectName = objNameLocalized; string ctrNameLocalized; @@ -1058,6 +1066,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa { return res; } + pathElts.CounterName = ctrNameLocalized; // Assemble the path back by using the translated object and counter names: @@ -1088,6 +1097,7 @@ public uint LookupPerfNameByIndex(string machineName, uint index, out string loc localizedPathPtr = Marshal.AllocHGlobal(strSize * sizeof(char)); res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); } + if (res == 0) { locName = Marshal.PtrToStringUni(localizedPathPtr); @@ -1140,6 +1150,7 @@ public uint GetValidPaths(string machineName, } } } + return res; } @@ -1357,6 +1368,7 @@ public string GetCounterSetHelp(string szMachineName, string szObjectName) { return string.Empty; } + IntPtr retString = PdhGetExplainText(szMachineName, szObjectName, null); return Marshal.PtrToStringUni(retString); } @@ -1371,6 +1383,7 @@ public uint ReadNextSetPreVista(out PerformanceCounterSampleSet nextSet, bool bS { return res; } + if (res != 0 && res != PdhResults.PDH_NO_DATA) { return res; @@ -1524,6 +1537,7 @@ public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReadi { return res; } + if (res != 0 && res != PdhResults.PDH_NO_DATA) { return res; From 23980ab7c591a8fbcb3098165686b78c6291c1c4 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:30 -0800 Subject: [PATCH 11/81] Update Microsoft.PowerShell.ScheduledJob --- .../ScheduledJob.cs | 14 ++++++++++++++ .../ScheduledJobDefinition.cs | 11 +++++++++++ .../ScheduledJobOptions.cs | 14 ++++++++++++++ .../ScheduledJobSourceAdapter.cs | 4 ++++ .../ScheduledJobStore.cs | 1 + .../ScheduledJobTrigger.cs | 18 ++++++++++++++++++ .../ScheduledJobWTS.cs | 13 +++++++++++++ 7 files changed, 75 insertions(+) diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs index b93bec6bcd5..da837ecbe05 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs @@ -51,6 +51,7 @@ public sealed class ScheduledJob : Job2, ISerializable public ScheduledJobDefinition Definition { get { return _jobDefinition; } + internal set { _jobDefinition = value; } } @@ -115,6 +116,7 @@ public override bool HasMoreData internal bool AllowSetShouldExit { get { return _allowSetShouldExit; } + set { _allowSetShouldExit = value; } } @@ -138,10 +140,12 @@ public ScheduledJob( { throw new PSArgumentNullException("command"); } + if (name == null) { throw new PSArgumentNullException("name"); } + if (jobDefinition == null) { throw new PSArgumentNullException("jobDefinition"); @@ -737,10 +741,12 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) _runspace = null; } } + if (disposePowerShell != null) { disposePowerShell.Dispose(); } + if (disposeRunspace != null) { disposeRunspace.Dispose(); @@ -1011,26 +1017,32 @@ Collection information { throw new PSArgumentNullException("output"); } + if (error == null) { throw new PSArgumentNullException("error"); } + if (warning == null) { throw new PSArgumentNullException("warning"); } + if (verbose == null) { throw new PSArgumentNullException("verbose"); } + if (progress == null) { throw new PSArgumentNullException("progress"); } + if (debug == null) { throw new PSArgumentNullException("debug"); } + if (information == null) { throw new PSArgumentNullException("information"); @@ -1224,6 +1236,7 @@ private StatusInfo( { _startTime = null; } + DateTime stopTime = info.GetDateTime("Status_StopTime"); if (stopTime != DateTime.MinValue) { @@ -1262,6 +1275,7 @@ public void GetObjectData( { info.AddValue("Status_StartTime", DateTime.MinValue); } + if (_stopTime != null) { info.AddValue("Status_StopTime", _stopTime); diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs index a0485ed55c3..69e60961586 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs @@ -88,6 +88,7 @@ public ScheduledJobOptions Options public PSCredential Credential { get { return _credential; } + internal set { _credential = value; } } @@ -762,6 +763,7 @@ internal void RenameAndSave(string newName) { ex = e; } + if (ex != null) { string msg; @@ -773,6 +775,7 @@ internal void RenameAndSave(string newName) { msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRenamingScheduledJob, oldName, newName); } + throw new ScheduledJobException(msg, ex); } @@ -846,6 +849,7 @@ internal void RenameAndSave(string newName) { msg = StringUtil.Format(ScheduledJobErrorStrings.BrokenRenamingScheduledJob, oldName, newName); } + throw new ScheduledJobException(msg, ex); } } @@ -977,6 +981,7 @@ public void Register() { ex = e; } + if (ex != null) { // Clean up job store. @@ -1036,6 +1041,7 @@ public void Save() { ex = e; } + if (ex != null) { // We want this object to remain synchronized with what is in WTS. @@ -1071,6 +1077,7 @@ public void Save() { ex = e; } + if (ex != null) { // Remove this from WTS for consistency. @@ -2158,6 +2165,7 @@ public void Add(ScheduledJobDefinition jobDef) string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionAlreadyExistsInLocal, jobDef.Name, jobDef.GlobalId); throw new ScheduledJobException(msg); } + _definitions.Add(jobDef.Name, jobDef); } } @@ -2179,6 +2187,7 @@ public void AddOrReplace(ScheduledJobDefinition jobDef) { _definitions.Remove(jobDef.Name); } + _definitions.Add(jobDef.Name, jobDef); } } @@ -2283,8 +2292,10 @@ public ScheduledJobException(string message, Exception innerException) internal string FQEID { get { return _fqeid; } + set { _fqeid = value ?? string.Empty; } } + private string _fqeid = string.Empty; } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs index 858288f3c4c..0c9913da894 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs @@ -53,6 +53,7 @@ public sealed class ScheduledJobOptions : ISerializable public bool StartIfOnBatteries { get { return _startIfOnBatteries; } + set { _startIfOnBatteries = value; } } @@ -62,6 +63,7 @@ public bool StartIfOnBatteries public bool StopIfGoingOnBatteries { get { return _stopIfGoingOnBatteries; } + set { _stopIfGoingOnBatteries = value; } } @@ -71,6 +73,7 @@ public bool StopIfGoingOnBatteries public bool WakeToRun { get { return _wakeToRun; } + set { _wakeToRun = value; } } @@ -80,6 +83,7 @@ public bool WakeToRun public bool StartIfNotIdle { get { return _startIfNotIdle; } + set { _startIfNotIdle = value; } } @@ -89,6 +93,7 @@ public bool StartIfNotIdle public bool StopIfGoingOffIdle { get { return _stopIfGoingOffIdle; } + set { _stopIfGoingOffIdle = value; } } /// @@ -97,6 +102,7 @@ public bool StopIfGoingOffIdle public bool RestartOnIdleResume { get { return _restartOnIdleResume; } + set { _restartOnIdleResume = value; } } @@ -106,6 +112,7 @@ public bool RestartOnIdleResume public TimeSpan IdleDuration { get { return _idleDuration; } + set { _idleDuration = value; } } @@ -115,6 +122,7 @@ public TimeSpan IdleDuration public TimeSpan IdleTimeout { get { return _idleTimeout; } + set { _idleTimeout = value; } } @@ -124,6 +132,7 @@ public TimeSpan IdleTimeout public bool ShowInTaskScheduler { get { return _showInTaskScheduler; } + set { _showInTaskScheduler = value; } } @@ -133,6 +142,7 @@ public bool ShowInTaskScheduler public bool RunElevated { get { return _runElevated; } + set { _runElevated = value; } } @@ -142,6 +152,7 @@ public bool RunElevated public bool RunWithoutNetwork { get { return _runWithoutNetwork; } + set { _runWithoutNetwork = value; } } @@ -151,6 +162,7 @@ public bool RunWithoutNetwork public bool DoNotAllowDemandStart { get { return _donotAllowDemandStart; } + set { _donotAllowDemandStart = value; } } @@ -160,6 +172,7 @@ public bool DoNotAllowDemandStart public TaskMultipleInstancePolicy MultipleInstancePolicy { get { return _multipleInstancePolicy; } + set { _multipleInstancePolicy = value; } } @@ -169,6 +182,7 @@ public TaskMultipleInstancePolicy MultipleInstancePolicy public ScheduledJobDefinition JobDefinition { get { return _jobDefAssociation; } + internal set { _jobDefAssociation = value; } } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs index 5e14b5f12c7..d8dd5f980fe 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs @@ -931,6 +931,7 @@ public void Add(Job2 job) string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobAlreadyExistsInLocal, job.Name, job.InstanceId); throw new ScheduledJobException(msg); } + _jobs.Add(job.InstanceId, job); } } @@ -952,6 +953,7 @@ public void AddOrReplace(Job2 job) { _jobs.Remove(job.InstanceId); } + _jobs.Add(job.InstanceId, job); } } @@ -974,6 +976,7 @@ public void Remove(Job2 job) string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobNotInRepository, job.Name); throw new ScheduledJobException(msg); } + _jobs.Remove(job.InstanceId); } } @@ -1058,6 +1061,7 @@ public ScheduledJob GetJob(string definitionName, DateTime jobRun) { continue; } + DateTime PSBeginTime = job.PSBeginTime ?? DateTime.MinValue; if (definitionName.Equals(job.Definition.Name, StringComparison.OrdinalIgnoreCase) && jobRun.Year == PSBeginTime.Year && diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs index ae438af230a..37f046f384f 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs @@ -291,6 +291,7 @@ public static void RenameScheduledJobDefDir( { throw new PSArgumentException("oldDefName"); } + if (string.IsNullOrEmpty(newDefName)) { throw new PSArgumentException("newDefName"); diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index 9daebe32810..da4e6265209 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -48,6 +48,7 @@ public sealed class ScheduledJobTrigger : ISerializable public DateTime? At { get { return _time; } + set { _time = value; } } @@ -57,6 +58,7 @@ public DateTime? At public List DaysOfWeek { get { return _daysOfWeek; } + set { _daysOfWeek = value; } } @@ -66,6 +68,7 @@ public List DaysOfWeek public Int32 Interval { get { return _interval; } + set { _interval = value; } } @@ -75,6 +78,7 @@ public Int32 Interval public TriggerFrequency Frequency { get { return _frequency; } + set { _frequency = value; } } @@ -84,6 +88,7 @@ public TriggerFrequency Frequency public TimeSpan RandomDelay { get { return _randomDelay; } + set { _randomDelay = value; } } @@ -93,6 +98,7 @@ public TimeSpan RandomDelay public TimeSpan? RepetitionInterval { get { return _repInterval; } + set { // A TimeSpan value of zero is equivalent to a null value. @@ -107,6 +113,7 @@ public TimeSpan? RepetitionInterval public TimeSpan? RepetitionDuration { get { return _repDuration; } + set { // A TimeSpan value of zero is equivalent to a null value. @@ -121,6 +128,7 @@ public TimeSpan? RepetitionDuration public string User { get { return _user; } + set { _user = value; } } @@ -130,6 +138,7 @@ public string User public Int32 Id { get { return _id; } + internal set { _id = value; } } @@ -139,6 +148,7 @@ public Int32 Id public bool Enabled { get { return _enabled; } + set { _enabled = value; } } @@ -148,6 +158,7 @@ public bool Enabled public ScheduledJobDefinition JobDefinition { get { return _jobDefAssociation; } + internal set { _jobDefAssociation = value; } } @@ -355,10 +366,12 @@ internal void Validate() string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerOnceType); throw new ScheduledJobException(msg); } + if (_repInterval != null || _repDuration != null) { ValidateOnceRepetitionParams(_repInterval, _repDuration); } + break; case TriggerFrequency.Daily: @@ -367,10 +380,12 @@ internal void Validate() string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerDailyType); throw new ScheduledJobException(msg); } + if (_interval < 1) { throw new ScheduledJobException(ScheduledJobErrorStrings.InvalidDaysIntervalParam); } + break; case TriggerFrequency.Weekly: @@ -379,15 +394,18 @@ internal void Validate() string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerWeeklyType); throw new ScheduledJobException(msg); } + if (_interval < 1) { throw new ScheduledJobException(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); } + if (_daysOfWeek == null || _daysOfWeek.Count == 0) { string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerDaysOfWeek, ScheduledJobErrorStrings.TriggerWeeklyType); throw new ScheduledJobException(msg); } + break; } } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs index 36713a7a885..6ae77f3804e 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs @@ -379,6 +379,7 @@ private void AddTaskTrigger( iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } + break; case TriggerFrequency.AtLogon: @@ -393,6 +394,7 @@ private void AddTaskTrigger( iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } + break; case TriggerFrequency.Once: @@ -423,6 +425,7 @@ private void AddTaskTrigger( iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } + break; case TriggerFrequency.Daily: @@ -438,6 +441,7 @@ private void AddTaskTrigger( iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } + break; case TriggerFrequency.Weekly: @@ -454,6 +458,7 @@ private void AddTaskTrigger( iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } + break; } } @@ -742,6 +747,7 @@ private TimeSpan ParseWTSTime(string wtsTime) str.Append(c2); } } + break; case 'T': @@ -770,6 +776,7 @@ private TimeSpan ParseWTSTime(string wtsTime) str.Append(c2); } } + break; } } @@ -871,11 +878,17 @@ private List ConvertMaskToDaysOfWeekArray(short mask) List daysOfWeek = new List(); if ((mask & WTSSunday) != 0) { daysOfWeek.Add(DayOfWeek.Sunday); } + if ((mask & WTSMonday) != 0) { daysOfWeek.Add(DayOfWeek.Monday); } + if ((mask & WTSTuesday) != 0) { daysOfWeek.Add(DayOfWeek.Tuesday); } + if ((mask & WTSWednesday) != 0) { daysOfWeek.Add(DayOfWeek.Wednesday); } + if ((mask & WTSThursday) != 0) { daysOfWeek.Add(DayOfWeek.Thursday); } + if ((mask & WTSFriday) != 0) { daysOfWeek.Add(DayOfWeek.Friday); } + if ((mask & WTSSaturday) != 0) { daysOfWeek.Add(DayOfWeek.Saturday); } return daysOfWeek; From b4c11be2109a570129e3e1dabe927624592693dd Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:30 -0800 Subject: [PATCH 12/81] Update Microsoft.WSMan.Management --- .../ConfigProvider.cs | 305 ++++++++++++++++++ src/Microsoft.WSMan.Management/CredSSP.cs | 16 + src/Microsoft.WSMan.Management/Interop.cs | 1 + .../InvokeWSManAction.cs | 26 ++ .../NewWSManSession.cs | 22 ++ src/Microsoft.WSMan.Management/PingWSMan.cs | 10 + .../Set-QuickConfig.cs | 13 + .../WSManConnections.cs | 27 ++ .../WSManInstance.cs | 116 +++++++ src/Microsoft.WSMan.Management/WsManHelper.cs | 43 +++ 10 files changed, 579 insertions(+) diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 576184f83a4..d955cf83688 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -69,6 +69,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) //Means we are at host level, where no new-item is supported. Return empty string. return String.Empty; } + String child = path.Substring(ChildIndex + 1); //We only return help for the below set of 5 commands, not for any other case. @@ -102,6 +103,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) break; } } + culture = culture.Parent; } while (culture != culture.Parent); @@ -169,10 +171,12 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) { return String.Empty; } + if (result != null) { return result.ParentNode.OuterXml; } + return String.Empty; } @@ -277,6 +281,7 @@ protected override string MakePath(string parent, string child) child = child.Remove(0, parent.Length); } } + string path = string.Empty; string ChildName = string.Empty; string CorrectCaseChildName = string.Empty; @@ -288,11 +293,13 @@ protected override string MakePath(string parent, string child) { path = child; } + if (path.Length != 0) { ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); CorrectCaseChildName = GetChildName(path); } + if (ChildName.Equals(CorrectCaseChildName, StringComparison.OrdinalIgnoreCase)) { if (child.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) @@ -305,6 +312,7 @@ protected override string MakePath(string parent, string child) child = CorrectCaseChildName; } } + String basepath = base.MakePath(parent, child); return GetCorrectCaseOfPath(basepath); } @@ -363,6 +371,7 @@ protected override bool HasChildItems(string path) //Get the ChildName childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); } + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); if (SessionObjCache.ContainsKey(path)) { @@ -381,6 +390,7 @@ protected override bool HasChildItems(string path) StartWSManService(Force); } } + string WsManURI = NormalizePath(path, host); lock(WSManHelper.AutoSession) @@ -423,6 +433,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { return true; } + ProcessCertMappingObjects(xmlCertificates, out CertificatesObjCache, out KeyCache); if (CertificatesObjCache.Count > 0) { @@ -450,6 +461,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi } } + strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + currentpluginname; if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) { @@ -465,6 +477,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi } } } + string filter = WsManURI + "?Name=" + currentpluginname; XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); ArrayList arrSecurities = null; @@ -478,6 +491,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return true; } } + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { if (arrInitParams != null && arrInitParams.Count > 0) @@ -485,6 +499,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return true; } } + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) { XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters); @@ -496,6 +511,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return false; } + if (arrResources != null) { foreach (PSObject objresource in arrResources) @@ -508,6 +524,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { return true; } + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity)) { @@ -518,6 +535,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return true; } } + strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) { @@ -525,6 +543,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { return false; } + foreach (PSObject security in arrSecurities) { string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); @@ -550,6 +569,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return IsItemContainer(nodes); } } + return false; } } @@ -588,6 +608,7 @@ protected override void GetItem(string path) { WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + childname, true); } + return; } @@ -645,6 +666,7 @@ protected override void GetItem(string path) { return; } + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML, true); ArrayList arrSecurity = null; ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); @@ -664,6 +686,7 @@ protected override void GetItem(string path) WriteItemObject(GetItemPSObjectWithTypeName(objPluginlevel.Properties[childname].Name, objPluginlevel.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + objPluginlevel.Properties[childname].Name, true); } } + strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) { @@ -671,6 +694,7 @@ protected override void GetItem(string path) { return; } + if (path.EndsWith(strPathChk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { foreach (PSObject p in arrResources) @@ -680,8 +704,10 @@ protected override void GetItem(string path) WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, new string[] { "ResourceURI=" + p.Properties["ResourceUri"].Value.ToString() }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true); } } + return; } + strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); string sResourceDirName = string.Empty; @@ -693,6 +719,7 @@ protected override void GetItem(string path) { sResourceDirName = path.Substring(strPathChk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length) - (strPathChk.Length)); } + if (path.Contains(strPathChk + sResourceDirName)) { if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) @@ -710,11 +737,14 @@ protected override void GetItem(string path) { WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false); } + break; } } + return; } + strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity)) { @@ -722,6 +752,7 @@ protected override void GetItem(string path) { return; } + foreach (PSObject p in arrSecurity) { if (path.EndsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) @@ -739,6 +770,7 @@ protected override void GetItem(string path) } } } + return; } } @@ -810,6 +842,7 @@ protected override void GetItem(string path) { mshObject = BuildHostLevelPSObjectArrayList(sessionobj, uri, false); } + if (mshObject != null) { if (mshObject.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) @@ -939,6 +972,7 @@ protected override void SetItem(string path, object value) { path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator)); } + string strPathChk = host + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerListener)) { @@ -954,6 +988,7 @@ protected override void SetItem(string path, object value) { AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); } + try { XmlDocument xmlPlugins = FindResourceValue(sessionobj, uri, null); @@ -966,8 +1001,10 @@ protected override void SetItem(string path, object value) // Don't need an error if ClearItem is called. AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); } + return; } + string filter = uri + "?Name=" + currentpluginname; CurrentConfigurations pluginConfiguration = new CurrentConfigurations((IWSManSession)sessionobj); @@ -1027,6 +1064,7 @@ protected override void SetItem(string path, object value) pluginConfiguration.UpdateOneConfiguration(".", ChildName, value.ToString()); } + strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) { @@ -1036,6 +1074,7 @@ protected override void SetItem(string path, object value) return; } + strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); string sResourceDirName = string.Empty; @@ -1047,6 +1086,7 @@ protected override void SetItem(string path, object value) { sResourceDirName = path.Substring(strPathChk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length) - (strPathChk.Length)); } + if (path.Contains(strPathChk + sResourceDirName)) { if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) @@ -1087,6 +1127,7 @@ protected override void SetItem(string path, object value) } } } + strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity)) { @@ -1263,11 +1304,13 @@ protected override void SetItem(string path, object value) { query = helper.GetResourceMsgFromResourcetext("SetItemRootSDDLWarningQuery"); } + if (!ShouldContinue(query, caption)) { return; } } + WSManProviderSetItemDynamicParameters dynParams = DynamicParameters as WSManProviderSetItemDynamicParameters; if (dynParams != null) { @@ -1280,6 +1323,7 @@ protected override void SetItem(string path, object value) } } } + cmdlinevalue.Add(ChildName, value); } else @@ -1296,6 +1340,7 @@ protected override void SetItem(string path, object value) warningMessage.Add(String.Format(helper.GetResourceMsgFromResourcetext("SetItemWarningForGlobalQuota"), value)); } } + PutResourceValue(sessionobj, uri, cmdlinevalue, host); } catch (COMException e) @@ -1345,6 +1390,7 @@ protected override object SetItemDynamicParameters(string path, object value) return new WSManProviderSetItemDynamicParameters(); } } + return null; } @@ -1404,6 +1450,7 @@ protected override bool IsItemContainer(string path) //Get the ChildName childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); } + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); if (SessionObjCache.ContainsKey(path)) { @@ -1439,6 +1486,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI); if (xmlListeners != null) @@ -1459,6 +1507,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI); if (xmlCertificates != null) { @@ -1480,6 +1529,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator; XmlDocument xmlPlugins = FindResourceValue(sessionobj, WsManURI, null); @@ -1490,6 +1540,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + string filter = WsManURI + "?Name=" + currentpluginname; XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); ArrayList arrSecurities = null; @@ -1498,15 +1549,18 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { return true; } + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { return true; } + if (path.EndsWith(strPathCheck + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) { return true; @@ -1516,6 +1570,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return false; } + foreach (PSObject objresource in arrResources) { string sResourceDirName = objresource.Properties["ResourceDir"].Value.ToString(); @@ -1526,6 +1581,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity)) { @@ -1533,6 +1589,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return true; } + strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) { @@ -1540,6 +1597,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co { return false; } + foreach (PSObject security in arrSecurities) { string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); @@ -1562,6 +1620,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co bool result = IsItemContainer(nodes); return result; } + return false; } } @@ -1579,6 +1638,7 @@ protected override void RemoveItem(string path, bool recurse) AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); return; } + String ChildName = String.Empty; if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString())) @@ -1597,6 +1657,7 @@ protected override void RemoveItem(string path, bool recurse) { AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false); } + helper.RemoveFromDictionary(ChildName); return; } @@ -1657,6 +1718,7 @@ protected override void RemoveItem(string path, bool recurse) { pName = path.Substring(pos); } + string filter1 = uri + "?Name=" + pName; XmlDocument pxml = GetResourceValue(sessionobj, filter1, null); @@ -1674,6 +1736,7 @@ protected override void RemoveItem(string path, bool recurse) throwerror = false; ResourceArray = RemoveItemfromResourceArray(ResourceArray, ChildName, string.Empty, "ResourceDir"); } + if (throwerror) { strPathCheck = strPathCheck + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; @@ -1687,6 +1750,7 @@ protected override void RemoveItem(string path, bool recurse) { sResourceDirName = path.Substring(strPathCheck.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathCheck.Length) - (strPathCheck.Length)); } + strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { @@ -1701,11 +1765,13 @@ protected override void RemoveItem(string path, bool recurse) throwerror = false; InitParamArray = RemoveItemfromResourceArray(InitParamArray, ChildName, "InitParams", string.Empty); } + if (throwerror) { AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); return; } + inputStr = ConstructPluginXml(ps, uri, host, "Set", ResourceArray, SecurityArray, InitParamArray); try { @@ -1729,6 +1795,7 @@ protected override void RemoveItem(string path, bool recurse) throwerror = false; RemoveListenerOrCertMapping(sessionobj, uri, ChildName, PKeyCertMapping, false); } + if (throwerror) { AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); @@ -1778,6 +1845,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem StartWSManService(this.Force); } } + string uri = NormalizePath(path, host); lock(WSManHelper.AutoSession) @@ -1801,18 +1869,22 @@ protected override void NewItem(string path, string itemTypeName, object newItem { listenerparams.Add("Hostname", niParams.HostName); } + if (niParams.URLPrefix != null) { listenerparams.Add("URLPrefix", niParams.URLPrefix); } + if (niParams.IsPortSpecified) { listenerparams.Add("Port", niParams.Port); } + if (niParams.CertificateThumbPrint != null) { listenerparams.Add("CertificateThumbPrint", niParams.CertificateThumbPrint); } + NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, listenerparams, WSManStringLiterals.containerListener, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerCaption")); } else if (path.EndsWith(strPathChk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) @@ -1829,6 +1901,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem Certparams.Add("UserName", nwCredentials.UserName); Certparams.Add("Password", nwCredentials.Password); } + Certparams.Add("Enabled", dynParams.Enabled); NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, Certparams, WSManStringLiterals.containerClientCertificate, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertCaption")); } @@ -1854,32 +1927,39 @@ protected override object NewItemDynamicParameters(string path, string itemTypeN { return new WSManProviderNewItemComputerParameters(); } + string hostname = GetHostName(path); string strpathchk = hostname + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strpathchk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) { return new WSManProviderNewItemPluginParameters(); } + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { return new WSManProviderInitializeParameters(); } + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { return new WSManProviderNewItemResourceParameters(); } + if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { return new WSManProviderNewItemSecurityParameters(); } + if (path.EndsWith(strpathchk + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) { return new WSManProvidersListenerParameters(); } + if (path.EndsWith(strpathchk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) { return new WSManProviderClientCertificateParameters(); } + return null; } @@ -1904,6 +1984,7 @@ private void NewItemCreateComputerConnection(string Name) parametersetName = "URI"; } + helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); if (dynParams.ConnectionURI != null) { @@ -1911,6 +1992,7 @@ private void NewItemCreateComputerConnection(string Name) string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); Name = constrsplit1[1].Trim(); } + WriteItemObject(GetItemPSObjectWithTypeName(Name, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + Name, true); } else @@ -1942,6 +2024,7 @@ private void NewItemContainerListenerOrCertMapping(object sessionobj, string pat return; } } + string inputstr = GetInputStringForCreate(uri, InputParams, host); CreateResourceValue(sessionobj, uri, inputstr, InputParams); XmlDocument xmlResource = GetResourceValue(sessionobj, uri, InputParams); @@ -1955,6 +2038,7 @@ private void NewItemContainerListenerOrCertMapping(object sessionobj, string pat { ProcessListenerObjects(xmlResource, out CCache, out kCache); } + if (CCache != null && CCache.Count > 0) { foreach (DictionaryEntry resource in CCache) @@ -2032,6 +2116,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h { mshObj.Properties.Add(new PSNoteProperty("XmlRenderingType", "Text")); } + inputStr = ConstructPluginXml(mshObj, uri, host, "New", null, null, null); PluginName = niParams.Plugin; } @@ -2046,6 +2131,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h WriteError(er); return; } + string filter = uri + "?Name=" + PluginName; CreateResourceValue(sessionobj, filter, inputStr, null); WriteItemObject(GetItemPSObjectWithTypeName(PluginName, WSManStringLiterals.ContainerChildValue, null, new string[] { "Name=" + PluginName }, string.Empty, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + PluginName, true); @@ -2107,12 +2193,14 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h } } } + int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length); string sResourceDirName = string.Empty; if (Sepindex != -1) { sResourceDirName = path.Substring(strPathChk.Length + 1, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length + 1) - (strPathChk.Length + 1)); } + strPathChk = strPathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName; if (path.EndsWith(strPathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) @@ -2161,6 +2249,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h } } + if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { @@ -2180,6 +2269,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h InitParamArray = ProcessPluginInitParamLevel(xdoc); } } + inputStr = ConstructPluginXml(ps, uri, host, "Set", ResourceArray, SecurityArray, InitParamArray); try { @@ -2222,11 +2312,13 @@ private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfEleme WSManConfigElement element = new WSManConfigElement(Name, TypeNameOfElement); mshObject = new PSObject(element); } + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigContainerElement)) { WSManConfigContainerElement element = new WSManConfigContainerElement(Name, TypeNameOfElement, keys); mshObject = new PSObject(element); } + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigLeafElement)) { object source = null; @@ -2243,6 +2335,7 @@ private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfEleme WSManConfigLeafElement element = new WSManConfigLeafElement(Name, Value, TypeNameOfElement, source); mshObject = new PSObject(element); } + if (!String.IsNullOrEmpty(ExtendedTypeName)) { StringBuilder types = new StringBuilder(string.Empty); @@ -2254,6 +2347,7 @@ private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfEleme mshObject.TypeNames.Insert(0, types.ToString()); } } + return mshObject; } @@ -2287,6 +2381,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour { ProcessCertMappingObjects(xmlResource, out objcache, out Keyscache); } + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + parent, StringComparison.OrdinalIgnoreCase)) { AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); @@ -2300,6 +2395,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour return; } } + string item = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1); try { @@ -2309,6 +2405,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour { cmdlinevalue.Add(key, ((PSObject)objcache[item]).Properties[key].Value); } + PutResourceValue(sessionObj, ResourceURI, cmdlinevalue, host); } catch (COMException e) @@ -2348,6 +2445,7 @@ private string GetInputStringForCreate(string ResourceURI, Hashtable value, stri sbvalues.Append(WSManStringLiterals.ATTR_NIL); nilns = " " + WSManStringLiterals.NS_XSI; } + sbvalues.Append(">"); sbvalues.Append(EscapeValuesForXML(((Hashtable)value)[key].ToString())); sbvalues.Append("" + sbvalues.ToString() + ""; return putstr; @@ -2405,6 +2504,7 @@ private string ReadFile(string path) ErrorRecord er = new ErrorRecord(e, "SecurityException", ErrorCategory.InvalidOperation, null); WriteError(er); } + return putstr; } @@ -2424,6 +2524,7 @@ private string GetHostName(string path) { sHostname = path.Substring(0, path.IndexOf(WSManStringLiterals.DefaultPathSeparator)); } + Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); if (!SessionObjCache.ContainsKey(sHostname)) sHostname = null; @@ -2434,6 +2535,7 @@ private string GetHostName(string path) ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidArgument, null); WriteError(er); } + return sHostname; } @@ -2444,6 +2546,7 @@ private string GetRootNodeName(string ResourceURI) { ResourceURI = ResourceURI.Split(new char[] { '?' }).GetValue(0).ToString(); } + string PTRN_URI_LAST = "([a-z_][-a-z0-9._]*)$"; Regex objregex = new Regex(PTRN_URI_LAST, RegexOptions.IgnoreCase); MatchCollection regexmatch = objregex.Matches(ResourceURI); @@ -2451,6 +2554,7 @@ private string GetRootNodeName(string ResourceURI) { tempuri = regexmatch[0].Value.ToString(); } + return tempuri; } @@ -2493,6 +2597,7 @@ private string EscapeValuesForXML(string value) } } } + return esc_str.ToString(); } @@ -2509,6 +2614,7 @@ private bool IsItemContainer(XmlNodeList nodes) } } } + return result; } @@ -2525,6 +2631,7 @@ private XmlNodeList SearchXml(XmlDocument resourcexmldocument, string searchitem searchitem = WSManStringLiterals.containerWinrs.ToLowerInvariant(); } } + if (ResourceURI.EndsWith("Config", StringComparison.OrdinalIgnoreCase) || !ResourceURI.EndsWith(searchitem, StringComparison.OrdinalIgnoreCase)) { xpathString = @"/*/*[local-name()=""" + searchitem.ToLowerInvariant() + @"""]"; @@ -2533,6 +2640,7 @@ private XmlNodeList SearchXml(XmlDocument resourcexmldocument, string searchitem { xpathString = @"/*[local-name()=""" + searchitem.ToLowerInvariant() + @"""]"; } + nodes = resourcexmldocument.SelectNodes(xpathString); } @@ -2541,6 +2649,7 @@ private XmlNodeList SearchXml(XmlDocument resourcexmldocument, string searchitem ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidArgument, null); WriteError(er); } + return nodes; } @@ -2590,6 +2699,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v } } } + if (Itemfound) { ResourceURI = GetURIWithFilter(ResourceURI, value); @@ -2697,6 +2807,7 @@ private XmlDocument EnumerateResourceValue(object sessionobj, string ResourceURI } } } + return xmlEnumResources; } @@ -2719,6 +2830,7 @@ private void DeleteResourceValue(object sessionobj, string ResourceURI, Hashtabl { ResourceURI = GetURIWithFilter(ResourceURI, cmdlinevalues); } + ((IWSManSession)sessionobj).Delete(ResourceURI, 0); } @@ -2784,6 +2896,7 @@ private XmlDocument FindResourceValue(object sessionobj, string ResourceURI, Has { outval = GetResourceValue(sessionobj, ResourceURI, cmdlinevalues); } + return outval; } @@ -2810,20 +2923,24 @@ private bool ContainResourceValue(object sessionobj, string ResourceURI, string { valuexml = valuexml + ((IWSManEnumerator)value).ReadItem(); } + if ((valuexml != string.Empty) && !(String.IsNullOrEmpty(valuexml))) { valuexml = "" + valuexml + ""; } + Marshal.ReleaseComObject(value); } else { valuexml = this.GetResourceValueInXml(((IWSManSession)sessionobj), ResourceURI, null); } + if (string.IsNullOrEmpty(valuexml)) { return false; } + XmlDocument xmlResourceValues = new XmlDocument(); xmlResourceValues.LoadXml(valuexml.ToLowerInvariant()); XmlNodeList nodes = SearchXml(xmlResourceValues, childname, ResourceURI, path, host); @@ -2833,6 +2950,7 @@ private bool ContainResourceValue(object sessionobj, string ResourceURI, string } } catch (COMException) { result = false; } + return result; } @@ -2859,6 +2977,7 @@ private string GetURIWithFilter(string uri, Hashtable cmdlinevalues) sburi.Append(GetFilterString(cmdlinevalues, PKeyPlugin)); } } + return sburi.ToString(); } @@ -2875,6 +2994,7 @@ private string GetFilterString(Hashtable cmdlinevalues, string[] pkey) filter.Append("+"); } } + if (filter.ToString().EndsWith("+", StringComparison.OrdinalIgnoreCase)) filter.Remove(filter.ToString().Length - 1, 1); return filter.ToString(); @@ -2895,6 +3015,7 @@ private bool IsPKey(string value, string ResourceURI) { result = CheckPkeysArray(null, value, PKeyCertMapping); } + return result; } @@ -2920,6 +3041,7 @@ private bool CheckPkeysArray(Hashtable values, string value, string[] pkeys) } } } + return result; } @@ -2963,11 +3085,13 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str WSManConfigElement element = new WSManConfigElement(prop.Name, prop.Value.ToString()); mshObject = new PSObject(element); } + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigContainerElement)) { WSManConfigContainerElement element = new WSManConfigContainerElement(prop.Name, prop.Value.ToString(), keys); mshObject = new PSObject(element); } + if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigLeafElement)) { string sourceProp = prop.Name + WSManStringLiterals.HiddenSuffixForSourceOfValue; @@ -2986,11 +3110,13 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str { element = new WSManConfigLeafElement(prop.Name, null, prop.Value.ToString()); } + if (element != null) { mshObject = new PSObject(element); } } + if (!String.IsNullOrEmpty(ExtendedTypeName)) { StringBuilder types = new StringBuilder(string.Empty); @@ -3002,6 +3128,7 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str mshObject.TypeNames.Insert(0, types.ToString()); } } + if (!prop.Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) { // This path is used by WriteItemObject to construct PSPath. @@ -3029,6 +3156,7 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str } } } + if (recurse) { foreach (string dir in directory) @@ -3046,6 +3174,7 @@ private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, { mshObject = ConvertToPSObject(innerResourceNodes); } + string existingvalue = string.Empty; try { @@ -3075,6 +3204,7 @@ private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, { } + return existingvalue; } @@ -3123,6 +3253,7 @@ private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string } } + return mshobject; } @@ -3163,6 +3294,7 @@ private PSObject ConvertToPSObject(XmlNode xmlnode) mshObject.Properties.Add(new PSNoteProperty(node.LocalName, WSManStringLiterals.ContainerChildValue)); } } + return mshObject; } @@ -3194,6 +3326,7 @@ private string SetXPathString(string uri) { parent = WSManStringLiterals.containerPlugin; } + parent = "/cfg:" + parent; return parent; } @@ -3270,10 +3403,13 @@ private string NormalizePath(string path, string host) uri = uri.Remove(index); } } + uri = WinrmRootName[0].ToString() + uri; } + return uri; } + return uri; } @@ -3379,6 +3515,7 @@ private PSObject GetItemValue(string path) { return null; } + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML); ArrayList arrSecurity = null; ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); @@ -3392,6 +3529,7 @@ private PSObject GetItemValue(string path) { return null; } + strPathchk = strPathchk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length); string sResourceDirName = String.Empty; @@ -3419,6 +3557,7 @@ private PSObject GetItemValue(string path) } } } + return null; } @@ -3449,6 +3588,7 @@ private string GetCorrectCaseOfPath(string path) sbPath.Append(GetChildName(tempPath.ToString())); } } + return sbPath.ToString(); } @@ -3506,6 +3646,7 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa StartWSManService(this.Force); } } + string uri = NormalizePath(path, hostname); lock(WSManHelper.AutoSession) @@ -3539,6 +3680,7 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa result = WSManStringLiterals.containerClientCertificate + "_" + ChildName.Substring(ChildName.IndexOf('_') + 1); } } + return result; } @@ -3566,11 +3708,14 @@ private ArrayList RemoveItemfromResourceArray(ArrayList resourceArray, string Ch break; } } + index++; } + if (itemfound) resourceArray.RemoveAt(index); } + return resourceArray; } @@ -3597,10 +3742,12 @@ private void GetChildItemOrNamesForListenerOrCertMapping(XmlDocument xmlResource } else { return; } + if (Objcache == null || Keyscache == null) { return; } + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + ListenerOrCerMapping, StringComparison.OrdinalIgnoreCase)) { foreach (string key in Keyscache.Keys) @@ -3620,6 +3767,7 @@ private void GetChildItemOrNamesForListenerOrCertMapping(XmlDocument xmlResource break; } } + return; } else @@ -3636,6 +3784,7 @@ private void GetChildItemOrNamesForListenerOrCertMapping(XmlDocument xmlResource WriteItemObject(prop.Name, path + WSManStringLiterals.DefaultPathSeparator + prop.Name, false); } } + return; } @@ -3662,10 +3811,12 @@ private void GetItemListenerOrCertMapping(string path, XmlDocument xmlResource, } else { return; } + if (Objcache == null || Keyscache == null) { return; } + if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + ContainerListenerOrClientCert, StringComparison.OrdinalIgnoreCase)) { if (Objcache.ContainsKey(childname)) @@ -3706,6 +3857,7 @@ private void RemoveListenerOrCertMapping(object sessionobj, string WsManUri, str { ProcessListenerObjects(xmlresources, out ResourcesCache, out KeysCache); } + if (KeysCache.Contains(childname)) { PSObject objResource = (PSObject)ResourcesCache[childname]; @@ -3714,6 +3866,7 @@ private void RemoveListenerOrCertMapping(object sessionobj, string WsManUri, str { SelectorParams.Add(pKey, objResource.Properties[pKey].Value); } + DeleteResourceValue(sessionobj, WsManUri, SelectorParams, false); } } @@ -3786,6 +3939,7 @@ private bool CheckValidContainerOrPath(string path) { return true; } + if (path.StartsWith(strpathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) { //Check for Plugin path @@ -3801,6 +3955,7 @@ private bool CheckValidContainerOrPath(string path) { return false; } + string filter = uri + "?Name=" + currentpluginname; XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); PSObject mshPluginLvl = ProcessPluginConfigurationLevel(CurrentPluginXML); @@ -3817,12 +3972,14 @@ private bool CheckValidContainerOrPath(string path) { return true; } + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { return true; } + if (arrResources != null) { strpathChk = strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources; @@ -3842,17 +3999,20 @@ private bool CheckValidContainerOrPath(string path) return true; } } + if (path.StartsWith(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { if (path.Equals(strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { return true; } + strpathChk = strpathChk + WSManStringLiterals.DefaultPathSeparator + sResourceDirName + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; if (arrSecurities == null) { return false; } + foreach (PSObject security in arrSecurities) { string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); @@ -3915,6 +4075,7 @@ private bool CheckValidContainerOrPath(string path) { return (ContainResourceValue(sessionobj, uri, ChildName, path, host)); } + return false; } } @@ -3926,10 +4087,12 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso { return true; } + if (outxml == null) { return false; } + Hashtable KeysCache=null, objcache=null; if (parentListenerOrCert.Equals(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) { @@ -3979,6 +4142,7 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso { return true; } + return false; } @@ -3999,6 +4163,7 @@ private void GetChildItemsRecurse(string path, string childname, ProviderMethods { path = path + WSManStringLiterals.DefaultPathSeparator + childname; } + if (HasChildItems(path)) { GetChildItemsOrNames(path, ProviderMethods.GetChildItems, recurse); @@ -4030,8 +4195,10 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool { WriteItemObject(hostname, WSManStringLiterals.rootpath, true); } + break; } + return; } @@ -4064,6 +4231,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool } } } + lock(WSManHelper.AutoSession) { object sessionobj; @@ -4089,13 +4257,16 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool WritePSObjectPropertyNames(obj, path); break; } + return; } + XmlDocument outxml = FindResourceValue(sessionobj, uri, null); if (outxml == null || !outxml.HasChildNodes) { return; } + if (path.Contains(strPathchk + WSManStringLiterals.containerListener)) { GetChildItemOrNamesForListenerOrCertMapping(outxml, WSManStringLiterals.containerListener, path, host, methodname, recurse); @@ -4121,12 +4292,14 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool WritePSObjectPropertiesAsWSManElementObjects(obj, path, new string[] { "Name=" + p.Name }, null, WsManElementObjectTypes.WSManConfigContainerElement, recurse); //WriteItemObject(new PSObject(new WSManConfigContainerElement(p.Name, p.Value.ToString(), new string[] { "Name=" + p.Name })), path + WSManStringLiterals.DefaultPathSeparator + p.Name, true); } + break; //Get the names of container at Plugin level case ProviderMethods.GetChildNames: WritePSObjectPropertyNames(objPluginNames, path); break; } + return; } else @@ -4137,6 +4310,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool { return; } + PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML, true); ArrayList arrSecurity = null; ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity); @@ -4155,6 +4329,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool WritePSObjectPropertyNames(objPluginlevel, path); break; } + return; } @@ -4219,9 +4394,11 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool break; } } + return; } } + strPathchk = strPathchk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathchk.Length); string sResourceDirName = String.Empty; @@ -4238,6 +4415,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool { return; } + if (path.Contains(strPathchk + sResourceDirName)) { if (path.EndsWith(strPathchk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) @@ -4259,8 +4437,10 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool } } } + return; } + strPathchk = strPathchk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathchk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase) || path.Contains(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + "_")) { @@ -4320,6 +4500,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool { return; } + foreach (PSObject p in arrInitParams) { switch (methodname) @@ -4528,6 +4709,7 @@ private bool IsPathLocalMachine(string host) } } } + return hostfound; } @@ -4577,6 +4759,7 @@ private void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certc Keyscache = null; return; } + foreach (XmlNode node in xmlnodesCerts) { Hashtable InputAttributes = new Hashtable(); @@ -4607,15 +4790,18 @@ private void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certc // //sbCerts.Append(childnode.InnerText); // //keys[2] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; // } + InputAttributes.Add(childnode.LocalName, childnode.InnerText); objCerts.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); } + GenerateObjectNameAndKeys(InputAttributes, WSManStringLiterals.containerCertMapping, WSManStringLiterals.containerClientCertificate, out ItemName, out keys); //lCache.Add(WSManStringLiterals.containerClientCertificate + "_" + Math.Abs(sbCerts.ToString().GetHashCode()), objCerts); lCache.Add(ItemName, objCerts); kCache.Add(ItemName, keys); //kCache.Add(WSManStringLiterals.containerClientCertificate + "_" + Math.Abs(sbCerts.ToString().GetHashCode()), keys); } + Certcache = lCache; Keyscache = kCache; } @@ -4631,6 +4817,7 @@ private void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable list Keyscache = null; return; } + foreach (XmlNode node in xmlnodesListeners) { Hashtable InputAttributes = new Hashtable(); @@ -4655,6 +4842,7 @@ private void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable list // Keys[1] = childnode.LocalName + WSManStringLiterals.Equalto + childnode.InnerText; // objListener.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); //} + if (childnode.LocalName.Equals("ListeningOn")) { string ListeningOnItem = childnode.LocalName + "_" + Math.Abs(childnode.InnerText.GetHashCode()); @@ -4667,12 +4855,14 @@ private void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable list objListener.Properties.Add(new PSNoteProperty(childnode.LocalName, childnode.InnerText)); } } + GenerateObjectNameAndKeys(InputAttributes, WSManStringLiterals.containerListener, WSManStringLiterals.containerListener, out ItemName, out Keys); //lCache.Add(WSManStringLiterals.containerListener + "_" + Math.Abs(sbListener.ToString().GetHashCode()), objListener); lCache.Add(ItemName, objListener); kCache.Add(ItemName, Keys); //kCache.Add(WSManStringLiterals.containerListener + "_" + Math.Abs(sbListener.ToString().GetHashCode()), Keys); } + listenercache = lCache; Keyscache = kCache; } @@ -4747,24 +4937,29 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a objResource.Properties.Add(new PSNoteProperty("ResourceDir", strUniqueResourceId)); } + if (attributecol[i].LocalName.Equals("ExactMatch", StringComparison.OrdinalIgnoreCase)) { objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); ExactMatchFound = true; continue; } + if (attributecol[i].LocalName.Equals("SupportsOptions", StringComparison.OrdinalIgnoreCase)) { objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); SupportsOptionsFound = true; continue; } + objResource.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); } + if (!ExactMatchFound) { objResource.Properties.Add(new PSNoteProperty("ExactMatch", false)); } + if (!SupportsOptionsFound) { objResource.Properties.Add(new PSNoteProperty("SupportsOptions", false)); @@ -4784,6 +4979,7 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a enumcapability.SetValue(nodeCapabilities[i].Attributes["Type"].Value, i); } } + objResource.Properties.Add(new PSNoteProperty("Capability", enumcapability)); objResource.Properties.Add(new PSNoteProperty(WSManStringLiterals.containerSecurity, WSManStringLiterals.ContainerChildValue)); @@ -4795,6 +4991,7 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a } } + arrSecurity = nSecurity; return Resources; } @@ -4820,17 +5017,20 @@ private ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) { Name = attributecol[i].Value; } + if (attributecol[i].LocalName.Equals("Value", StringComparison.OrdinalIgnoreCase)) { String ValueAsXML = attributecol[i].Value; Value = SecurityElement.Escape(ValueAsXML); } } + objInitParam.Properties.Add(new PSNoteProperty(Name, Value)); InitParamLvl.Add(objInitParam); } } } + return InitParamLvl; } @@ -4855,18 +5055,22 @@ private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument { objSecurity.Properties.Add(new PSNoteProperty("SecurityDIR", "Security_" + Math.Abs(UniqueResourceID.GetHashCode()))); } + if (attributecol[i].LocalName.Equals("ExactMatch", StringComparison.OrdinalIgnoreCase)) { objSecurity.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); ExactMatchFound = true; continue; } + objSecurity.Properties.Add(new PSNoteProperty(attributecol[i].LocalName, attributecol[i].Value)); } + if (!ExactMatchFound) { objSecurity.Properties.Add(new PSNoteProperty("ExactMatch", false)); } + objSecurity.Properties.Add(new PSNoteProperty("ResourceDir", UniqueResourceID)); objSecurity.Properties.Add(new PSNoteProperty("ParentResourceUri", ParentResourceUri)); @@ -4874,6 +5078,7 @@ private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument } } } + return arrSecurity; } @@ -4947,6 +5152,7 @@ private string ConstructPluginXml(PSObject objinputparam, string ResourceURI, st if (resources != null) sbvalues.Append(ConstructResourceXml(null, resources, securities)); } + sbvalues.Append(""); return sbvalues.ToString(); } @@ -5041,6 +5247,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources { return sbvalues.ToString(); } + object[] capability = null; sbvalues.Append(""); if (objinputparams != null) @@ -5067,6 +5274,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources } } } + sbvalues.Append(WSManStringLiterals.GreaterThan); if (securities != null) sbvalues.Append(ConstructSecurityXml(null, securities, String.Empty)); @@ -5106,6 +5314,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources } } } + sbvalues.Append(WSManStringLiterals.GreaterThan); if (securities != null) sbvalues.Append(ConstructSecurityXml(null, securities, p.Properties["ResourceDir"].Value.ToString())); @@ -5113,6 +5322,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources sbvalues.Append(""); } } + sbvalues.Append(""); return sbvalues.ToString(); } @@ -5125,6 +5335,7 @@ private string ConstructSecurityXml(PSObject objinputparams, ArrayList securitie { return sbvalues.ToString(); } + if (objinputparams != null) { AddSecurityProperties(objinputparams.Properties, sbvalues); @@ -5139,6 +5350,7 @@ private string ConstructSecurityXml(PSObject objinputparams, ArrayList securitie } } } + return sbvalues.ToString(); } @@ -5162,6 +5374,7 @@ private void AddSecurityProperties( sbValues.Append(WSManStringLiterals.EnclosingDoubleQuotes + propValueStr + WSManStringLiterals.EnclosingDoubleQuotes); } } + sbValues.Append(WSManStringLiterals.GreaterThan); sbValues.Append(""); } @@ -5176,6 +5389,7 @@ private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initpar { return sbvalues.ToString(); } + sbvalues.Append(""); if (objinputparams != null) { @@ -5212,6 +5426,7 @@ private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initpar } } } + sbvalues.Append(""); return sbvalues.ToString(); } @@ -5228,6 +5443,7 @@ private string ConstructCapabilityXml(object[] capabilities) sbvalues.Append(WSManStringLiterals.GreaterThan); sbvalues.Append(""); } + return sbvalues.ToString(); } @@ -5242,6 +5458,7 @@ private bool IsValueOfParamList(string name, string[] paramcontainer) break; } } + return result; } @@ -5340,8 +5557,10 @@ public class WSManProviderNewItemComputerParameters public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -5364,8 +5583,10 @@ public Hashtable OptionSet public AuthenticationMechanism Authentication { get { return authentication; } + set { authentication = value; } } + private AuthenticationMechanism authentication = AuthenticationMechanism.Default; /// @@ -5377,8 +5598,10 @@ public AuthenticationMechanism Authentication public string CertificateThumbprint { get { return thumbPrint; } + set { thumbPrint = value; } } + private string thumbPrint = null; /// @@ -5393,8 +5616,10 @@ public string CertificateThumbprint public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -5406,8 +5631,10 @@ public SessionOption SessionOption public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = "wsman"; /// @@ -5421,8 +5648,10 @@ public String ApplicationName public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -5436,8 +5665,10 @@ public Int32 Port public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; /// @@ -5452,8 +5683,10 @@ public SwitchParameter UseSSL public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; } @@ -5474,8 +5707,10 @@ public class WSManProviderNewItemPluginParameters public string Plugin { get { return _plugin; } + set { _plugin = value; } } + private string _plugin; /// @@ -5486,8 +5721,10 @@ public string Plugin public string FileName { get { return _filename; } + set { _filename = value; } } + private string _filename; /// @@ -5499,8 +5736,10 @@ public string FileName public string SDKVersion { get { return _sdkversion; } + set { _sdkversion = value; } } + private string _sdkversion; /// @@ -5511,8 +5750,10 @@ public string SDKVersion public System.Uri Resource { get { return _resourceuri; } + set { _resourceuri = value; } } + private System.Uri _resourceuri; /// @@ -5524,8 +5765,10 @@ public System.Uri Resource public object[] Capability { get { return _capability; } + set { _capability = value; } } + private object[] _capability; /// @@ -5537,8 +5780,10 @@ public object[] Capability public string XMLRenderingType { get { return _xmlRenderingtype; } + set { _xmlRenderingtype = value; } } + private string _xmlRenderingtype; /// @@ -5549,8 +5794,10 @@ public string XMLRenderingType public string File { get { return _file; } + set { _file = value; } } + private string _file; /// @@ -5561,8 +5808,10 @@ public string File public PSCredential RunAsCredential { get { return this.runAsCredentials; } + set { this.runAsCredentials = value; } } + private PSCredential runAsCredentials; /// @@ -5572,8 +5821,10 @@ public PSCredential RunAsCredential public SwitchParameter UseSharedProcess { get { return this.sharedHost; } + set { this.sharedHost = value; } } + private bool sharedHost; /// @@ -5583,8 +5834,10 @@ public SwitchParameter UseSharedProcess public SwitchParameter AutoRestart { get { return this.autoRestart; } + set { this.autoRestart = value; } } + private bool autoRestart; /// @@ -5597,11 +5850,13 @@ public uint? ProcessIdleTimeoutSec { return this.processIdleTimeoutSeconds; } + set { this.processIdleTimeoutSeconds = value; } } + private uint? processIdleTimeoutSeconds; } @@ -5621,8 +5876,10 @@ public class WSManProviderInitializeParameters public string ParamName { get { return _paramname; } + set { _paramname = value; } } + private string _paramname; /// @@ -5634,8 +5891,10 @@ public string ParamName public string ParamValue { get { return _paramvalue; } + set { _paramvalue = value; } } + private string _paramvalue; } @@ -5653,8 +5912,10 @@ public class WSManProviderNewItemResourceParameters public System.Uri ResourceUri { get { return _resourceuri; } + set { _resourceuri = value; } } + private System.Uri _resourceuri; /// @@ -5666,8 +5927,10 @@ public System.Uri ResourceUri public object[] Capability { get { return _capability; } + set { _capability = value; } } + private object[] _capability; } @@ -5685,8 +5948,10 @@ public class WSManProviderNewItemSecurityParameters public string Sddl { get { return _sddl; } + set { _sddl = value; } } + private string _sddl; } @@ -5708,11 +5973,13 @@ public string Issuer { return _issuer; } + set { _issuer = value; } } + private string _issuer; /// @@ -5726,11 +5993,13 @@ public string Subject { return _subject; } + set { _subject = value; } } + private string _subject = "*"; /// @@ -5745,11 +6014,13 @@ public System.Uri URI { return _uri; } + set { _uri = value; } } + private System.Uri _uri = new Uri("*", UriKind.RelativeOrAbsolute); /// @@ -5762,11 +6033,13 @@ public bool Enabled { return _enabled; } + set { _enabled = value; } } + private bool _enabled = true; } @@ -5792,11 +6065,13 @@ public string Address { return _address; } + set { _address = value; } } + private string _address; /// @@ -5810,11 +6085,13 @@ public string Transport { return _transport; } + set { _transport = value; } } + private string _transport = "http"; /// @@ -5828,12 +6105,14 @@ public int Port { return _port; } + set { _port = value; _IsPortSpecified = true; } } + private int _port = 0; /// @@ -5847,11 +6126,13 @@ public string HostName { return _hostName; } + set { _hostName = value; } } + private string _hostName; /// @@ -5864,11 +6145,13 @@ public bool Enabled { return _enabled; } + set { _enabled = value; } } + private bool _enabled = true; /// @@ -5884,11 +6167,13 @@ public string URLPrefix { return _urlprefix; } + set { _urlprefix = value; } } + private string _urlprefix = "wsman"; /// @@ -5903,11 +6188,13 @@ public string CertificateThumbPrint { return _certificatethumbprint; } + set { _certificatethumbprint = value; } } + private string _certificatethumbprint; /// @@ -5919,12 +6206,14 @@ public bool IsPortSpecified { return _IsPortSpecified; } + set { _IsPortSpecified = value; } } + private bool _IsPortSpecified = false; } @@ -5947,8 +6236,10 @@ public class WSManProviderSetItemDynamicParameters public SwitchParameter Concatenate { get { return _concatenate; } + set { _concatenate = value; } } + private SwitchParameter _concatenate = false; } @@ -6205,6 +6496,7 @@ function Start-WSManServiceD15A7957836142a18627D7E1D342DD82 Restart-Service WinRM -Force -Confirm:$false return $true }} + return $false }} #end of Begin block }} @@ -6225,6 +6517,7 @@ public class WSManConfigElement internal WSManConfigElement() { } + internal WSManConfigElement(string name, string typenameofelement) { _name = name; @@ -6237,9 +6530,11 @@ internal WSManConfigElement(string name, string typenameofelement) public string Name { get { return _name; } + set { _name = value; } } + private string _name; /// @@ -6248,8 +6543,10 @@ public string Name public string TypeNameOfElement { get { return _typenameofelement; } + set { _typenameofelement = value; } } + private string _typenameofelement; /// @@ -6258,6 +6555,7 @@ public string TypeNameOfElement public string Type { get { return _typenameofelement; } + set { _typenameofelement = value; } } } @@ -6269,6 +6567,7 @@ public class WSManConfigLeafElement : WSManConfigElement internal WSManConfigLeafElement() { } + internal WSManConfigLeafElement(string Name, object Value, string TypeNameOfElement, object SourceOfValue = null) { _value = Value; @@ -6283,9 +6582,11 @@ internal WSManConfigLeafElement(string Name, object Value, string TypeNameOfElem public object SourceOfValue { get { return _SourceOfValue; } + set { _SourceOfValue = value; } } + private object _SourceOfValue; /// @@ -6294,9 +6595,11 @@ public object SourceOfValue public object Value { get { return _value; } + set { _value = value; } } + private object _value; } /// @@ -6318,9 +6621,11 @@ internal WSManConfigContainerElement(string Name, string TypeNameOfElement, stri public string[] Keys { get { return _keys; } + set { _keys = value; } } + private string[] _keys; } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index a9933122926..2f4b4269c3c 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -49,8 +49,10 @@ public class WSManCredSSPCommandBase : PSCmdlet public string Role { get { return role; } + set { role = value; } } + private string role; #endregion @@ -135,6 +137,7 @@ private void DisableClientSideSettings() WriteError(er); return; } + m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) @@ -240,6 +243,7 @@ private void DeleteUserDelegateSettings() DeleteDelegateSettings(applicationname, Registry.CurrentUser, key, GPO); } } + KeyHandle = System.IntPtr.Zero; } @@ -271,8 +275,10 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, otherkeys = true; } } + Allow_Fresh_Credential_Key.DeleteValue(value); } + foreach (string keyvalue in KeyCollection) { Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), keyvalue, RegistryValueKind.String); @@ -280,6 +286,7 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, } } } + if (!otherkeys) { rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); @@ -290,17 +297,20 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, { rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false); } + object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh); if (regval2 != null) { rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false); } + if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null) { rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials); } } } + GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814")); } catch (InvalidOperationException ex) @@ -399,8 +409,10 @@ public class EnableWSManCredSSPCommand : WSManCredSSPCommandBase, IDisposable/*, public String[] DelegateComputer { get { return delegatecomputer; } + set { delegatecomputer = value; } } + private String[] delegatecomputer; /// @@ -410,8 +422,10 @@ public String[] DelegateComputer public SwitchParameter Force { get { return force; } + set { force = value; } } + private bool force = false; //helper variable @@ -773,6 +787,7 @@ private string GetDelegateSettings(string applicationname) } } } + if (result.EndsWith(listvalue, StringComparison.OrdinalIgnoreCase)) { result = result.Remove(result.Length - 1); @@ -796,6 +811,7 @@ private string GetDelegateSettings(string applicationname) ErrorRecord er = new ErrorRecord(ex, "ObjectDisposedException", ErrorCategory.PermissionDenied, null); WriteError(er); } + return result; } # endregion private diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index 8ae0ace4ecc..7e101ebd536 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -1058,6 +1058,7 @@ public class WSManClass public class GPClass { } + [ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IGroupPolicyObject diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 83ca65daeb6..5c0cc1e6530 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -38,8 +38,10 @@ public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable public String Action { get { return action; } + set { action = value; } } + private String action; /// @@ -51,8 +53,10 @@ public String Action public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// @@ -66,6 +70,7 @@ public String ApplicationName public String ComputerName { get { return computername; } + set { computername = value; @@ -76,6 +81,7 @@ public String ComputerName } } + private String computername = null; /// @@ -91,8 +97,10 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; /// @@ -106,8 +114,10 @@ public Uri ConnectionURI public String FilePath { get { return filepath; } + set { filepath = value; } } + private String filepath; /// @@ -123,8 +133,10 @@ public String FilePath public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -137,8 +149,10 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -155,8 +169,10 @@ public Int32 Port public Hashtable SelectorSet { get { return selectorset; } + set { selectorset = value; } } + private Hashtable selectorset; /// @@ -171,8 +187,10 @@ public Hashtable SelectorSet public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -186,8 +204,10 @@ public SessionOption SessionOption public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; /// @@ -201,8 +221,10 @@ public SwitchParameter UseSSL public Hashtable ValueSet { get { return valueset; } + set { valueset = value; } } + private Hashtable valueset; /// @@ -217,8 +239,10 @@ public Hashtable ValueSet public Uri ResourceURI { get { return resourceuri; } + set { resourceuri = value; } } + private Uri resourceuri; private WSManHelper helper; @@ -269,10 +293,12 @@ protected override void ProcessRecord() { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } + if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } + if (m_session != null) Dispose(m_session); diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 594acf9f535..7c8c142fa2a 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -39,11 +39,13 @@ public ProxyAccessType ProxyAccessType { return _proxyaccesstype; } + set { _proxyaccesstype = value; } } + private ProxyAccessType _proxyaccesstype; /// @@ -60,11 +62,13 @@ public ProxyAccessType ProxyAccessType public ProxyAuthentication ProxyAuthentication { get { return proxyauthentication; } + set { proxyauthentication = value; } } + private ProxyAuthentication proxyauthentication; /// @@ -76,11 +80,13 @@ public ProxyAuthentication ProxyAuthentication public PSCredential ProxyCredential { get { return _proxycredential; } + set { _proxycredential = value; } } + private PSCredential _proxycredential; /// @@ -95,11 +101,13 @@ public PSCredential ProxyCredential public SwitchParameter SkipCACheck { get { return skipcacheck; } + set { skipcacheck = value; } } + private bool skipcacheck; /// @@ -112,11 +120,13 @@ public SwitchParameter SkipCACheck public SwitchParameter SkipCNCheck { get { return skipcncheck; } + set { skipcncheck = value; } } + private bool skipcncheck; /// @@ -129,11 +139,13 @@ public SwitchParameter SkipCNCheck public SwitchParameter SkipRevocationCheck { get { return skiprevocationcheck; } + set { skiprevocationcheck = value; } } + private bool skiprevocationcheck; /// @@ -148,11 +160,13 @@ public SwitchParameter SkipRevocationCheck public Int32 SPNPort { get { return spnport; } + set { spnport = value; } } + private Int32 spnport; /// @@ -165,11 +179,13 @@ public Int32 SPNPort public Int32 OperationTimeout { get { return operationtimeout; } + set { operationtimeout = value; } } + private Int32 operationtimeout; /// @@ -182,11 +198,13 @@ public Int32 OperationTimeout public SwitchParameter NoEncryption { get { return noencryption; } + set { noencryption = value; } } + private bool noencryption; /// @@ -199,11 +217,13 @@ public SwitchParameter NoEncryption public SwitchParameter UseUTF16 { get { return useutf16; } + set { useutf16 = value; } } + private bool useutf16; /// @@ -249,11 +269,13 @@ protected override void BeginProcessing() { objSessionOption.UseEncryption = false; } + if (_proxycredential != null) { NetworkCredential nwCredentials = _proxycredential.GetNetworkCredential(); objSessionOption.ProxyCredential = nwCredentials; } + WriteObject(objSessionOption); }//End BeginProcessing() diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index dac4835e1ed..d456cc8473f 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -38,6 +38,7 @@ public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable public String ComputerName { get { return computername; } + set { computername = value; @@ -47,6 +48,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -73,12 +75,14 @@ public String ComputerName public override AuthenticationMechanism Authentication { get { return authentication; } + set { authentication = value; ValidateSpecifiedAuthentication(); } } + private AuthenticationMechanism authentication = AuthenticationMechanism.None; /// @@ -91,8 +95,10 @@ public override AuthenticationMechanism Authentication public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -106,8 +112,10 @@ public Int32 Port public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; /// @@ -119,8 +127,10 @@ public SwitchParameter UseSSL public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index 2e5ff94c794..da8e59aa013 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -42,8 +42,10 @@ public class SetWSManQuickConfigCommand : PSCmdlet, IDisposable public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; //helper variable @@ -57,8 +59,10 @@ public SwitchParameter UseSSL public SwitchParameter Force { get { return force; } + set { force = value; } } + private bool force = false; /// @@ -68,8 +72,10 @@ public SwitchParameter Force public SwitchParameter SkipNetworkProfileCheck { get { return skipNetworkProfileCheck; } + set { skipNetworkProfileCheck = value; } } + private bool skipNetworkProfileCheck = false; /// @@ -86,6 +92,7 @@ protected override void BeginProcessing() { return; } + QuickConfigRemoting(true); QuickConfigRemoting(false); }//End BeginProcessing() @@ -155,6 +162,7 @@ private void QuickConfigRemoting(bool serviceonly) { source = sourceAttribute.Value; } + string rxml = string.Empty; if (enabled.Equals("true")) { @@ -173,6 +181,7 @@ private void QuickConfigRemoting(bool serviceonly) WriteObject(Err_Msg); return; } + if (!enabled.Equals("false")) { ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage")); @@ -208,6 +217,7 @@ private void QuickConfigRemoting(bool serviceonly) { action = "EnableRemoting"; } + rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0); XmlDocument finalxml = new XmlDocument(); finalxml.LoadXml(rxml); @@ -222,6 +232,7 @@ private void QuickConfigRemoting(bool serviceonly) xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status"; xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results"; } + if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded")) { if (serviceonly) @@ -232,6 +243,7 @@ private void QuickConfigRemoting(bool serviceonly) { WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message")); } + WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText); } else @@ -245,6 +257,7 @@ private void QuickConfigRemoting(bool serviceonly) { helper.AssertError(m_SessionObj.Error, true, null); } + if (m_SessionObj != null) Dispose(m_SessionObj); diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 40e5164bc2e..d3e4fd6880a 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -38,12 +38,14 @@ public class AuthenticatingWSManCommand : PSCmdlet public virtual PSCredential Credential { get { return credential; } + set { credential = value; ValidateSpecifiedAuthentication(); } } + private PSCredential credential; /// @@ -67,12 +69,14 @@ public virtual PSCredential Credential public virtual AuthenticationMechanism Authentication { get { return authentication; } + set { authentication = value; ValidateSpecifiedAuthentication(); } } + private AuthenticationMechanism authentication = AuthenticationMechanism.Default; /// @@ -84,12 +88,14 @@ public virtual AuthenticationMechanism Authentication public virtual string CertificateThumbprint { get { return thumbPrint; } + set { thumbPrint = value; ValidateSpecifiedAuthentication(); } } + private string thumbPrint = null; internal void ValidateSpecifiedAuthentication() @@ -122,8 +128,10 @@ public class ConnectWSManCommand : AuthenticatingWSManCommand public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// @@ -137,6 +145,7 @@ public String ApplicationName public String ComputerName { get { return computername; } + set { computername = value; @@ -146,6 +155,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -160,8 +170,10 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; /// @@ -176,8 +188,10 @@ public Uri ConnectionURI public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -191,8 +205,10 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -207,8 +223,10 @@ public Int32 Port public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -222,8 +240,10 @@ public SessionOption SessionOption public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; #endregion @@ -249,15 +269,18 @@ protected override void BeginProcessing() helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } + string crtComputerName = computername; if (crtComputerName == null) { crtComputerName = "localhost"; } + if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.OrdinalIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); } + helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); }//End BeginProcessing() @@ -285,6 +308,7 @@ public class DisconnectWSManCommand : PSCmdlet, IDisposable public String ComputerName { get { return computername; } + set { @@ -295,6 +319,7 @@ public String ComputerName } } } + private String computername = null; #region IDisposable Members @@ -333,10 +358,12 @@ protected override void BeginProcessing() { computername = "localhost"; } + if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.OrdinalIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); } + if (computername.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index caa9dc153e8..0179629bf0f 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -41,11 +41,13 @@ public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable public String ApplicationName { get { return applicationname; } + set { { applicationname = value; } } } + private String applicationname = null; /// @@ -59,11 +61,13 @@ public String ApplicationName public SwitchParameter BasePropertiesOnly { get { return basepropertiesonly; } + set { { basepropertiesonly = value; } } } + private SwitchParameter basepropertiesonly; /// @@ -78,6 +82,7 @@ public SwitchParameter BasePropertiesOnly public String ComputerName { get { return computername; } + set { computername = value; @@ -87,6 +92,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -105,11 +111,13 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { { connectionuri = value; } } } + private Uri connectionuri; /// @@ -120,11 +128,13 @@ public Uri ConnectionURI public Uri Dialect { get { return dialect; } + set { { dialect = value; } } } + private Uri dialect; /// @@ -138,11 +148,13 @@ public Uri Dialect public SwitchParameter Enumerate { get { return enumerate; } + set { { enumerate = value; } } } + private SwitchParameter enumerate; /// @@ -154,11 +166,13 @@ public SwitchParameter Enumerate public String Filter { get { return filter; } + set { { filter = value; } } } + private String filter; /// @@ -172,11 +186,13 @@ public String Filter public String Fragment { get { return fragment; } + set { { fragment = value; } } } + private String fragment; /// @@ -192,11 +208,13 @@ public String Fragment public Hashtable OptionSet { get { return optionset; } + set { { optionset = value; } } } + private Hashtable optionset; /// @@ -208,11 +226,13 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { { port = value; } } } + private Int32 port = 0; /// @@ -226,11 +246,13 @@ public Int32 Port public SwitchParameter Associations { get { return associations; } + set { { associations = value; } } } + private SwitchParameter associations; /// @@ -247,11 +269,13 @@ public SwitchParameter Associations public Uri ResourceURI { get { return resourceuri; } + set { { resourceuri = value; } } } + private Uri resourceuri; /// @@ -274,11 +298,13 @@ public Uri ResourceURI public String ReturnType { get { return returntype; } + set { { returntype = value; } } } + private String returntype="object"; /// @@ -294,11 +320,13 @@ public String ReturnType public Hashtable SelectorSet { get { return selectorset; } + set { { selectorset = value; } } } + private Hashtable selectorset; /// @@ -313,11 +341,13 @@ public Hashtable SelectorSet public SessionOption SessionOption { get { return sessionoption; } + set { { sessionoption = value; } } } + private SessionOption sessionoption; /// @@ -331,11 +361,13 @@ public SessionOption SessionOption public SwitchParameter Shallow { get { return shallow; } + set { { shallow = value; } } } + private SwitchParameter shallow; /// @@ -352,11 +384,13 @@ public SwitchParameter Shallow public SwitchParameter UseSSL { get { return usessl; } + set { { usessl = value; } } } + private SwitchParameter usessl; #endregion parameter @@ -373,6 +407,7 @@ private string GetFilter() //mismatched property name/value pair return null; } + filter = ""; for (int i = 0; i" + value + ""; } + filter = filter + ""; return (filter.ToString()); } @@ -419,6 +455,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman { flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } + if (dialect != null && filter != null) { @@ -437,6 +474,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman { flags |= wsmanObject.EnumerationFlagAssociatedInstance(); } + fragment = helper.URI_ASSOCIATION_DIALECT; dialect = new Uri(fragment); } @@ -446,6 +484,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman fragment = helper.URI_SELECTOR_DIALECT; dialect = new Uri(fragment); } + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) @@ -499,6 +538,7 @@ protected override void ProcessRecord() } } + try { IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); @@ -544,10 +584,12 @@ protected override void ProcessRecord() { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } + if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } + if (m_session != null) Dispose(m_session); } @@ -613,8 +655,10 @@ public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// @@ -628,6 +672,7 @@ public String ApplicationName public String ComputerName { get { return computername; } + set { computername = value; @@ -637,6 +682,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -651,8 +697,10 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; /// @@ -664,8 +712,10 @@ public Uri ConnectionURI public Uri Dialect { get { return dialect; } + set { dialect = value; } } + private Uri dialect; /// @@ -679,8 +729,10 @@ public Uri Dialect public string FilePath { get { return filepath; } + set { filepath = value; } } + private string filepath; /// @@ -694,8 +746,10 @@ public string FilePath public String Fragment { get { return fragment; } + set { fragment = value; } } + private String fragment; /// @@ -712,8 +766,10 @@ public String Fragment public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -726,8 +782,10 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -744,8 +802,10 @@ public Int32 Port public Uri ResourceURI { get { return resourceuri; } + set { resourceuri = value; } } + private Uri resourceuri; /// @@ -762,8 +822,10 @@ public Uri ResourceURI public Hashtable SelectorSet { get { return selectorset; } + set { selectorset = value; } } + private Hashtable selectorset; /// @@ -778,8 +840,10 @@ public Hashtable SelectorSet public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -794,8 +858,10 @@ public SessionOption SessionOption public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; /// @@ -809,8 +875,10 @@ public SwitchParameter UseSSL public Hashtable ValueSet { get { return valueset; } + set { valueset = value; } } + private Hashtable valueset; #endregion @@ -855,6 +923,7 @@ protected override void ProcessRecord() } } + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); @@ -891,10 +960,12 @@ protected override void ProcessRecord() { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } + if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } + if (m_session != null) Dispose(m_session); } @@ -960,8 +1031,10 @@ public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposabl public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// @@ -975,6 +1048,7 @@ public String ApplicationName public String ComputerName { get { return computername; } + set { computername = value; @@ -984,6 +1058,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -998,8 +1073,10 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; /// @@ -1016,8 +1093,10 @@ public Uri ConnectionURI public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -1030,8 +1109,10 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -1048,8 +1129,10 @@ public Int32 Port public Uri ResourceURI { get { return resourceuri; } + set { resourceuri = value; } } + private Uri resourceuri; /// @@ -1066,8 +1149,10 @@ public Uri ResourceURI public Hashtable SelectorSet { get { return selectorset; } + set { selectorset = value; } } + private Hashtable selectorset; /// @@ -1082,8 +1167,10 @@ public Hashtable SelectorSet public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -1098,8 +1185,10 @@ public SessionOption SessionOption public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; #endregion @@ -1132,6 +1221,7 @@ protected override void ProcessRecord() } } + IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string ResourceURI = helper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); @@ -1151,10 +1241,12 @@ protected override void ProcessRecord() { helper.AssertError(m_session.Error, true, resourceuri); } + if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } + if (m_session != null) Dispose(m_session); @@ -1209,8 +1301,10 @@ public class NewWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable public String ApplicationName { get { return applicationname; } + set { applicationname = value; } } + private String applicationname = null; /// @@ -1224,6 +1318,7 @@ public String ApplicationName public String ComputerName { get { return computername; } + set { computername = value; @@ -1233,6 +1328,7 @@ public String ComputerName } } } + private String computername = null; /// @@ -1248,8 +1344,10 @@ public String ComputerName public Uri ConnectionURI { get { return connectionuri; } + set { connectionuri = value; } } + private Uri connectionuri; /// @@ -1263,8 +1361,10 @@ public Uri ConnectionURI public String FilePath { get { return filepath; } + set { filepath = value; } } + private String filepath; /// @@ -1279,8 +1379,10 @@ public String FilePath public Hashtable OptionSet { get { return optionset; } + set { optionset = value; } } + private Hashtable optionset; /// @@ -1293,8 +1395,10 @@ public Hashtable OptionSet public Int32 Port { get { return port; } + set { port = value; } } + private Int32 port = 0; /// @@ -1308,8 +1412,10 @@ public Int32 Port public Uri ResourceURI { get { return resourceuri; } + set { resourceuri = value; } } + private Uri resourceuri; /// @@ -1325,8 +1431,10 @@ public Uri ResourceURI public Hashtable SelectorSet { get { return selectorset; } + set { selectorset = value; } } + private Hashtable selectorset; /// @@ -1340,8 +1448,10 @@ public Hashtable SelectorSet public SessionOption SessionOption { get { return sessionoption; } + set { sessionoption = value; } } + private SessionOption sessionoption; /// @@ -1355,8 +1465,10 @@ public SessionOption SessionOption public SwitchParameter UseSSL { get { return usessl; } + set { usessl = value; } } + private SwitchParameter usessl; /// @@ -1369,8 +1481,10 @@ public SwitchParameter UseSSL public Hashtable ValueSet { get { return valueset; } + set { valueset = value; } } + private Hashtable valueset; private WSManHelper helper; @@ -1435,10 +1549,12 @@ protected override void ProcessRecord() { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } + if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } + if (m_session != null) { Dispose(m_session); diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 3d343731182..bc357e043a9 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -100,6 +100,7 @@ internal class Sessions ReleaseSessions(); } } + internal static Sessions AutoSession = new Sessions(); // // @@ -121,8 +122,10 @@ internal static void ReleaseSessions() { //Somehow the object was a null reference. Ignore the error } + sessionobj=null; } + Sessions.SessionObjCache.Clear(); } } @@ -192,6 +195,7 @@ private static string FormatResourceMsgFromResourcetextS( result = String.Format(CultureInfo.CurrentCulture, template, args); } + return result; } @@ -221,6 +225,7 @@ internal void AddtoDictionary(string key, Object value) { //Somehow the object was a null reference. Ignore the error } + Sessions.SessionObjCache.Remove(key); Sessions.SessionObjCache.Add(key, value); } @@ -245,9 +250,11 @@ internal object RemoveFromDictionary(string computer) { //Somehow the object was a null reference. Ignore the error } + Sessions.SessionObjCache.Remove(computer); } } + return objsession; } @@ -277,6 +284,7 @@ internal static Dictionary GetSessionObjCache() catch (COMException) { } + return Sessions.SessionObjCache; } @@ -307,6 +315,7 @@ internal string GetRootNodeName(string operation, string resourceUri, string act //error } } + return resultStr; } @@ -325,6 +334,7 @@ internal string ReadFile(string path) { throw new ArgumentException(GetResourceMsgFromResourcetext("InvalidFileName")); } + string strOut = null; try { @@ -367,12 +377,14 @@ internal string ReadFile(string path) // _sr.Close(); _sr.Dispose(); } + if (_fs != null) { //_fs.Close(); _fs.Dispose(); } } + return strOut; } @@ -388,6 +400,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, { throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); } + resultString = ReadFile(filepath); return resultString; } @@ -411,9 +424,11 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, parameters = parameters + " " + ATTR_NIL; nilns = " " + NS_XSI; } + parameters = parameters + ">" + entry.Value.ToString() + ""; } } + resultString = "" + parameters + ""; break; @@ -462,6 +477,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, } } } + if (string.IsNullOrEmpty(entry.Key.ToString())) { //XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); @@ -501,6 +517,7 @@ internal XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnam { nsmgr.AddNamespace("cfg", xmlnamespace); } + node = xDoc.SelectSingleNode(xpathpattern, nsmgr); return node; } @@ -527,11 +544,13 @@ internal string CreateConnectionString(Uri ConnUri, int port, string computernam { ConnectionString = ConnectionString + ":" + port; } + if (applicationname != null) { ConnectionString = ConnectionString + "/" + applicationname; } } + return ConnectionString; } @@ -544,6 +563,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha { resource = resourceuri.ToString(); } + if (selectorset != null) { resource = resource + "?"; @@ -556,6 +576,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha resource += "+"; } } + IWSManResourceLocator m_resource = null; try { @@ -590,6 +611,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha { AssertError(ex.Message, false, null); } + return m_resource; } @@ -640,26 +662,32 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNoAuthentication; } + if (authentication.Equals(AuthenticationMechanism.Basic)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } + if (authentication.Equals(AuthenticationMechanism.Negotiate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNegotiate; } + if (authentication.Equals(AuthenticationMechanism.Kerberos)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseKerberos; } + if (authentication.Equals(AuthenticationMechanism.Digest)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } + if (authentication.Equals(AuthenticationMechanism.Credssp)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } + if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; @@ -691,6 +719,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName; } + connObject.Password = nwCredential.Password; if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { @@ -741,6 +770,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest(); } + if (sessionoption.ProxyCredential != null) { try @@ -758,18 +788,22 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM } } + if (sessionoption.SkipCACheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCACheck; } + if (sessionoption.SkipCNCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCNCheck; } + if (sessionoption.SPNPort > 0) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagEnableSpnServerPort; } + if (sessionoption.UseUtf16) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf16; @@ -779,10 +813,12 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM //If UseUtf16 is false, then default Encoding is Utf8 sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8; } + if (!sessionoption.UseEncryption) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagNoEncryption; } + if (sessionoption.SkipRevocationCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipRevocationCheck; @@ -815,6 +851,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { AssertError(ex.Message, false, null); } + return m_SessionObj; } @@ -826,6 +863,7 @@ internal void CleanUp() _sr.Dispose(); _sr = null; } + if (_fs != null) { _fs.Dispose(); @@ -847,6 +885,7 @@ internal string GetFilterString(Hashtable seletorset) filter.Append("+"); } } + filter.Remove(filter.ToString().Length - 1, 1); return filter.ToString(); } @@ -927,6 +966,7 @@ internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } + IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl); m_session.Identify(0); string key = computername; @@ -934,6 +974,7 @@ internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, { key = "localhost"; } + AddtoDictionary(key, m_session); } catch (IndexOutOfRangeException) @@ -1098,11 +1139,13 @@ internal static string GetResourceString(string Key) { LoadResourceData(); } + string value = string.Empty; if (ResourceValueCache.ContainsKey(Key.Trim())) { ResourceValueCache.TryGetValue(Key.Trim(), out value); } + return value.Trim(); } From 5cc03b56702d45dc4f4e85068791eda74d201f93 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:31 -0800 Subject: [PATCH 13/81] Update Microsoft.WSMan.Runtime --- .../WSManSessionOption.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index 8841dc0c3a9..a6e50e7449c 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -33,11 +33,13 @@ public sealed class SessionOption public bool SkipCACheck { get { return _SkipCACheck; } + set { _SkipCACheck = value; } } + private bool _SkipCACheck; /// @@ -46,11 +48,13 @@ public bool SkipCACheck public bool SkipCNCheck { get { return _SkipCNCheck; } + set { _SkipCNCheck = value; } } + private bool _SkipCNCheck; /// @@ -59,12 +63,14 @@ public bool SkipCNCheck public bool SkipRevocationCheck { get { return _SkipRevocationCheck; } + set { _SkipRevocationCheck = value; } } + private bool _SkipRevocationCheck; /// @@ -73,11 +79,13 @@ public bool SkipRevocationCheck public bool UseEncryption { get { return _useencryption; } + set { _useencryption = value; } } + private bool _useencryption = true; /// @@ -86,11 +94,13 @@ public bool UseEncryption public bool UseUtf16 { get { return _UTF16; } + set { _UTF16 = value; } } + private bool _UTF16; /// @@ -99,11 +109,13 @@ public bool UseUtf16 public ProxyAuthentication ProxyAuthentication { get { return _ProxyAuthentication; } + set { _ProxyAuthentication = value; } } + private ProxyAuthentication _ProxyAuthentication; /// @@ -113,6 +125,7 @@ public ProxyAuthentication ProxyAuthentication public int SPNPort { get { return _SPNPort; } + set { _SPNPort = value; @@ -127,11 +140,13 @@ public int SPNPort public int OperationTimeout { get { return _OperationTimeout; } + set { _OperationTimeout = value; } } + private int _OperationTimeout; /// @@ -140,11 +155,13 @@ public int OperationTimeout public NetworkCredential ProxyCredential { get { return _ProxyCredential; } + set { _ProxyCredential = value; } } + private NetworkCredential _ProxyCredential; /// @@ -153,6 +170,7 @@ public NetworkCredential ProxyCredential public ProxyAccessType ProxyAccessType { get { return _proxyaccesstype; } + set { _proxyaccesstype = value; From f04d6a6fc5eb026eb4636ef3e76c8340e663e413 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:31 -0800 Subject: [PATCH 14/81] Update ResGen --- src/ResGen/Program.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ResGen/Program.cs b/src/ResGen/Program.cs index 35b8e8ec11a..0a0f21aaa08 100644 --- a/src/ResGen/Program.cs +++ b/src/ResGen/Program.cs @@ -143,6 +143,7 @@ internal class {0} {{ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(""{1}.resources.{3}"", typeof({0}).Assembly); resourceMan = temp; }} + return resourceMan; }} }} @@ -156,6 +157,7 @@ internal class {0} {{ get {{ return resourceCulture; }} + set {{ resourceCulture = value; }} From f259122b17373432e6301ca8f3a4d58733f1d48b Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:31 -0800 Subject: [PATCH 15/81] Update TypeCatalogGen --- src/TypeCatalogGen/TypeCatalogGen.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 710f50baafc..4f54be2f633 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -122,6 +122,7 @@ public static void Main(string[] args) REPLACE '{fullName}' from '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete}) WITH '{strongAssemblyName}' (IsObsolete? {isTypeObsolete})"); } + typeNameToAssemblyMap[fullName] = new TypeMetadata(strongAssemblyName, isTypeObsolete); } else if (printDebugMessage) @@ -157,6 +158,7 @@ private static bool IsTypeObsolete(MetadataReader reader, TypeDefinition typeDef return true; } } + return false; } @@ -196,6 +198,7 @@ private static bool IsAttributeOfType(MetadataReader reader, CustomAttribute cus // constructor is global method, vararg method, or from a generic type. return false; } + break; default: @@ -444,6 +447,7 @@ private Dictionary InitializeTypeCatalog() { sourceCode.AppendLine(string.Format(CultureInfo.InvariantCulture, SourceFormat, pair.Key, pair.Value.AssemblyName)); } + sourceCode.Append(SourceEnd); using (FileStream stream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write)) From e1acfaebed8e28bf43cd973d725008f0f91157ff Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:32 -0800 Subject: [PATCH 16/81] Update commands --- .../commands/AddJobTrigger.cs | 8 +++ .../commands/DisableJobDefinitionBase.cs | 8 +++ .../commands/EnableDisableCmdletBase.cs | 3 + .../commands/GetJobDefinition.cs | 5 ++ .../commands/GetJobTrigger.cs | 8 +++ .../commands/GetScheduledJobOption.cs | 6 ++ .../commands/NewJobTrigger.cs | 34 ++++++++++ .../commands/RegisterJobDefinition.cs | 29 ++++++++ .../commands/RemoveJobTrigger.cs | 8 +++ .../commands/SchedJobCmdletBase.cs | 2 + .../commands/ScheduledJobOptionCmdletBase.cs | 26 ++++++++ .../commands/SetJobDefinition.cs | 32 +++++++++ .../commands/SetJobTrigger.cs | 66 +++++++++++++++++++ .../commands/SetScheduledJobOption.cs | 4 ++ .../commands/UnregisterJobDefinition.cs | 8 +++ 15 files changed, 247 insertions(+) diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs index 4837a664865..7a080a86038 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs @@ -40,8 +40,10 @@ public sealed class AddJobTriggerCommand : ScheduleJobCmdletBase public ScheduledJobTrigger[] Trigger { get { return _triggers; } + set { _triggers = value; } } + private ScheduledJobTrigger[] _triggers; /// @@ -54,8 +56,10 @@ public ScheduledJobTrigger[] Trigger public Int32[] Id { get { return _ids; } + set { _ids = value; } } + private Int32[] _ids; /// @@ -68,8 +72,10 @@ public Int32[] Id public string[] Name { get { return _names; } + set { _names = value; } } + private string[] _names; /// @@ -82,8 +88,10 @@ public string[] Name public ScheduledJobDefinition[] InputObject { get { return _definitions; } + set { _definitions = value; } } + private ScheduledJobDefinition[] _definitions; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs index a6f7f037ed2..cf151d11188 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs @@ -38,8 +38,10 @@ public abstract class DisableScheduledJobDefinitionBase : ScheduleJobCmdletBase public ScheduledJobDefinition InputObject { get { return _definition; } + set { _definition = value; } } + private ScheduledJobDefinition _definition; /// @@ -50,8 +52,10 @@ public ScheduledJobDefinition InputObject public Int32 Id { get { return _definitionId; } + set { _definitionId = value; } } + private Int32 _definitionId; /// @@ -63,8 +67,10 @@ public Int32 Id public string Name { get { return _definitionName; } + set { _definitionName = value; } } + private string _definitionName; /// @@ -76,8 +82,10 @@ public string Name public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private SwitchParameter _passThru; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs index f51ceced32f..196ebb9df0e 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs @@ -35,6 +35,7 @@ public abstract class EnableDisableScheduledJobCmdletBase : ScheduleJobCmdletBas public ScheduledJobTrigger[] InputObject { get { return _triggers; } + set { _triggers = value; } } @@ -45,8 +46,10 @@ public ScheduledJobTrigger[] InputObject public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private SwitchParameter _passThru; private ScheduledJobTrigger[] _triggers; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs index fb1539f6bad..aedaed6237a 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs @@ -30,8 +30,10 @@ public sealed class GetScheduledJobCommand : ScheduleJobCmdletBase public Int32[] Id { get { return _definitionIds; } + set { _definitionIds = value; } } + private Int32[] _definitionIds; /// @@ -44,8 +46,10 @@ public Int32[] Id public string[] Name { get { return _definitionNames; } + set { _definitionNames = value; } } + private string[] _definitionNames; #endregion @@ -77,6 +81,7 @@ protected override void ProcessRecord() WriteObject(definition); }); } + break; case DefinitionNameParameterSet: diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs index dc188dc0676..4b1c3f4df18 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs @@ -40,8 +40,10 @@ public sealed class GetJobTriggerCommand : ScheduleJobCmdletBase public Int32[] TriggerId { get { return _triggerIds; } + set { _triggerIds = value; } } + private Int32[] _triggerIds; /// @@ -53,8 +55,10 @@ public Int32[] TriggerId public ScheduledJobDefinition InputObject { get { return _definition; } + set { _definition = value; } } + private ScheduledJobDefinition _definition; /// @@ -65,8 +69,10 @@ public ScheduledJobDefinition InputObject public Int32 Id { get { return _definitionId; } + set { _definitionId = value; } } + private Int32 _definitionId; /// @@ -78,8 +84,10 @@ public Int32 Id public string Name { get { return _name; } + set { _name = value; } } + private string _name; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs index 07058f03a72..26458fda2df 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs @@ -29,8 +29,10 @@ public sealed class GetScheduledJobOptionCommand : ScheduleJobCmdletBase public Int32 Id { get { return _id; } + set { _id = value; } } + private Int32 _id; /// @@ -42,8 +44,10 @@ public Int32 Id public string Name { get { return _name; } + set { _name = value; } } + private string _name; /// @@ -55,8 +59,10 @@ public string Name public ScheduledJobDefinition InputObject { get { return _definition; } + set { _definition = value; } } + private ScheduledJobDefinition _definition; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs index 4f134ef70d5..2609a905e60 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs @@ -37,8 +37,10 @@ public sealed class NewJobTriggerCommand : ScheduleJobCmdletBase public Int32 DaysInterval { get { return _daysInterval; } + set { _daysInterval = value; } } + private Int32 _daysInterval = 1; /// @@ -48,8 +50,10 @@ public Int32 DaysInterval public Int32 WeeksInterval { get { return _weeksInterval; } + set { _weeksInterval = value; } } + private Int32 _weeksInterval = 1; /// @@ -63,8 +67,10 @@ public Int32 WeeksInterval public TimeSpan RandomDelay { get { return _randomDelay; } + set { _randomDelay = value; } } + private TimeSpan _randomDelay; /// @@ -79,8 +85,10 @@ public TimeSpan RandomDelay public DateTime At { get { return _atTime; } + set { _atTime = value; } } + private DateTime _atTime; /// @@ -92,8 +100,10 @@ public DateTime At public string User { get { return _user; } + set { _user = value; } } + private string _user; /// @@ -106,8 +116,10 @@ public string User public DayOfWeek[] DaysOfWeek { get { return _daysOfWeek; } + set { _daysOfWeek = value; } } + private DayOfWeek[] _daysOfWeek; /// @@ -118,8 +130,10 @@ public DayOfWeek[] DaysOfWeek public SwitchParameter AtStartup { get { return _atStartup; } + set { _atStartup = value; } } + private SwitchParameter _atStartup; /// @@ -130,8 +144,10 @@ public SwitchParameter AtStartup public SwitchParameter AtLogOn { get { return _atLogon; } + set { _atLogon = value; } } + private SwitchParameter _atLogon; /// @@ -142,8 +158,10 @@ public SwitchParameter AtLogOn public SwitchParameter Once { get { return _once; } + set { _once = value; } } + private SwitchParameter _once; /// @@ -153,8 +171,10 @@ public SwitchParameter Once public TimeSpan RepetitionInterval { get { return _repInterval; } + set { _repInterval = value; } } + private TimeSpan _repInterval; /// @@ -164,8 +184,10 @@ public TimeSpan RepetitionInterval public TimeSpan RepetitionDuration { get { return _repDuration; } + set { _repDuration = value; } } + private TimeSpan _repDuration; /// @@ -175,8 +197,10 @@ public TimeSpan RepetitionDuration public SwitchParameter RepeatIndefinitely { get { return _repRepeatIndefinitely; } + set { _repRepeatIndefinitely = value; } } + private SwitchParameter _repRepeatIndefinitely; /// @@ -187,8 +211,10 @@ public SwitchParameter RepeatIndefinitely public SwitchParameter Daily { get { return _daily; } + set { _daily = value; } } + private SwitchParameter _daily; /// @@ -199,8 +225,10 @@ public SwitchParameter Daily public SwitchParameter Weekly { get { return _weekly; } + set { _weekly = value; } } + private SwitchParameter _weekly; #endregion @@ -219,6 +247,7 @@ protected override void BeginProcessing() { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidDaysIntervalParam); } + if (_weeksInterval < 1) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); @@ -281,24 +310,29 @@ private void CreateOnceTrigger() { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepeatIndefinitelyParams); } + if (!MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval))) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionRepeatParams); } + _repDuration = TimeSpan.MaxValue; } else if (!MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || !MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration))) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParams); } + if (_repInterval < TimeSpan.Zero || _repDuration < TimeSpan.Zero) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues); } + if (_repInterval < TimeSpan.FromMinutes(1)) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue); } + if (_repInterval > _repDuration) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval); diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs index c724cf77962..aa8d4851ae7 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs @@ -36,8 +36,10 @@ public sealed class RegisterScheduledJobCommand : ScheduleJobCmdletBase public string FilePath { get { return _filePath; } + set { _filePath = value; } } + private string _filePath; /// @@ -49,8 +51,10 @@ public string FilePath public ScriptBlock ScriptBlock { get { return _scriptBlock; } + set { _scriptBlock = value; } } + private ScriptBlock _scriptBlock; /// @@ -64,8 +68,10 @@ public ScriptBlock ScriptBlock public string Name { get { return _name; } + set { _name = value; } } + private string _name; /// @@ -78,8 +84,10 @@ public string Name public ScheduledJobTrigger[] Trigger { get { return _triggers; } + set { _triggers = value; } } + private ScheduledJobTrigger[] _triggers; /// @@ -91,8 +99,10 @@ public ScheduledJobTrigger[] Trigger public ScriptBlock InitializationScript { get { return _initializationScript; } + set { _initializationScript = value; } } + private ScriptBlock _initializationScript; /// @@ -103,8 +113,10 @@ public ScriptBlock InitializationScript public SwitchParameter RunAs32 { get { return _runAs32; } + set { _runAs32 = value; } } + private SwitchParameter _runAs32; /// @@ -116,8 +128,10 @@ public SwitchParameter RunAs32 public PSCredential Credential { get { return _credential; } + set { _credential = value; } } + private PSCredential _credential; /// @@ -128,8 +142,10 @@ public PSCredential Credential public AuthenticationMechanism Authentication { get { return _authenticationMechanism; } + set { _authenticationMechanism = value; } } + private AuthenticationMechanism _authenticationMechanism; /// @@ -141,8 +157,10 @@ public AuthenticationMechanism Authentication public ScheduledJobOptions ScheduledJobOption { get { return _options; } + set { _options = value; } } + private ScheduledJobOptions _options; /// @@ -155,8 +173,10 @@ public ScheduledJobOptions ScheduledJobOption public object[] ArgumentList { get { return _arguments; } + set { _arguments = value; } } + private object[] _arguments; /// @@ -167,8 +187,10 @@ public object[] ArgumentList public int MaxResultCount { get { return _executionHistoryLength; } + set { _executionHistoryLength = value; } } + private int _executionHistoryLength; /// @@ -179,8 +201,10 @@ public int MaxResultCount public SwitchParameter RunNow { get { return _runNow; } + set { _runNow = value; } } + private SwitchParameter _runNow; /// @@ -192,8 +216,10 @@ public SwitchParameter RunNow public TimeSpan RunEvery { get { return _runEvery; } + set { _runEvery = value; } } + private TimeSpan _runEvery; #endregion @@ -238,6 +264,7 @@ protected override void ProcessRecord() return; } + definition.SetExecutionHistoryLength(MaxResultCount, false); } @@ -333,6 +360,7 @@ private ScheduledJobDefinition CreateFilePathDefinition() return null; } + Collection pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(FilePath); if (pathInfos.Count != 1) { @@ -343,6 +371,7 @@ private ScheduledJobDefinition CreateFilePathDefinition() return null; } + parameterCollection.Add(ScheduledJobInvocationInfo.FilePathParameter, pathInfos[0].Path); JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameterCollection); diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs index 2456b46de6e..f1c225da995 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs @@ -37,8 +37,10 @@ public sealed class RemoveJobTriggerCommand : ScheduleJobCmdletBase public Int32[] TriggerId { get { return _triggerIds; } + set { _triggerIds = value; } } + private Int32[] _triggerIds; /// @@ -51,8 +53,10 @@ public Int32[] TriggerId public Int32[] Id { get { return _definitionIds; } + set { _definitionIds = value; } } + private Int32[] _definitionIds; /// @@ -65,8 +69,10 @@ public Int32[] Id public string[] Name { get { return _names; } + set { _names = value; } } + private string[] _names; /// @@ -79,8 +85,10 @@ public string[] Name public ScheduledJobDefinition[] InputObject { get { return _definitions; } + set { _definitions = value; } } + private ScheduledJobDefinition[] _definitions; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs index 6021aa6ea97..eddeb199789 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs @@ -370,10 +370,12 @@ internal static void AddRepetitionJobTriggerToDefinition( { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues); } + if (repInterval < TimeSpan.FromMinutes(1)) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue); } + if (repInterval > repDuration) { throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval); diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs index 4971658086f..5d0bd636fa6 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs @@ -26,8 +26,10 @@ public abstract class ScheduledJobOptionCmdletBase : ScheduleJobCmdletBase public SwitchParameter RunElevated { get { return _runElevated; } + set { _runElevated = value; } } + private SwitchParameter _runElevated = false; /// @@ -37,8 +39,10 @@ public SwitchParameter RunElevated public SwitchParameter HideInTaskScheduler { get { return _hideInTaskScheduler; } + set { _hideInTaskScheduler = value; } } + private SwitchParameter _hideInTaskScheduler = false; /// @@ -49,8 +53,10 @@ public SwitchParameter HideInTaskScheduler public SwitchParameter RestartOnIdleResume { get { return _restartOnIdleResume; } + set { _restartOnIdleResume = value; } } + private SwitchParameter _restartOnIdleResume = false; /// @@ -60,8 +66,10 @@ public SwitchParameter RestartOnIdleResume public TaskMultipleInstancePolicy MultipleInstancePolicy { get { return _multipleInstancePolicy; } + set { _multipleInstancePolicy = value; } } + private TaskMultipleInstancePolicy _multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew; /// @@ -71,8 +79,10 @@ public TaskMultipleInstancePolicy MultipleInstancePolicy public SwitchParameter DoNotAllowDemandStart { get { return _doNotAllowDemandStart; } + set { _doNotAllowDemandStart = value; } } + private SwitchParameter _doNotAllowDemandStart = false; /// @@ -82,8 +92,10 @@ public SwitchParameter DoNotAllowDemandStart public SwitchParameter RequireNetwork { get { return _requireNetwork; } + set { _requireNetwork = value; } } + private SwitchParameter _requireNetwork = false; /// @@ -93,8 +105,10 @@ public SwitchParameter RequireNetwork public SwitchParameter StopIfGoingOffIdle { get { return _stopIfGoingOffIdle; } + set { _stopIfGoingOffIdle = value; } } + private SwitchParameter _stopIfGoingOffIdle = false; /// @@ -105,8 +119,10 @@ public SwitchParameter StopIfGoingOffIdle public SwitchParameter WakeToRun { get { return _wakeToRun; } + set { _wakeToRun = value; } } + private SwitchParameter _wakeToRun = false; /// @@ -116,8 +132,10 @@ public SwitchParameter WakeToRun public SwitchParameter ContinueIfGoingOnBattery { get { return _continueIfGoingOnBattery; } + set { _continueIfGoingOnBattery = value; } } + private SwitchParameter _continueIfGoingOnBattery = false; /// @@ -127,8 +145,10 @@ public SwitchParameter ContinueIfGoingOnBattery public SwitchParameter StartIfOnBattery { get { return _startIfOnBattery; } + set { _startIfOnBattery = value; } } + private SwitchParameter _startIfOnBattery = false; /// @@ -139,8 +159,10 @@ public SwitchParameter StartIfOnBattery public TimeSpan IdleTimeout { get { return _idleTimeout; } + set { _idleTimeout = value; } } + private TimeSpan _idleTimeout = new TimeSpan(1, 0, 0); /// @@ -150,8 +172,10 @@ public TimeSpan IdleTimeout public TimeSpan IdleDuration { get { return _idleDuration; } + set { _idleDuration = value; } } + private TimeSpan _idleDuration = new TimeSpan(0, 10, 0); /// @@ -161,8 +185,10 @@ public TimeSpan IdleDuration public SwitchParameter StartIfIdle { get { return _startIfIdle; } + set { _startIfIdle = value; } } + private SwitchParameter _startIfIdle = false; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs index f9f9e2e6f62..1a322c070df 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs @@ -34,8 +34,10 @@ public sealed class SetScheduledJobCommand : ScheduleJobCmdletBase public string Name { get { return _name; } + set { _name = value; } } + private string _name; /// @@ -47,8 +49,10 @@ public string Name public string FilePath { get { return _filePath; } + set { _filePath = value; } } + private string _filePath; /// @@ -59,8 +63,10 @@ public string FilePath public ScriptBlock ScriptBlock { get { return _scriptBlock; } + set { _scriptBlock = value; } } + private ScriptBlock _scriptBlock; /// @@ -73,8 +79,10 @@ public ScriptBlock ScriptBlock public ScheduledJobTrigger[] Trigger { get { return _triggers; } + set { _triggers = value; } } + private ScheduledJobTrigger[] _triggers; /// @@ -86,8 +94,10 @@ public ScheduledJobTrigger[] Trigger public ScriptBlock InitializationScript { get { return _initializationScript; } + set { _initializationScript = value; } } + private ScriptBlock _initializationScript; /// @@ -98,8 +108,10 @@ public ScriptBlock InitializationScript public SwitchParameter RunAs32 { get { return _runAs32; } + set { _runAs32 = value; } } + private SwitchParameter _runAs32; /// @@ -111,8 +123,10 @@ public SwitchParameter RunAs32 public PSCredential Credential { get { return _credential; } + set { _credential = value; } } + private PSCredential _credential; /// @@ -123,8 +137,10 @@ public PSCredential Credential public AuthenticationMechanism Authentication { get { return _authenticationMechanism; } + set { _authenticationMechanism = value; } } + private AuthenticationMechanism _authenticationMechanism; /// @@ -136,8 +152,10 @@ public AuthenticationMechanism Authentication public ScheduledJobOptions ScheduledJobOption { get { return _options; } + set { _options = value; } } + private ScheduledJobOptions _options; /// @@ -153,8 +171,10 @@ public ScheduledJobOptions ScheduledJobOption public ScheduledJobDefinition InputObject { get { return _definition; } + set { _definition = value; } } + private ScheduledJobDefinition _definition; /// @@ -164,8 +184,10 @@ public ScheduledJobDefinition InputObject public SwitchParameter ClearExecutionHistory { get { return _clearExecutionHistory; } + set { _clearExecutionHistory = value; } } + private SwitchParameter _clearExecutionHistory; /// @@ -176,8 +198,10 @@ public SwitchParameter ClearExecutionHistory public int MaxResultCount { get { return _executionHistoryLength; } + set { _executionHistoryLength = value; } } + private int _executionHistoryLength; /// @@ -189,8 +213,10 @@ public int MaxResultCount public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private SwitchParameter _passThru; /// @@ -203,8 +229,10 @@ public SwitchParameter PassThru public object[] ArgumentList { get { return _arguments; } + set { _arguments = value; } } + private object[] _arguments; /// @@ -215,8 +243,10 @@ public object[] ArgumentList public SwitchParameter RunNow { get { return _runNow; } + set { _runNow = value; } } + private SwitchParameter _runNow; /// @@ -228,8 +258,10 @@ public SwitchParameter RunNow public TimeSpan RunEvery { get { return _runEvery; } + set { _runEvery = value; } } + private TimeSpan _runEvery; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs index 09c20e2ec4a..8f9fc446978 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs @@ -32,8 +32,10 @@ public sealed class SetJobTriggerCommand : ScheduleJobCmdletBase public ScheduledJobTrigger[] InputObject { get { return _triggers; } + set { _triggers = value; } } + private ScheduledJobTrigger[] _triggers; /// @@ -43,8 +45,10 @@ public ScheduledJobTrigger[] InputObject public Int32 DaysInterval { get { return _daysInterval; } + set { _daysInterval = value; } } + private Int32 _daysInterval = 1; /// @@ -54,8 +58,10 @@ public Int32 DaysInterval public Int32 WeeksInterval { get { return _weeksInterval; } + set { _weeksInterval = value; } } + private Int32 _weeksInterval = 1; /// @@ -65,8 +71,10 @@ public Int32 WeeksInterval public TimeSpan RandomDelay { get { return _randomDelay; } + set { _randomDelay = value; } } + private TimeSpan _randomDelay; /// @@ -76,8 +84,10 @@ public TimeSpan RandomDelay public DateTime At { get { return _atTime; } + set { _atTime = value; } } + private DateTime _atTime; /// @@ -89,8 +99,10 @@ public DateTime At public string User { get { return _user; } + set { _user = value; } } + private string _user; /// @@ -102,8 +114,10 @@ public string User public DayOfWeek[] DaysOfWeek { get { return _daysOfWeek; } + set { _daysOfWeek = value; } } + private DayOfWeek[] _daysOfWeek; /// @@ -113,8 +127,10 @@ public DayOfWeek[] DaysOfWeek public SwitchParameter AtStartup { get { return _atStartup; } + set { _atStartup = value; } } + private SwitchParameter _atStartup; /// @@ -124,8 +140,10 @@ public SwitchParameter AtStartup public SwitchParameter AtLogOn { get { return _atLogon; } + set { _atLogon = value; } } + private SwitchParameter _atLogon; /// @@ -135,8 +153,10 @@ public SwitchParameter AtLogOn public SwitchParameter Once { get { return _once; } + set { _once = value; } } + private SwitchParameter _once; /// @@ -146,8 +166,10 @@ public SwitchParameter Once public TimeSpan RepetitionInterval { get { return _repInterval; } + set { _repInterval = value; } } + private TimeSpan _repInterval; /// @@ -157,8 +179,10 @@ public TimeSpan RepetitionInterval public TimeSpan RepetitionDuration { get { return _repDuration; } + set { _repDuration = value; } } + private TimeSpan _repDuration; /// @@ -168,8 +192,10 @@ public TimeSpan RepetitionDuration public SwitchParameter RepeatIndefinitely { get { return _repRepeatIndefinitely; } + set { _repRepeatIndefinitely = value; } } + private SwitchParameter _repRepeatIndefinitely; /// @@ -179,8 +205,10 @@ public SwitchParameter RepeatIndefinitely public SwitchParameter Daily { get { return _daily; } + set { _daily = value; } } + private SwitchParameter _daily; /// @@ -190,8 +218,10 @@ public SwitchParameter Daily public SwitchParameter Weekly { get { return _weekly; } + set { _weekly = value; } } + private SwitchParameter _weekly; /// @@ -201,8 +231,10 @@ public SwitchParameter Weekly public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private SwitchParameter _passThru; #endregion @@ -276,27 +308,33 @@ private bool ValidateParameterSet(ref TriggerFrequency newTriggerFrequency) { switchParamList.Add(TriggerFrequency.AtStartup); } + if (MyInvocation.BoundParameters.ContainsKey(nameof(AtLogon))) { switchParamList.Add(TriggerFrequency.AtLogon); } + if (MyInvocation.BoundParameters.ContainsKey(nameof(Once))) { switchParamList.Add(TriggerFrequency.Once); } + if (MyInvocation.BoundParameters.ContainsKey(nameof(Daily))) { switchParamList.Add(TriggerFrequency.Daily); } + if (MyInvocation.BoundParameters.ContainsKey(nameof(Weekly))) { switchParamList.Add(TriggerFrequency.Weekly); } + if (switchParamList.Count > 1) { WriteValidationError(ScheduledJobErrorStrings.ConflictingTypeParams); return false; } + newTriggerFrequency = (switchParamList.Count == 1) ? switchParamList[0] : TriggerFrequency.None; // Validate parameters against the new trigger frequency value. @@ -344,30 +382,35 @@ private bool ValidateStartupParams() WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerStartUpType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerStartUpType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerStartUpType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerStartUpType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) { @@ -387,24 +430,28 @@ private bool ValidateLogonParams() WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerLogonType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerLogonType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerLogonType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) { @@ -424,18 +471,21 @@ private bool ValidateOnceParams(ScheduledJobTrigger trigger = null) WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerOnceType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerOnceType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerOnceType); @@ -484,24 +534,28 @@ private bool ValidateDailyParams(ScheduledJobTrigger trigger = null) WriteValidationError(ScheduledJobErrorStrings.InvalidDaysIntervalParam); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerDailyType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerDailyType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerDailyType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) { @@ -531,18 +585,21 @@ private bool ValidateWeeklyParams(ScheduledJobTrigger trigger = null) WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)) && _weeksInterval < 1) { WriteValidationError(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) { string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerWeeklyType); WriteValidationError(msg); return false; } + if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) { @@ -559,6 +616,7 @@ private bool ValidateWeeklyParams(ScheduledJobTrigger trigger = null) WriteValidationError(msg); return false; } + if ((trigger.DaysOfWeek == null || trigger.DaysOfWeek.Count == 0) && !MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) { @@ -616,6 +674,7 @@ private bool CreateTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + CreateOnceTrigger(trigger); break; @@ -625,6 +684,7 @@ private bool CreateTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + CreateDailyTrigger(trigger); break; @@ -634,6 +694,7 @@ private bool CreateTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + CreateWeeklyTrigger(trigger); break; } @@ -651,6 +712,7 @@ private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + ModifyStartupTrigger(trigger); break; @@ -660,6 +722,7 @@ private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + ModifyLogonTrigger(trigger); break; @@ -669,6 +732,7 @@ private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + ModifyOnceTrigger(trigger); break; @@ -678,6 +742,7 @@ private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + ModifyDailyTrigger(trigger); break; @@ -687,6 +752,7 @@ private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency trigger { return false; } + ModifyWeeklyTrigger(trigger); break; } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs index 7c0734e4f4a..8dbac01b438 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs @@ -26,8 +26,10 @@ public class SetScheduledJobOptionCommand : ScheduledJobOptionCmdletBase public ScheduledJobOptions InputObject { get { return _jobOptions; } + set { _jobOptions = value; } } + private ScheduledJobOptions _jobOptions; /// @@ -37,8 +39,10 @@ public ScheduledJobOptions InputObject public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private SwitchParameter _passThru; #endregion diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs index bde525a2944..e978312a354 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs @@ -32,8 +32,10 @@ public sealed class UnregisterScheduledJobCommand : ScheduleJobCmdletBase public Int32[] Id { get { return _definitionIds; } + set { _definitionIds = value; } } + private Int32[] _definitionIds; /// @@ -46,8 +48,10 @@ public Int32[] Id public string[] Name { get { return _names; } + set { _names = value; } } + private string[] _names; /// @@ -60,8 +64,10 @@ public string[] Name public ScheduledJobDefinition[] InputObject { get { return _definitions; } + set { _definitions = value; } } + private ScheduledJobDefinition[] _definitions; /// @@ -74,8 +80,10 @@ public ScheduledJobDefinition[] InputObject public SwitchParameter Force { get { return _force; } + set { _force = value; } } + private SwitchParameter _force; #endregion From 50bbcf5d46ca29f91b5f83ff6448affa8b38bdf2 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:34 -0800 Subject: [PATCH 17/81] Update Eventing --- .../DotNetCode/Eventing/EventDescriptor.cs | 1 + .../DotNetCode/Eventing/EventProvider.cs | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs index 2b8cbcfc39e..1471e9b94b3 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -89,6 +89,7 @@ public byte Channel return _channel; } } + public byte Level { get diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 619f499abec..0f2fd266b76 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -452,6 +452,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe t_returnCode = WriteEventErrorCode.EventTooBig; return false; } + unsafe { fixed (char* pdata = eventMessage) @@ -466,6 +467,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe } } } + return true; } @@ -549,6 +551,7 @@ public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) SetLastError((int)status); return false; } + return true; } @@ -587,6 +590,7 @@ protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, In SetLastError((int)status); return false; } + return true; } @@ -679,30 +683,37 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related { userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; } + if (dataString[1] != null) { userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; } + if (dataString[2] != null) { userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; } + if (dataString[3] != null) { userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; } + if (dataString[4] != null) { userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; } + if (dataString[5] != null) { userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; } + if (dataString[6] != null) { userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; } + if (dataString[7] != null) { userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; @@ -724,6 +735,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related SetLastError((int)status); return false; } + return true; } @@ -750,6 +762,7 @@ protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid rela SetLastError((int)status); return false; } + return true; } From f1debb2fdbb185616d432a9f660995c76c6b44de Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:34 -0800 Subject: [PATCH 18/81] Update Reader --- .../Eventing/Reader/EventLogConfiguration.cs | 7 ++++ .../Eventing/Reader/EventLogException.cs | 15 ++++++++ .../Eventing/Reader/EventLogInformation.cs | 7 ++++ .../Eventing/Reader/EventLogQuery.cs | 3 ++ .../Eventing/Reader/EventLogReader.cs | 3 ++ .../Eventing/Reader/EventLogRecord.cs | 7 ++++ .../Eventing/Reader/EventPropertyContext.cs | 1 + .../DotNetCode/Eventing/Reader/EventRecord.cs | 15 ++++++++ .../Eventing/Reader/NativeWrapper.cs | 37 +++++++++++++++++++ .../Eventing/Reader/ProviderMetadata.cs | 14 +++++++ .../ProviderMetadataCachedInformation.cs | 4 ++ 11 files changed, 113 insertions(+) diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs index c8580091f0d..2f8d22a50e4 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs @@ -107,6 +107,7 @@ public bool IsEnabled { return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value); @@ -127,6 +128,7 @@ public string SecurityDescriptor { return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value); @@ -139,6 +141,7 @@ public string LogFilePath { return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value); @@ -151,6 +154,7 @@ public long MaximumSizeInBytes { return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value); @@ -175,6 +179,7 @@ public EventLogMode LogMode return EventLogMode.Circular; } + set { switch (value) @@ -217,6 +222,7 @@ public int? ProviderLevel { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel)); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value); @@ -229,6 +235,7 @@ public long? ProviderKeywords { return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords)); } + set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs index 486c45e5723..80e1299d296 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs @@ -51,8 +51,11 @@ internal static void Throw(int errorCode) } public EventLogException() { } + public EventLogException(string message) : base(message) { } + public EventLogException(string message, Exception innerException) : base(message, innerException) { } + protected EventLogException(int errorCode) { _errorCode = errorCode; } public override string Message @@ -76,8 +79,11 @@ public override string Message public class EventLogNotFoundException : EventLogException { public EventLogNotFoundException() { } + public EventLogNotFoundException(string message) : base(message) { } + public EventLogNotFoundException(string message, Exception innerException) : base(message, innerException) { } + internal EventLogNotFoundException(int errorCode) : base(errorCode) { } } @@ -89,8 +95,11 @@ internal EventLogNotFoundException(int errorCode) : base(errorCode) { } public class EventLogReadingException : EventLogException { public EventLogReadingException() { } + public EventLogReadingException(string message) : base(message) { } + public EventLogReadingException(string message, Exception innerException) : base(message, innerException) { } + internal EventLogReadingException(int errorCode) : base(errorCode) { } } @@ -102,8 +111,11 @@ internal EventLogReadingException(int errorCode) : base(errorCode) { } public class EventLogProviderDisabledException : EventLogException { public EventLogProviderDisabledException() { } + public EventLogProviderDisabledException(string message) : base(message) { } + public EventLogProviderDisabledException(string message, Exception innerException) : base(message, innerException) { } + internal EventLogProviderDisabledException(int errorCode) : base(errorCode) { } } @@ -113,8 +125,11 @@ internal EventLogProviderDisabledException(int errorCode) : base(errorCode) { } public class EventLogInvalidDataException : EventLogException { public EventLogInvalidDataException() { } + public EventLogInvalidDataException(string message) : base(message) { } + public EventLogInvalidDataException(string message, Exception innerException) : base(message, innerException) { } + internal EventLogInvalidDataException(int errorCode) : base(errorCode) { } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs index daebcc3787d..95350eab81b 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs @@ -47,12 +47,19 @@ internal EventLogInformation(EventLogSession session, string channelName, PathTy } public DateTime? CreationTime { get { return _creationTime; } } + public DateTime? LastAccessTime { get { return _lastAccessTime; } } + public DateTime? LastWriteTime { get { return _lastWriteTime; } } + public long? FileSize { get { return _fileSize; } } + public int? Attributes { get { return _fileAttributes; } } + public long? RecordCount { get { return _recordCount; } } + public long? OldestRecordNumber { get { return _oldestRecordNumber; } } + public bool? IsLogFull { get { return _isLogFull; } } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs index 65eaee0e6d6..fd827890a31 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs @@ -60,6 +60,7 @@ public EventLogSession Session { return _session; } + set { _session = value; @@ -72,6 +73,7 @@ public bool TolerateQueryErrors { return _tolerateErrors; } + set { _tolerateErrors = value; @@ -84,6 +86,7 @@ public bool ReverseDirection { return _reverseDirection; } + set { _reverseDirection = value; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs index 7190cb04a02..ce47aca1eb0 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs @@ -125,6 +125,7 @@ public int BatchSize { return _batchSize; } + set { if (value < 1) @@ -309,6 +310,7 @@ public void Seek(SeekOrigin origin, long offset) { SeekCommon(offset); } + return; } } @@ -343,6 +345,7 @@ public IList LogStatus EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]); list.Add(cs); } + return list.AsReadOnly(); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs index ae1ea29482f..bc8a2541d42 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs @@ -264,6 +264,7 @@ public string ContainerLog { _containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); } + return _containerChannel; } } @@ -281,6 +282,7 @@ public IEnumerable MatchedQueryIds { _matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); } + return _matchedQueryIds; } } @@ -335,6 +337,7 @@ public override string LevelDisplayName _levelNameReady = true; _levelName = _cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, _handle); } + return _levelName; } } @@ -351,6 +354,7 @@ public override string OpcodeDisplayName _opcodeNameReady = true; _opcodeName = _cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, _handle); } + return _opcodeName; } } @@ -369,6 +373,7 @@ public override string TaskDisplayName _taskNameReady = true; _taskName = _cachedMetadataInformation.GetTaskDisplayName(this.ProviderName, _handle); } + return _taskName; } } @@ -386,6 +391,7 @@ public override IEnumerable KeywordsDisplayNames { _keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, _handle); } + return _keywordsNames; } } @@ -402,6 +408,7 @@ public override IList Properties { list.Add(new EventProperty(value)); } + return list; } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs index 99c6219955b..a87441f3317 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs @@ -20,6 +20,7 @@ public void Dispose() Dispose(true); GC.SuppressFinalize(this); } + protected virtual void Dispose(bool disposing) { } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs index 53f3e9132e2..045ec27f371 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs @@ -22,28 +22,40 @@ namespace System.Diagnostics.Eventing.Reader public abstract class EventRecord : IDisposable { public abstract int Id { get; } + public abstract byte? Version { get; } + public abstract byte? Level { get; } + public abstract int? Task { get; } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] public abstract short? Opcode { get; } + public abstract long? Keywords { get; } public abstract long? RecordId { get; } public abstract string ProviderName { get; } + public abstract Guid? ProviderId { get; } + public abstract string LogName { get; } public abstract int? ProcessId { get; } + public abstract int? ThreadId { get; } + public abstract string MachineName { get; } + public abstract SecurityIdentifier UserId { get; } + public abstract DateTime? TimeCreated { get; } public abstract Guid? ActivityId { get; } + public abstract Guid? RelatedActivityId { get; } + public abstract int? Qualifiers { get; } public abstract string FormatDescription(); @@ -53,7 +65,9 @@ public abstract class EventRecord : IDisposable [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] public abstract string OpcodeDisplayName { get; } + public abstract string TaskDisplayName { get; } + public abstract IEnumerable KeywordsDisplayNames { get; } public abstract EventBookmark Bookmark { get; } @@ -67,6 +81,7 @@ public void Dispose() Dispose(true); GC.SuppressFinalize(this); } + protected virtual void Dispose(bool disposing) { } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 0e048b0fc32..aa58d385a21 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -301,6 +301,7 @@ public static void EvtRender( status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); win32Error = Marshal.GetLastWin32Error(); } + if (!status) { EventLogException.Throw(win32Error); @@ -354,6 +355,7 @@ public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods. if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); @@ -384,6 +386,7 @@ public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods. if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, bufferNeeded, buffer, ref bufferNeeded); error = Marshal.GetLastWin32Error(); @@ -414,6 +417,7 @@ public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, Un if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); @@ -443,6 +447,7 @@ internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHan if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); @@ -489,6 +494,7 @@ public static string EvtFormatMessage(EventLogHandle handle, uint msgId) case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -510,12 +516,15 @@ public static string EvtFormatMessage(EventLogHandle handle, uint msgId) case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + if (error == UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { return null; } + EventLogException.Throw(error); } + return sb.ToString(); } @@ -535,6 +544,7 @@ public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, in if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); @@ -565,6 +575,7 @@ public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNa if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); @@ -596,6 +607,7 @@ public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNa if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); @@ -638,6 +650,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: { @@ -645,6 +658,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: { @@ -652,24 +666,28 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; varVal.UInteger = (uint)((int)val); } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: { @@ -677,6 +695,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: { @@ -684,6 +703,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } + break; default: throw new InvalidOperationException(); @@ -693,6 +713,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull; } + bool status = UnsafeNativeMethods.EvtSetChannelConfigProperty(handle, enumType, 0, ref varVal); int win32Error = Marshal.GetLastWin32Error(); if (!status) @@ -773,6 +794,7 @@ public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.Ev if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } + buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); @@ -878,6 +900,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle systemProperties.Version = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; } + pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); } } @@ -926,6 +949,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); } } + return valuesList; } finally @@ -961,6 +985,7 @@ public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLo case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + if (error != (int)UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -980,8 +1005,10 @@ public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLo case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + EventLogException.Throw(error); } + return sb.ToString(); } @@ -1009,6 +1036,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return keywordsList.AsReadOnly(); } + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -1027,6 +1055,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return keywordsList; } + EventLogException.Throw(error); } @@ -1118,6 +1147,7 @@ public static string EvtFormatMessageFormatDescription(EventLogHandle handle, Ev case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -1137,8 +1167,10 @@ public static string EvtFormatMessageFormatDescription(EventLogHandle handle, Ev case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } + EventLogException.Throw(error); } + return sb.ToString(); } @@ -1307,6 +1339,7 @@ public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int si array.SetValue(Marshal.PtrToStructure(ptr), i); ptr = new IntPtr((Int64)ptr + size); } + return array; } } @@ -1329,6 +1362,7 @@ public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) array[i] = value; ptr = new IntPtr((Int64)ptr + 4); } + return array; } } @@ -1349,6 +1383,7 @@ public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); ptr = new IntPtr((Int64)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes } + return array; } } @@ -1370,6 +1405,7 @@ public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) array[i] = new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); ptr = new IntPtr((Int64)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes } + return array; } } @@ -1391,6 +1427,7 @@ public static string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, { stringArray[i] = ansi ? Marshal.PtrToStringAnsi(pointersToString[i]) : Marshal.PtrToStringUni(pointersToString[i]); } + return stringArray; } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs index 5ff0706e3c3..3075b7e45ef 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs @@ -259,8 +259,10 @@ internal string FindStandardLevelDisplayName(string name, uint value) if (standardLevel.Name == name && standardLevel.Value == value) return standardLevel.DisplayName; } + return null; } + internal string FindStandardOpcodeDisplayName(string name, uint value) { if (_standardOpcodes == null) @@ -270,8 +272,10 @@ internal string FindStandardOpcodeDisplayName(string name, uint value) if (standardOpcode.Name == name && standardOpcode.Value == value) return standardOpcode.DisplayName; } + return null; } + internal string FindStandardKeywordDisplayName(string name, long value) { if (_standardKeywords == null) @@ -281,8 +285,10 @@ internal string FindStandardKeywordDisplayName(string name, long value) if (standardKeyword.Name == name && standardKeyword.Value == value) return standardKeyword.DisplayName; } + return null; } + internal string FindStandardTaskDisplayName(string name, uint value) { if (_standardTasks == null) @@ -292,6 +298,7 @@ internal string FindStandardTaskDisplayName(string name, uint value) if (standardTask.Name == name && standardTask.Value == value) return standardTask.DisplayName; } + return null; } @@ -353,6 +360,7 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat default: return null; } + for (int index = 0; index < arraySize; index++) { string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName); @@ -437,6 +445,7 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat case ObjectTypeName.Task: return taskList; } + return null; } finally @@ -458,6 +467,7 @@ public IList Levels el = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); _levels = el.AsReadOnly(); } + return _levels; } } @@ -476,6 +486,7 @@ public IList Opcodes eo = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); _opcodes = eo.AsReadOnly(); } + return _opcodes; } } @@ -493,6 +504,7 @@ public IList Keywords ek = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); _keywords = ek.AsReadOnly(); } + return _keywords; } } @@ -510,6 +522,7 @@ public IList Tasks et = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); _tasks = et.AsReadOnly(); } + return _tasks; } } @@ -554,6 +567,7 @@ public IEnumerable Events } } } + return emList.AsReadOnly(); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs index feb1823cc3c..9a08c69c005 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs @@ -60,6 +60,7 @@ public string ProviderName return _providerName; } } + public CultureInfo TheCultureInfo { get @@ -86,6 +87,7 @@ public DateTime TheTime { return _theTime; } + set { _theTime = value; @@ -183,6 +185,7 @@ private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } + AddCacheEntry(key, pm); return pm; } @@ -213,6 +216,7 @@ private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } + AddCacheEntry(key, pm); } From a30b813da42d84b0689af3602cf1b47d318e5fb1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:39 -0800 Subject: [PATCH 19/81] Update utility --- .../commands/utility/AddMember.cs | 24 +++++++++ .../commands/utility/AddType.cs | 13 +++++ .../commands/utility/CSVCommands.cs | 41 +++++++++++++++ .../commands/utility/ConsoleColorCmdlet.cs | 2 + .../utility/ConvertFrom-SddlString.cs | 3 ++ .../utility/ConvertFrom-StringData.cs | 1 + .../commands/utility/Csv.cs | 3 ++ .../commands/utility/CustomSerialization.cs | 13 +++++ .../commands/utility/DebugRunspaceCommand.cs | 4 ++ .../commands/utility/Disable-PSBreakpoint.cs | 1 + .../commands/utility/Enable-PSBreakpoint.cs | 4 ++ .../EnableDisableRunspaceDebugCommand.cs | 1 + .../commands/utility/ExportAliasCommand.cs | 13 +++++ .../commands/utility/Get-PSBreakpoint.cs | 13 +++++ .../commands/utility/GetAliasCommand.cs | 6 +++ .../commands/utility/GetDateCommand.cs | 17 ++++++ .../commands/utility/GetEventCommand.cs | 4 ++ .../utility/GetEventSubscriberCommand.cs | 2 + .../commands/utility/GetHash.cs | 5 ++ .../commands/utility/GetMember.cs | 6 +++ .../commands/utility/GetRandomCommand.cs | 5 ++ .../commands/utility/GetUnique.cs | 6 +++ .../commands/utility/GetVerbCommand.cs | 1 + .../utility/ImplicitRemotingCommands.cs | 52 +++++++++++++++++++ .../commands/utility/Import-LocalizedData.cs | 6 +++ .../commands/utility/ImportAliasCommand.cs | 6 +++ .../utility/ImportPowerShellDataFile.cs | 1 + .../commands/utility/Measure-Object.cs | 27 ++++++++++ .../utility/NewTemporaryFileCommand.cs | 1 + .../commands/utility/NewTimeSpanCommand.cs | 5 ++ .../commands/utility/ObjectCommandComparer.cs | 1 + .../commands/utility/OrderObjectBase.cs | 19 +++++++ .../commands/utility/ReadConsoleCmdlet.cs | 2 + .../utility/RegisterObjectEventCommand.cs | 4 ++ .../utility/RegisterPSEventCommand.cs | 1 + .../commands/utility/RemoveEventCommand.cs | 4 ++ .../commands/utility/Set-PSBreakpoint.cs | 2 + .../commands/utility/ShowMarkdownCommand.cs | 1 + .../commands/utility/StartSleepCommand.cs | 2 + .../commands/utility/UnblockFile.cs | 2 + .../utility/UnregisterEventCommand.cs | 2 + .../commands/utility/Update-Data.cs | 3 ++ .../commands/utility/Update-TypeData.cs | 39 ++++++++++++++ .../commands/utility/Var.cs | 29 +++++++++++ .../commands/utility/WaitEventCommand.cs | 4 ++ .../commands/utility/Write-Object.cs | 1 + .../commands/utility/WriteAliasCommandBase.cs | 2 + .../commands/utility/WriteConsoleCmdlet.cs | 1 + .../commands/utility/WriteProgressCmdlet.cs | 1 + .../commands/utility/XmlCommands.cs | 25 +++++++++ .../commands/utility/compare-object.cs | 15 ++++++ .../commands/utility/convert-HTML.cs | 46 ++++++++++++++++ .../commands/utility/join-string.cs | 2 +- .../commands/utility/new-object.cs | 8 +++ .../commands/utility/neweventcommand.cs | 8 +++ .../commands/utility/select-object.cs | 21 ++++++++ .../commands/utility/sort-object.cs | 5 ++ .../commands/utility/tee-object.cs | 9 ++++ .../commands/utility/update-list.cs | 6 +++ .../commands/utility/write.cs | 3 ++ 60 files changed, 553 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 516fb0f88dd..d74c15d4337 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -38,6 +38,7 @@ private static bool HasBeenSpecified(object obj) public PSObject InputObject { set { _inputObject = value; } + get { return _inputObject; } } @@ -50,6 +51,7 @@ public PSObject InputObject public PSMemberTypes MemberType { set { _memberType = value; } + get { return _memberType; } } @@ -61,6 +63,7 @@ public PSMemberTypes MemberType public string Name { set { _memberName = value; } + get { return _memberName; } } @@ -72,6 +75,7 @@ public string Name public object Value { set { _value1 = value; } + get { return _value1; } } @@ -83,6 +87,7 @@ public object Value public object SecondValue { set { _value2 = value; } + get { return _value2; } } @@ -98,6 +103,7 @@ public object SecondValue public string TypeName { set { _typeName = value; } + get { return _typeName; } } @@ -111,6 +117,7 @@ public string TypeName public SwitchParameter Force { set { _force = value; } + get { return _force; } } @@ -126,6 +133,7 @@ public SwitchParameter Force public SwitchParameter PassThru { set { _passThru = value; } + get { return _passThru; } } @@ -145,6 +153,7 @@ public SwitchParameter PassThru public string NotePropertyName { set { _notePropertyName = value; } + get { return _notePropertyName; } } @@ -157,6 +166,7 @@ public string NotePropertyName public object NotePropertyValue { set { _notePropertyValue = value; } + get { return _notePropertyValue; } } @@ -172,6 +182,7 @@ public object NotePropertyValue public IDictionary NotePropertyMembers { get { return _property; } + set { _property = value; } } @@ -242,6 +253,7 @@ private PSMemberInfo GetAliasProperty() Type value2Type = (Type)GetParameterType(_value2, typeof(Type)); return new PSAliasProperty(_memberName, value1Str, value2Type); } + return new PSAliasProperty(_memberName, value1Str); } @@ -264,11 +276,13 @@ private PSMemberInfo GetCodeProperty() { value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo)); } + MethodInfo value2MethodInfo = null; if (HasBeenSpecified(_value2)) { value2MethodInfo = (MethodInfo)GetParameterType(_value2, typeof(MethodInfo)); } + return new PSCodeProperty(_memberName, value1MethodInfo, value2MethodInfo); } @@ -279,6 +293,7 @@ private PSMemberInfo GetMemberSet() { return new PSMemberSet(_memberName); } + Collection value1Collection = (Collection)GetParameterType(_value1, typeof(Collection)); return new PSMemberSet(_memberName, value1Collection); @@ -320,11 +335,13 @@ private PSMemberInfo GetScriptProperty() { value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock)); } + ScriptBlock value2ScriptBlock = null; if (HasBeenSpecified(_value2)) { value2ScriptBlock = (ScriptBlock)GetParameterType(_value2, typeof(ScriptBlock)); } + return new PSScriptProperty(_memberName, value1ScriptBlock, value2ScriptBlock); } @@ -346,6 +363,7 @@ protected override void ProcessRecord() { WriteObject(_inputObject); } + return; } @@ -370,8 +388,10 @@ protected override void ProcessRecord() { memberCount++; } + memberCountHelper = memberCountHelper >> 1; } + if (memberCount != 1) { ThrowTerminatingError(NewError("WrongMemberCount", "WrongMemberCount", null, _memberType.ToString())); @@ -461,6 +481,7 @@ private bool AddMemberToTarget(PSMemberInfo member) } } } + _inputObject.Members.Add(member); return true; } @@ -492,6 +513,7 @@ private void ProcessNotePropertyMultiMemberSet() { UpdateTypeNames(); } + if (result && _passThru) { WriteObject(_inputObject); @@ -504,6 +526,7 @@ private void UpdateTypeNames() Type type; string typeNameInUse = _typeName; if (LanguagePrimitives.TryConvertTo(_typeName, out type)) { typeNameInUse = type.FullName; } + _inputObject.TypeNames.Insert(0, typeNameInUse); } @@ -571,6 +594,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input var result = LanguagePrimitives.ConvertTo(target); return result; } + return inputData; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index d285c50edbb..efe4176115a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -81,6 +81,7 @@ public String TypeDefinition { return _sourceCode; } + set { _sourceCode = value; @@ -105,6 +106,7 @@ public String[] MemberDefinition { return new string[] { _sourceCode }; } + set { _sourceCode = String.Empty; @@ -147,6 +149,7 @@ public string[] Path { return _paths; } + set { if (value == null) @@ -194,6 +197,7 @@ public string[] LiteralPath { return _paths; } + set { if (value == null) @@ -299,11 +303,13 @@ private void ProcessPaths(List resolvedPaths) public String[] ReferencedAssemblies { get { return referencedAssemblies; } + set { if (value != null) { referencedAssemblies = value; } } } + private string[] referencedAssemblies = Utils.EmptyArray(); /// @@ -320,6 +326,7 @@ public string OutputAssembly { return _outputAssembly; } + set { _outputAssembly = value; @@ -384,6 +391,7 @@ public string OutputAssembly } } } + private string _outputAssembly = null; /// @@ -531,6 +539,7 @@ private string GetUsingSet(Language language) { usingNamespaceSet.Append("using " + namespaceValue + ";\n"); } + break; default: @@ -833,6 +842,7 @@ private IEnumerable GetPortableExecutableReferences foreach (string assembly in ReferencedAssemblies) { if (string.IsNullOrWhiteSpace(assembly)) { continue; } + string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); // Ignore some specified reference assemblies @@ -842,8 +852,10 @@ private IEnumerable GetPortableExecutableReferences WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath)); continue; } + tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath)); } + return tempReferences; } else @@ -976,6 +988,7 @@ private void SourceCodeProcessing() syntaxTrees.Add(ParseSourceText(sourceText, parseOptions, path: filePath)); } } + break; case FromMemberParameterSetName: _sourceCode = GenerateTypeSource(Namespace, Name, _sourceCode, Language); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs index ccb4dd32f20..77f9c7d3010 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs @@ -36,6 +36,7 @@ public char Delimiter { return _delimiter; } + set { _delimiter = value; @@ -98,10 +99,12 @@ protected override void BeginProcessing() ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } + if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation))) { NoTypeInformation = !IncludeTypeInformation; } + _delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, _delimiter, UseCulture); } } @@ -137,12 +140,14 @@ public string Path { return _path; } + set { _path = value; _specifiedPath = true; } } + private string _path; private bool _specifiedPath = false; @@ -159,12 +164,14 @@ public string LiteralPath { return _path; } + set { _path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -177,11 +184,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -195,11 +204,13 @@ public SwitchParameter NoClobber { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// @@ -395,12 +406,14 @@ private void CreateFileStream() _sw.Dispose(); _sw = null; } + _fs.Dispose(); _fs = null; // reset the read-only attribute if (_readOnlyFileInfo != null) _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } + if (_helper != null) { _helper.Dispose(); @@ -482,6 +495,7 @@ public override void { CleanUp(); } + _disposed = true; } @@ -520,12 +534,14 @@ public String[] Path { return _paths; } + set { _paths = value; _specifiedPath = true; } } + private string[] _paths; private bool _specifiedPath = false; @@ -542,12 +558,14 @@ public string[] LiteralPath { return _paths; } + set { _paths = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -561,11 +579,13 @@ public SwitchParameter UseCulture { return _useculture; } + set { _useculture = value; } } + private bool _useculture; /// @@ -823,6 +843,7 @@ protected override { Header = helper.Header.ToArray(); } + if ((_typeName == null) && (helper.TypeName != null)) { _typeName = helper.TypeName; @@ -864,6 +885,7 @@ internal class ExportCsvHelper : IDisposable { throw new ArgumentNullException("cmdlet"); } + _cmdlet = cmdlet; _delimiter = delimiter; } @@ -892,6 +914,7 @@ internal class ExportCsvHelper : IDisposable { propertyNames.Add(prop.Name); } + return propertyNames; } @@ -921,8 +944,10 @@ internal class ExportCsvHelper : IDisposable //changed to delimiter dest.Append(_delimiter); } + EscapeAndAppendString(dest, propertyName); } + return dest.ToString(); } @@ -953,6 +978,7 @@ internal class ExportCsvHelper : IDisposable { dest.Append(_delimiter); } + PSPropertyInfo property = mshObject.Properties[propertyName] as PSPropertyInfo; string value = null; //If property is not present, assume value is null @@ -960,8 +986,10 @@ internal class ExportCsvHelper : IDisposable { value = GetToStringValueForProperty(property); } + EscapeAndAppendString(dest, value); } + return dest.ToString(); } @@ -992,6 +1020,7 @@ internal class ExportCsvHelper : IDisposable catch (Exception) { } + return value; } @@ -1026,6 +1055,7 @@ internal class ExportCsvHelper : IDisposable { temp = temp.Substring(4); } + type = string.Format(System.Globalization.CultureInfo.InvariantCulture, "#TYPE {0}", temp); } @@ -1055,8 +1085,10 @@ internal static { dest.Append('"'); } + dest.Append(c); } + dest.Append('"'); } #region IDisposable Members @@ -1077,6 +1109,7 @@ internal static { GC.SuppressFinalize(this); } + _disposed = true; } @@ -1197,6 +1230,7 @@ bool EOF { return false; } + return (c == (char)i); } @@ -1285,6 +1319,7 @@ internal void ReadHeader() prevalidated = true; _cmdlet.WriteObject(result); } + alreadyWriteOutWarning = _alreadyWarnedUnspecifiedName; } @@ -1348,6 +1383,7 @@ private string } } } + return type; } @@ -1505,6 +1541,7 @@ private void current.Append(ch); } } + if (current.Length != 0) { result.Add(current.ToString()); @@ -1585,6 +1622,7 @@ private void } } } + if (eatTrailingBlanks && !nonWhiteSpace) { string s = temp.ToString(); @@ -1678,13 +1716,16 @@ internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName, char // [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1 Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0]; } + break; default: { Delimiter = ImportExportCSVHelper.CSVDelimiter; } + break; } + return Delimiter; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs index 17ddd0d3c8f..f0b24be51ed 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -42,6 +42,7 @@ public ConsoleColorCmdlet() return _fgColor; } + set { if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) @@ -75,6 +76,7 @@ public ConsoleColorCmdlet() return _bgColor; } + set { if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index 6962f8beb38..b3c343321ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -34,12 +34,14 @@ public sealed class ConvertFromSddlStringCommand : PSCmdlet public AccessRightTypeNames Type { get { return _type; } + set { _isTypeSet = true; _type = value; } } + private AccessRightTypeNames _type; private bool _isTypeSet = false; @@ -139,6 +141,7 @@ private string[] ConvertAccessControlListToStrings(CommonAcl acl, AccessRightTyp string accessRights = String.Join(", ", accessRightList); aceString.Append($" ({accessRights})"); } + aceStringList.Add(aceString.ToString()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index b8c7d6dbc6e..0698e150f59 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -30,6 +30,7 @@ public string StringData { return _stringData; } + set { _stringData = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs index 5b5404e367e..1bbc70fb4e4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs @@ -35,6 +35,7 @@ internal Collection ParseCsv(string csv) { return result; } + bool inQuote = false; for (int i = 0; i < csv.Length; i++) { @@ -98,10 +99,12 @@ internal Collection ParseCsv(string csv) } } } + if (tempString.Length > 0) { result.Add(tempString); } + return result; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 2173291050d..9e66939ab5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -56,10 +56,12 @@ internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth { throw PSTraceSource.NewArgumentException("writer"); } + if (depth < 1) { throw PSTraceSource.NewArgumentException("writer", Serialization.DepthOfOneRequired); } + _depth = depth; _writer = writer; _notypeinformation = notypeinformation; @@ -152,6 +154,7 @@ internal void Done() _firstCall = false; Start(); } + _writer.WriteEndElement(); _writer.Flush(); } @@ -320,6 +323,7 @@ private bool HandlePrimitiveKnownType(object source, string property) WriteOnePrimitiveKnownType(_writer, property, source, pktInfo); return true; } + return false; } @@ -349,6 +353,7 @@ private bool HandlePrimitiveKnownTypePSObject(object source, string property, in sourceHandled = true; } } + return sourceHandled; } @@ -381,6 +386,7 @@ private bool HandleKnownContainerTypes(object source, string property, int depth { WriteDictionary(dictionary, depth); } + break; case ContainerType.Stack: case ContainerType.Queue: @@ -389,11 +395,13 @@ private bool HandleKnownContainerTypes(object source, string property, int depth { WriteEnumerable(enumerable, depth); } + break; default: { Dbg.Assert(false, "All containers should be handled in the switch"); } + break; } @@ -523,8 +531,10 @@ private static bool DerivesFromGenericType(Type derived, Type baseType) { return true; } + derived = derived.GetTypeInfo().BaseType; } + return false; } @@ -671,6 +681,7 @@ private bool PSObjectHasNotes(PSObject source) { return true; } + return false; } @@ -740,6 +751,7 @@ private void WritePSObjectProperties(PSObject source, int depth) specificProperties.Add(property); } } + SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth); return; } @@ -862,6 +874,7 @@ private void WriteEnumerable(IEnumerable enumerable, int depth) { break; } + WriteOneObject(item, null, depth); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index a9e98dcb9f4..9282a39df02 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -329,7 +329,9 @@ private void AddDataEventHandlers() { // Create new collection objects. if (_debugBlockingCollection != null) { _debugBlockingCollection.Dispose(); } + if (_debugAccumulateCollection != null) { _debugAccumulateCollection.Dispose(); } + _debugBlockingCollection = new PSDataCollection(); _debugBlockingCollection.BlockingEnumerator = true; _debugAccumulateCollection = new PSDataCollection(); @@ -341,6 +343,7 @@ private void AddDataEventHandlers() { _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding; } + if (_runningPowerShell.ErrorBuffer != null) { _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding; @@ -355,6 +358,7 @@ private void AddDataEventHandlers() { _runningPipeline.Output.DataReady += HandlePipelineOutputDataReady; } + if (_runningPipeline.Error != null) { _runningPipeline.Error.DataReady += HandlePipelineErrorDataReady; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs index 98ec98a8fa0..6d7e1454367 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs @@ -23,6 +23,7 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs index 46143f81686..e697d36bc2b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs @@ -24,11 +24,13 @@ public Breakpoint[] Breakpoint { return _breakpoints; } + set { _breakpoints = value; } } + private Breakpoint[] _breakpoints; /// @@ -42,6 +44,7 @@ public int[] Id { return _ids; } + set { _ids = value; @@ -130,6 +133,7 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index df47dbdbf13..0d54331da94 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -295,6 +295,7 @@ protected void SetDebugPreferenceHelper(string processName, string[] appDomainNa { appDomainNames = new List(); } + appDomainNames.Add(currentAppDomainName.ToLowerInvariant()); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 9409d9b5bcc..18e1e371aff 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -42,8 +42,10 @@ public class ExportAliasCommand : PSCmdlet public string Path { get { return _path; } + set { _path = value ?? "."; } } + private string _path = "."; /// @@ -54,6 +56,7 @@ public string Path public string LiteralPath { get { return _path; } + set { if (value == null) @@ -67,6 +70,7 @@ public string LiteralPath } } } + private bool _isLiteralPath = false; /// @@ -76,8 +80,10 @@ public string LiteralPath public string[] Name { get { return _names; } + set { _names = value ?? new string[] { "*" }; } } + private string[] _names = new string[] { "*" }; /// @@ -96,6 +102,7 @@ public SwitchParameter PassThru _passThru = value; } } + private bool _passThru; /// @@ -114,11 +121,13 @@ public SwitchParameter Append { return _append; } + set { _append = value; } } + private bool _append; /// @@ -131,11 +140,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -149,11 +160,13 @@ public SwitchParameter NoClobber { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index fc46d17dac6..20c296ac508 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -47,11 +47,13 @@ public string[] Script { return _script; } + set { _script = value; } } + private string[] _script; /// @@ -66,11 +68,13 @@ public int[] Id { return _id; } + set { _id = value; } } + private int[] _id; /// @@ -85,11 +89,13 @@ public string[] Variable { return _variable; } + set { _variable = value; } } + private string[] _variable; /// @@ -104,11 +110,13 @@ public string[] Command { return _command; } + set { _command = value; } } + private string[] _command; /// @@ -124,11 +132,13 @@ public BreakpointType[] Type { return _type; } + set { _type = value; } } + private BreakpointType[] _type; #endregion parameters @@ -206,6 +216,7 @@ protected override void ProcessRecord() { return true; } + break; case BreakpointType.Command: @@ -213,6 +224,7 @@ protected override void ProcessRecord() { return true; } + break; case BreakpointType.Variable: @@ -220,6 +232,7 @@ protected override void ProcessRecord() { return true; } + break; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index 7f7d6435ac4..bd8b33a4450 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -27,8 +27,10 @@ public class GetAliasCommand : PSCmdlet public string[] Name { get { return _names; } + set { _names = value ?? new string[] { "*" }; } } + private string[] _names = new string[] { "*" }; /// @@ -38,8 +40,10 @@ public string[] Name public string[] Exclude { get { return _excludes; } + set { _excludes = value ?? new string[0]; } } + private string[] _excludes = new string[0]; /// @@ -124,6 +128,7 @@ private void WriteMatches(string value, string parametersetname) { continue; } + if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false)) { continue; @@ -141,6 +146,7 @@ private void WriteMatches(string value, string parametersetname) continue; } } + if (ContainsWildcard) { // Only write the command if it is visible to the requestor diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index a10bc14c36b..e524cf80422 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -32,12 +32,14 @@ public DateTime Date { return _date; } + set { _date = value; _dateSpecified = true; } } + private DateTime _date; private bool _dateSpecified; @@ -52,12 +54,14 @@ public int Year { return _year; } + set { _year = value; _yearSpecified = true; } } + private int _year; private bool _yearSpecified; @@ -72,12 +76,14 @@ public int Month { return _month; } + set { _month = value; _monthSpecified = true; } } + private int _month; private bool _monthSpecified; @@ -92,12 +98,14 @@ public int Day { return _day; } + set { _day = value; _daySpecified = true; } } + private int _day; private bool _daySpecified; @@ -112,12 +120,14 @@ public int Hour { return _hour; } + set { _hour = value; _hourSpecified = true; } } + private int _hour; private bool _hourSpecified; @@ -132,12 +142,14 @@ public int Minute { return _minute; } + set { _minute = value; _minuteSpecified = true; } } + private int _minute; private bool _minuteSpecified; @@ -152,12 +164,14 @@ public int Second { return _second; } + set { _second = value; _secondSpecified = true; } } + private int _second; private bool _secondSpecified; @@ -172,12 +186,14 @@ public int Millisecond { return _millisecond; } + set { _millisecond = value; _millisecondSpecified = true; } } + private int _millisecond; private bool _millisecondSpecified; @@ -329,6 +345,7 @@ private string UFormatDateString(DateTime dateTime) { offset++; } + for (int i = offset; i < UFormat.Length; i++) { if (UFormat[i] == '%') diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index 7e4b17aa2a8..d66151875a6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -27,6 +27,7 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; @@ -37,6 +38,7 @@ public string SourceIdentifier } } } + private string _sourceIdentifier = null; /// @@ -50,11 +52,13 @@ public int EventIdentifier { return _eventId; } + set { _eventId = value; } } + private int _eventId = -1; #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index 9c5f70360e5..3f5835d0d07 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -27,6 +27,7 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; @@ -37,6 +38,7 @@ public string SourceIdentifier } } } + private string _sourceIdentifier = null; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index 4355e5be3e7..9bd84b3a9c7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -30,6 +30,7 @@ public String[] Path { return _paths; } + set { _paths = value; @@ -50,6 +51,7 @@ public String[] LiteralPath { return _paths; } + set { _paths = value; @@ -110,6 +112,7 @@ protected override void ProcessRecord() } } } + break; case LiteralPathParameterSet: foreach (string path in _paths) @@ -117,6 +120,7 @@ protected override void ProcessRecord() string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); pathsToProcess.Add(newPath); } + break; } @@ -210,6 +214,7 @@ public String Algorithm { return _Algorithm; } + set { // A hash algorithm name is case sensitive diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 6df4f1902d9..87df561afc7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -95,6 +95,7 @@ public class GetMemberCommand : PSCmdlet public SwitchParameter Static { set { _staticParameter = value; } + get { return _staticParameter; } } @@ -114,6 +115,7 @@ public SwitchParameter Force { return (_matchOptions == MshMemberMatchOptions.IncludeHidden); } + set { if (value) @@ -127,6 +129,7 @@ public SwitchParameter Force } } } + private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; private HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); @@ -234,9 +237,11 @@ protected override void ProcessRecord() continue; } } + members[resultCount] = new MemberDefinition(typeName, member.Name, member.MemberType, member.ToString()); resultCount++; } + Array.Sort(members, 0, resultCount, new MemberComparer()); for (int index = 0; index < resultCount; index++) { @@ -255,6 +260,7 @@ public int Compare(MemberDefinition first, MemberDefinition second) { return result; } + return String.Compare(first.Name, second.Name, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index cb02853a761..7e40757ddf0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -124,6 +124,7 @@ private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEve { GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } + break; } } @@ -160,6 +161,7 @@ private PolymorphicRandomNumberGenerator Generator return _generator; } + set { _generator = value; @@ -173,6 +175,7 @@ private PolymorphicRandomNumberGenerator Generator // make sure we won't leave the generator around after runspace exits myRunspace.StateChanged += CurrentRunspace_StateChanged; } + GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator; } finally @@ -215,6 +218,7 @@ private bool IsInt(object o) { return true; } + return false; } @@ -224,6 +228,7 @@ private bool IsInt64(object o) { return true; } + return false; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index 974d94cb628..de15cb6bed3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -30,8 +30,10 @@ public sealed class GetUniqueCommand : PSCmdlet public SwitchParameter AsString { get { return _asString; } + set { _asString = value; } } + private bool _asString; /// @@ -43,8 +45,10 @@ public SwitchParameter AsString public SwitchParameter OnType { get { return _onType; } + set { _onType = value; } } + private bool _onType = false; #endregion Parameters @@ -72,6 +76,7 @@ protected override void ProcessRecord() { _lastObjectAsString = _lastObject.ToString(); } + if (0 == String.Compare( inputString, _lastObjectAsString, @@ -93,6 +98,7 @@ protected override void ProcessRecord() CultureInfo.CurrentCulture, true); // case-sensitive } + isUnique = (0 != _comparer.Compare(InputObject, _lastObject)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 48ad6f65bfe..238f993e2b7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -60,6 +60,7 @@ protected override void ProcessRecord() continue; } } + foreach (FieldInfo field in type.GetFields()) { if (field.IsLiteral) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 6b669bc403e..82b77a0a44d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -65,11 +65,13 @@ public SwitchParameter Force { return new SwitchParameter(_force); } + set { _force = value.IsPresent; } } + private bool _force; /// @@ -247,6 +249,7 @@ private PSModuleInfo CreateModule(string manifestFile) public new string Prefix { set { base.Prefix = value; } + get { return base.Prefix; } } @@ -259,6 +262,7 @@ private PSModuleInfo CreateModule(string manifestFile) public SwitchParameter DisableNameChecking { get { return _disableNameChecking; } + set { _disableNameChecking = value; } } @@ -303,6 +307,7 @@ protected override void BeginProcessing() manifestFile = file; } } + Dbg.Assert(manifestFile != null, "A psd1 file should always be generated"); PSModuleInfo moduleInfo = this.CreateModule(manifestFile); @@ -350,6 +355,7 @@ public string[] CommandName { return _commandNameParameter; } + set { _commandNameParameter = value; @@ -359,6 +365,7 @@ public string[] CommandName WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } + private string[] _commandNameParameter; private Collection _commandNamePatterns; // initialized to default value in the constructor @@ -383,12 +390,14 @@ public object[] ArgumentList { return _commandArgs; } + set { _commandArgs = value; _commandParameterSpecified = true; } } + private object[] _commandArgs; /// @@ -402,6 +411,7 @@ public CommandTypes CommandType { return _commandType; } + set { _commandType = value; @@ -432,11 +442,13 @@ public string[] Module { value = new string[0]; } + _PSSnapins = value; _commandParameterSpecified = true; IsModuleSpecified = true; } } + private string[] _PSSnapins = new string[0]; internal bool IsModuleSpecified = false; /// @@ -458,10 +470,12 @@ public ModuleSpecification[] FullyQualifiedModule { _moduleSpecifications = value; } + _commandParameterSpecified = true; IsFullyQualifiedModuleSpecified = true; } } + private ModuleSpecification[] _moduleSpecifications = new ModuleSpecification[0]; internal bool IsFullyQualifiedModuleSpecified = false; @@ -482,6 +496,7 @@ public string[] FormatTypeName { return _formatTypeNameParameter; } + set { _formatTypeNameParameter = value; @@ -491,6 +506,7 @@ public string[] FormatTypeName WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } + private string[] _formatTypeNameParameter; // initialized to default value in the constructor private Collection _formatTypeNamePatterns; private bool _formatTypeNamesSpecified; // initialized to default value in the constructor @@ -666,10 +682,12 @@ private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, stri { throw PSTraceSource.NewArgumentNullException("commandName"); } + if (string.IsNullOrEmpty(nameType)) { throw PSTraceSource.NewArgumentNullException("nameType"); } + Dbg.Assert(nameType.Equals("Alias") || nameType.Equals("ParameterSet") || nameType.Equals("Parameter"), "nameType matches resource names"); if (string.IsNullOrEmpty(name)) { @@ -696,6 +714,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti { throw PSTraceSource.NewArgumentNullException("commandName"); } + if (runtimeException == null) { throw PSTraceSource.NewArgumentNullException("runtimeException"); @@ -834,6 +853,7 @@ private Dictionary ExistingCommands _existingCommands[commandInfo.Name] = null; } } + return _existingCommands; } } @@ -1000,6 +1020,7 @@ private T GetPropertyValue(string commandName, PSObject pso, string propertyN { this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); } + return ConvertTo(commandName, property.Value, nullOk); } @@ -1390,15 +1411,18 @@ private void AddRemoteCommandMetadata( { return; } + if (resolvedCommandName != null && !IsSafeNameOrIdentifier(commandMetadata.Name)) { this.WriteError(this.GetErrorSkippedUnsafeCommandName(resolvedCommandName)); return; } + if (IsCommandSkippedByServerDeclaration(commandMetadata.Name)) { return; } + if (!IsCommandNameAllowedForImport(commandMetadata.Name)) { return; @@ -1607,6 +1631,7 @@ internal List GetRemoteFormatData() this.DuplicatePowerShellStreams(powerShell); this.WriteProgress(startTime, ++numberOfReceivedObjects, expectedCount, ImplicitRemotingStrings.ProgressStatusGetFormatDataProgress); } + this.DuplicatePowerShellStreams(powerShell); powerShell.EndInvoke(asyncResult); @@ -1614,6 +1639,7 @@ internal List GetRemoteFormatData() { this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-FormatData")); } + return result; } } @@ -1643,11 +1669,13 @@ private PowerShell BuildPowerShellForGetCommand() { powerShell.AddParameter("Name", this.CommandName); } + powerShell.AddParameter(nameof(Module), this.Module); if (IsFullyQualifiedModuleSpecified) { powerShell.AddParameter(nameof(FullyQualifiedModule), this.FullyQualifiedModule); } + powerShell.AddParameter("ArgumentList", this.ArgumentList); powerShell.Runspace = Session.Runspace; @@ -1729,6 +1757,7 @@ internal List GetRemoteCommandMetadata(out Dictionary GetRemoteCommandMetadata(out Dictionary(name2commandMetadata.Values); } } @@ -1778,6 +1808,7 @@ private void WriteProgress(string statusDescription, int? percentComplete, int? return; } } + _lastTimeProgressWasWritten = DateTime.UtcNow; string activityDescription = StringUtil.Format(ImplicitRemotingStrings.ProgressActivity); @@ -1958,6 +1989,7 @@ private string EscapeFunctionNameForRemoteHelp(string name) result.Append(c); } } + return result.ToString(); } @@ -2227,12 +2259,17 @@ private string GenerateNewPSSessionOption() if (wsmanConnectionInfo != null) { if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } + if (wsmanConnectionInfo.NoEncryption) { result.Append("-NoEncryption "); } + if (wsmanConnectionInfo.NoMachineProfile) { result.Append("-NoMachineProfile "); } + if (wsmanConnectionInfo.UseUTF16) { result.Append("-UseUTF16 "); } if (wsmanConnectionInfo.SkipCACheck) { result.Append("-SkipCACheck "); } + if (wsmanConnectionInfo.SkipCNCheck) { result.Append("-SkipCNCheck "); } + if (wsmanConnectionInfo.SkipRevocationCheck) { result.Append("-SkipRevocationCheck "); } if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) @@ -2242,6 +2279,7 @@ private string GenerateNewPSSessionOption() "-MaximumReceivedDataSizePerCommand {0} ", wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value); } + if (wsmanConnectionInfo.MaximumReceivedObjectSize.HasValue) { result.AppendFormat( @@ -2249,6 +2287,7 @@ private string GenerateNewPSSessionOption() "-MaximumReceivedObjectSize {0} ", wsmanConnectionInfo.MaximumReceivedObjectSize.Value); } + result.AppendFormat( CultureInfo.InvariantCulture, "-MaximumRedirection {0} ", @@ -2333,6 +2372,7 @@ function Get-PSImplicitRemotingSession -InstanceId {0} ` -ErrorAction SilentlyContinue ) }} + if (($null -ne $script:PSSession) -and ($script:PSSession.Runspace.RunspaceStateInfo.State -eq 'Disconnected')) {{ # If we are handed a disconnected session, try re-connecting it before creating a new session. @@ -2341,6 +2381,7 @@ function Get-PSImplicitRemotingSession -Session $script:PSSession ` -ErrorAction SilentlyContinue) }} + if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened')) {{ Write-PSImplicitRemotingMessage ('{1}' -f $commandName) @@ -2360,10 +2401,12 @@ function Get-PSImplicitRemotingSession {8} }} + if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened')) {{ throw '{3}' }} + return [Management.Automation.Runspaces.PSSession]$script:PSSession }} "; @@ -2695,6 +2738,7 @@ function Get-PSImplicitRemotingClientSideParameters $proxyForCmdlet) $clientSideParameters = @{} + $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction' Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters 'AsJob' @@ -2765,6 +2809,7 @@ private void GenerateHelperFunctions(TextWriter writer) $null = $positionalArguments.Add( $PSBoundParameters[$parameterName] ) $null = $PSBoundParameters.Remove($parameterName) }} + $positionalArguments.AddRange($args) $clientSideParameters = Get-PSImplicitRemotingClientSideParameters $PSBoundParameters ${8} @@ -2783,7 +2828,9 @@ private void GenerateHelperFunctions(TextWriter writer) throw }} }} + Process {{ {6} }} + End {{ {7} }} # .ForwardHelpTargetName {1} @@ -2820,6 +2867,7 @@ private void GenerateCommandProxy(TextWriter writer, IEnumerable GetListOfCommandNames(IEnumerable listOfCo { listOfCommandNames.Add(commandMetadata.Name); } + return listOfCommandNames; } @@ -2887,6 +2937,7 @@ private string GenerateArrayString(IEnumerable listOfStrings) { arrayString.Append(", "); } + arrayString.Append('\''); arrayString.Append(CodeGeneration.EscapeSingleQuotedStringContent(s)); arrayString.Append('\''); @@ -2939,6 +2990,7 @@ private void GenerateFormatFile(TextWriter writer, List { throw PSTraceSource.NewArgumentNullException("writer"); } + if (listOfFormatData == null) { throw PSTraceSource.NewArgumentNullException("listOfFormatData"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index cc3fa79cb19..86f9afb1c3f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -36,6 +36,7 @@ public string BindingVariable _bindingVariable = value; } } + private string _bindingVariable; /// @@ -54,6 +55,7 @@ public string UICulture _uiculture = value; } } + private string _uiculture; /// @@ -72,6 +74,7 @@ public string BaseDirectory _baseDirectory = value; } } + private string _baseDirectory; /// @@ -90,6 +93,7 @@ public string FileName _fileName = value; } } + private string _fileName; /// @@ -104,12 +108,14 @@ public string[] SupportedCommand { return _commandsAllowed; } + set { _setSupportedCommand = true; _commandsAllowed = value; } } + private string[] _commandsAllowed = new string[] { "ConvertFrom-StringData" }; private bool _setSupportedCommand = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index bc30cde1f34..3e7ebcb8b27 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -73,6 +73,7 @@ public SwitchParameter PassThru _passThru = value; } } + private bool _passThru; /// @@ -92,6 +93,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; #endregion Parameters @@ -250,6 +252,7 @@ private Dictionary ExistingCommands } } } + return _existingCommands; } } @@ -373,8 +376,10 @@ private Collection GetAliasesFromFile(bool isLiteralPath) result.Add(newAlias); } + reader.Dispose(); } + return result; } @@ -469,6 +474,7 @@ private static bool OnlyContainsWhitespace(string line) result = false; break; } + return result; } #endregion Command code diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index a1ac032c6ed..1edac551584 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -35,6 +35,7 @@ public class ImportPowerShellDataFileCommand : PSCmdlet public string[] LiteralPath { get { return _isLiteralPath ? Path : null; } + set { _isLiteralPath = true; Path = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 97fdb97e089..09d97dd7fc4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -256,6 +256,7 @@ public SwitchParameter StandardDeviation { return _measureStandardDeviation; } + set { _measureStandardDeviation = value; @@ -275,11 +276,13 @@ public SwitchParameter Sum { return _measureSum; } + set { _measureSum = value; } } + private bool _measureSum; /// @@ -313,11 +316,13 @@ public SwitchParameter Average { return _measureAverage; } + set { _measureAverage = value; } } + private bool _measureAverage; /// @@ -331,11 +336,13 @@ public SwitchParameter Maximum { return _measureMax; } + set { _measureMax = value; } } + private bool _measureMax; /// @@ -349,11 +356,13 @@ public SwitchParameter Minimum { return _measureMin; } + set { _measureMin = value; } } + private bool _measureMin; #region TextMeasure ParameterSet @@ -367,11 +376,13 @@ public SwitchParameter Line { return _measureLines; } + set { _measureLines = value; } } + private bool _measureLines = false; /// @@ -384,11 +395,13 @@ public SwitchParameter Word { return _measureWords; } + set { _measureWords = value; } } + private bool _measureWords = false; /// @@ -401,11 +414,13 @@ public SwitchParameter Character { return _measureCharacters; } + set { _measureCharacters = value; } } + private bool _measureCharacters = false; /// @@ -418,11 +433,13 @@ public SwitchParameter IgnoreWhiteSpace { return _ignoreWhiteSpace; } + set { _ignoreWhiteSpace = value; } } + private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet @@ -642,10 +659,12 @@ internal static int CountChar(string inStr, bool ignoreWhiteSpace) { return 0; } + if (!ignoreWhiteSpace) { return inStr.Length; } + int len = 0; foreach (char c in inStr) { @@ -654,6 +673,7 @@ internal static int CountChar(string inStr, bool ignoreWhiteSpace) len++; } } + return len; } @@ -668,6 +688,7 @@ internal static int CountWord(string inStr) { return 0; } + int wordCount = 0; bool wasAWhiteSpace = true; foreach (char c in inStr) @@ -682,9 +703,11 @@ internal static int CountWord(string inStr) { wordCount++; } + wasAWhiteSpace = false; } } + return wordCount; } @@ -699,6 +722,7 @@ internal static int CountLine(string inStr) { return 0; } + int numberOfLines = 0; foreach (char c in inStr) { @@ -713,6 +737,7 @@ internal static int CountLine(string inStr) { numberOfLines++; } + return numberOfLines; } } @@ -744,6 +769,7 @@ private void AnalyzeNumber(double numValue, Statistics stat) stat.sumPrevious = stat.sum; stat.sum += numValue; } + if (_measureStandardDeviation && stat.count > 1) { // Based off of iterative method of calculating variance on @@ -889,6 +915,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene { gmi.Maximum = (double)max; } + if (min != null) { gmi.Minimum = (double)min; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs index 9f12a63161a..7e7be738132 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs @@ -37,6 +37,7 @@ protected override void EndProcessing() tempPath)); return; } + if (!string.IsNullOrEmpty(filePath)) { FileInfo file = new FileInfo(filePath); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs index a702357d643..0ce410f0cc5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -29,12 +29,14 @@ public DateTime Start { return _start; } + set { _start = value; _startSpecified = true; } } + private DateTime _start; private bool _startSpecified; @@ -50,12 +52,14 @@ public DateTime End { return _end; } + set { _end = value; _endSpecified = true; } } + private DateTime _end; private bool _endSpecified = false; @@ -104,6 +108,7 @@ protected override void ProcessRecord() { startTime = Start; } + if (_endSpecified) { endTime = End; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 7b68d4c7064..ddca8eb249c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -96,6 +96,7 @@ public override bool Equals(Object inputObject) { return true; } + if (baseObject != null && inComingbaseObjectPropertyValue != null) { return baseObject.ToString().Equals(inComingbaseObjectPropertyValue.ToString(), StringComparison.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index b3e349d4918..bbe080b6f1c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -57,6 +57,7 @@ public class ObjectCmdletBase : PSCmdlet public string Culture { get { return _cultureInfo != null ? _cultureInfo.ToString() : null; } + set { if (string.IsNullOrEmpty(value)) @@ -83,9 +84,11 @@ public string Culture _cultureInfo = new CultureInfo(cultureNumber); return; } + _cultureInfo = new CultureInfo(value); } } + internal CultureInfo _cultureInfo = null; /// @@ -95,8 +98,10 @@ public string Culture public SwitchParameter CaseSensitive { get { return _caseSensitive; } + set { _caseSensitive = value; } } + private bool _caseSensitive; #endregion Parameters } @@ -136,8 +141,10 @@ public class OrderObjectBase : ObjectBase internal SwitchParameter DescendingOrder { get { return !_ascending; } + set { _ascending = !value; } } + private bool _ascending = true; internal List InputObjects { get; } = new List(); @@ -213,6 +220,7 @@ private static void ProcessExpressionParameter( { expr = GetDefaultKeyPropertySet(inputObjects[0]); } + if (expr != null) { List unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); @@ -348,12 +356,14 @@ internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) { return null; } + PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet; if (defaultKeys == null) { return null; } + string[] props = new string[defaultKeys.ReferencedPropertyNames.Count]; defaultKeys.ReferencedPropertyNames.CopyTo(props, 0); return props; @@ -381,10 +391,12 @@ List mshParameterList { cmdlet.WriteError(err); } + foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); } + orderMatrixToCreate.Add(result); } @@ -407,6 +419,7 @@ private static OrderByPropertyComparer CreateComparer( { return null; } + bool?[] ascendingOverrides = null; if (mshParameterList != null && mshParameterList.Count != 0) { @@ -441,6 +454,7 @@ private static OrderByPropertyComparer CreateComparer( } } } + OrderByPropertyComparer comparer = OrderByPropertyComparer.CreateComparer(orderMatrix, ascending, ascendingOverrides, cultureInfo, caseSensitive); @@ -502,6 +516,7 @@ internal OrderByPropertyEntry CreateOrderByPropertyEntry( { cmdlet.WriteError(err); } + foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); @@ -577,6 +592,7 @@ private static void EvaluateSortingExpression( propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString()); return; } + propertyNotFoundMsg = null; // we obtained some results, enter them into the list foreach (PSPropertyExpressionResult r in expressionResults) @@ -595,6 +611,7 @@ private static void EvaluateSortingExpression( errors.Add(errorRecord); orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty); } + comparable = true; } } @@ -658,6 +675,7 @@ internal static OrderByPropertyComparer CreateComparer(List maxEntries) maxEntries = entry.orderValues.Count; } + if (maxEntries == 0) return null; @@ -696,6 +714,7 @@ public int Compare(OrderByPropertyEntry lhs, OrderByPropertyEntry rhs) { return lhs.comparable.CompareTo(rhs.comparable) * -1; } + int result = _orderByPropertyComparer.Compare(lhs, rhs); // When items are identical according to the internal comparison, compare by index // to preserve the original order diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index 5b4f14f47b4..4d51fec6994 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -110,6 +110,7 @@ protected override void BeginProcessing() sb.Append(element); } } + promptString = sb.ToString(); } else @@ -152,6 +153,7 @@ protected override void BeginProcessing() { result = Host.UI.ReadLine(); } + WriteObject(result); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs index ff2b2272149..c7c0d26b5e0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs @@ -25,11 +25,13 @@ public PSObject InputObject { return _inputObject; } + set { _inputObject = value; } } + private PSObject _inputObject = null; /// @@ -42,11 +44,13 @@ public string EventName { return _eventName; } + set { _eventName = value; } } + private string _eventName = null; #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs index f1b708fe7cc..cf0d8f7d308 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -23,6 +23,7 @@ public class RegisterEngineEventCommand : ObjectEventRegistrationBase { return base.SourceIdentifier; } + set { base.SourceIdentifier = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs index 0be3bf888c2..03099f196a5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -24,6 +24,7 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; @@ -34,6 +35,7 @@ public string SourceIdentifier } } } + private string _sourceIdentifier = null; /// @@ -46,11 +48,13 @@ public int EventIdentifier { return _eventIdentifier; } + set { _eventIdentifier = value; } } + private int _eventIdentifier = -1; #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs index d430a928a84..1a68ee4ce31 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -38,11 +38,13 @@ public int Column { return _column ?? 0; } + set { _column = value; } } + private int? _column = null; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 35e157b74b0..6d108395d69 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -50,6 +50,7 @@ public class ShowMarkdownCommand : PSCmdlet public string[] LiteralPath { get { return Path; } + set { Path = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index 5ef327f161e..61130e1d65f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -29,6 +29,7 @@ public void Dispose() _waitHandle.Dispose(); _waitHandle = null; } + _disposed = true; } } @@ -79,6 +80,7 @@ private void Sleep(int milliSecondsToSleep) _waitHandle = new ManualResetEvent(false); } } + if (_waitHandle != null) { _waitHandle.WaitOne(milliSecondsToSleep, true); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index 5d4212c44d3..401ce2ab8aa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -34,6 +34,7 @@ public string[] Path { return _paths; } + set { _paths = value; @@ -52,6 +53,7 @@ public string[] LiteralPath { return _paths; } + set { _paths = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index a1621bef845..fb8f17eb531 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -24,6 +24,7 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; @@ -34,6 +35,7 @@ public string SourceIdentifier } } } + private string _sourceIdentifier = null; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs index 6ee921cecff..38fece39dfa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs @@ -75,11 +75,13 @@ internal static Collection Glob(string[] files, string errorId, PSCmdlet cmdlet.WriteError(new ErrorRecord(e, errorId, ErrorCategory.InvalidOperation, file)); continue; } + if (!provider.NameEquals(cmdlet.Context.ProviderNames.FileSystem)) { ReportWrongProviderType(provider.FullName, errorId, cmdlet); continue; } + foreach (string providerPath in providerPaths) { if (!providerPath.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase)) @@ -87,6 +89,7 @@ internal static Collection Glob(string[] files, string errorId, PSCmdlet ReportWrongExtension(providerPath, "WrongExtension", cmdlet); continue; } + retValue.Add(providerPath); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index 2c0bd5b4478..4d013301adf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -52,6 +52,7 @@ public PSMemberTypes MemberType _memberType = value; _isMemberTypeSet = true; } + get { return _memberType; } } @@ -64,6 +65,7 @@ public PSMemberTypes MemberType public string MemberName { set { _memberName = value; } + get { return _memberName; } } @@ -76,6 +78,7 @@ public string MemberName public object Value { set { _value1 = value; } + get { return _value1; } } @@ -89,6 +92,7 @@ public object Value public object SecondValue { set { _value2 = value; } + get { return _value2; } } @@ -101,6 +105,7 @@ public object SecondValue public Type TypeConverter { set { _typeConverter = value; } + get { return _typeConverter; } } @@ -113,6 +118,7 @@ public Type TypeConverter public Type TypeAdapter { set { _typeAdapter = value; } + get { return _typeAdapter; } } @@ -124,6 +130,7 @@ public Type TypeAdapter public string SerializationMethod { set { _serializationMethod = value; } + get { return _serializationMethod; } } @@ -135,6 +142,7 @@ public string SerializationMethod public Type TargetTypeForDeserialization { set { _targetTypeForDeserialization = value; } + get { return _targetTypeForDeserialization; } } @@ -147,6 +155,7 @@ public Type TargetTypeForDeserialization public int SerializationDepth { set { _serializationDepth = value; } + get { return _serializationDepth; } } @@ -158,6 +167,7 @@ public int SerializationDepth public string DefaultDisplayProperty { set { _defaultDisplayProperty = value; } + get { return _defaultDisplayProperty; } } @@ -169,6 +179,7 @@ public string DefaultDisplayProperty public bool? InheritPropertySerializationSet { set { _inheritPropertySerializationSet = value; } + get { return _inheritPropertySerializationSet; } } @@ -180,6 +191,7 @@ public bool? InheritPropertySerializationSet public string StringSerializationSource { set { _stringSerializationSource = value; } + get { return _stringSerializationSource; } } @@ -192,6 +204,7 @@ public string StringSerializationSource public string[] DefaultDisplayPropertySet { set { _defaultDisplayPropertySet = value; } + get { return _defaultDisplayPropertySet; } } @@ -204,6 +217,7 @@ public string[] DefaultDisplayPropertySet public string[] DefaultKeyPropertySet { set { _defaultKeyPropertySet = value; } + get { return _defaultKeyPropertySet; } } @@ -216,6 +230,7 @@ public string[] DefaultKeyPropertySet public string[] PropertySerializationSet { set { _propertySerializationSet = value; } + get { return _propertySerializationSet; } } @@ -244,6 +259,7 @@ public string[] PropertySerializationSet public string TypeName { set { _typeName = value; } + get { return _typeName; } } @@ -256,6 +272,7 @@ public string TypeName public SwitchParameter Force { set { _force = value; } + get { return _force; } } @@ -272,6 +289,7 @@ public SwitchParameter Force public TypeData[] TypeData { set { _typeData = value; } + get { return _typeData; } } @@ -330,6 +348,7 @@ private void ProcessStrongTypeData() { continue; } + TypeData type = item.Copy(); // Set property IsOverride to be true if -Force parameter is specified @@ -388,6 +407,7 @@ private void ProcessDynamicType() { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } + TypeData type = new TypeData(_typeName) { IsOverride = _force }; GetMembers(type.Members); @@ -396,6 +416,7 @@ private void ProcessDynamicType() { type.TypeConverter = _typeConverter; } + if (_typeAdapter != null) { type.TypeAdapter = _typeAdapter; @@ -405,36 +426,44 @@ private void ProcessDynamicType() { type.SerializationMethod = _serializationMethod; } + if (_targetTypeForDeserialization != null) { type.TargetTypeForDeserialization = _targetTypeForDeserialization; } + if (_serializationDepth != int.MinValue) { type.SerializationDepth = (uint)_serializationDepth; } + if (_defaultDisplayProperty != null) { type.DefaultDisplayProperty = _defaultDisplayProperty; } + if (_inheritPropertySerializationSet != null) { type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; } + if (_stringSerializationSource != null) { type.StringSerializationSource = _stringSerializationSource; } + if (_defaultDisplayPropertySet != null) { PropertySetData defaultDisplayPropertySet = new PropertySetData(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } + if (_defaultKeyPropertySet != null) { PropertySetData defaultKeyPropertySet = new PropertySetData(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } + if (_propertySerializationSet != null) { PropertySetData propertySerializationSet = new PropertySetData(_propertySerializationSet); @@ -502,6 +531,7 @@ private void GetMembers(Dictionary members) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } + return; } @@ -566,6 +596,7 @@ private void EnsureValue1NotNullOrEmpty() { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } + return; } @@ -607,6 +638,7 @@ private bool EnsureTypeDataIsNotEmpty(TypeData typeData) this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); return false; } + return true; } @@ -632,6 +664,7 @@ private AliasPropertyData GetAliasProperty() alias = new AliasPropertyData(_memberName, referencedName, type); return alias; } + alias = new AliasPropertyData(_memberName, referencedName); return alias; } @@ -833,6 +866,7 @@ private void ProcessTypeFiles() RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } + errors = new ConcurrentBag(); } } @@ -1020,6 +1054,7 @@ public class RemoveTypeDataCommand : PSCmdlet public string TypeName { get { return _typeName; } + set { _typeName = value; } } @@ -1034,6 +1069,7 @@ public string TypeName public string[] Path { get { return _typeFiles; } + set { _typeFiles = value; } } @@ -1046,6 +1082,7 @@ public string[] Path public TypeData TypeData { get { return _typeData; } + set { _typeData = value; } } @@ -1163,6 +1200,7 @@ protected override void ProcessRecord() { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } + typeNameToRemove = _typeName; } @@ -1272,6 +1310,7 @@ private void ValidateTypeName() { typeNameInUse = type.FullName; } + typeNames.Add(typeNameInUse); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index e6d5499434b..f5ba3f3a1f6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -44,9 +44,11 @@ protected string[] IncludeFilters { value = new string[0]; } + _include = value; } } + private string[] _include = new string[0]; /// @@ -65,9 +67,11 @@ protected string[] ExcludeFilters { value = new string[0]; } + _exclude = value; } } + private string[] _exclude = new string[0]; #region helpers @@ -210,6 +214,7 @@ internal List GetMatchingVariables(string name, string lookupScope, } } } + result.Add(entry.Value); } else @@ -225,6 +230,7 @@ internal List GetMatchingVariables(string name, string lookupScope, } } } + return result; } #endregion helpers @@ -258,9 +264,11 @@ public string[] Name { value = new string[] { "*" }; } + _name = value; } } + private string[] _name = new string[] { "*" }; /// @@ -273,11 +281,13 @@ public SwitchParameter ValueOnly { return _valueOnly; } + set { _valueOnly = value; } } + private bool _valueOnly; /// @@ -413,6 +423,7 @@ public SessionStateEntryVisibility Visibility _visibility = value; } } + private SessionStateEntryVisibility? _visibility; /// @@ -431,6 +442,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; /// @@ -443,11 +455,13 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; } } + private bool _passThru; #endregion parameters @@ -624,11 +638,13 @@ public ScopedItemOptions Option { return (ScopedItemOptions)_options; } + set { _options = value; } } + private ScopedItemOptions? _options; /// @@ -647,6 +663,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; /// @@ -665,6 +682,7 @@ public SessionStateEntryVisibility Visibility _visibility = value; } } + private SessionStateEntryVisibility? _visibility; /// @@ -677,11 +695,13 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; } } + private bool _passThru; private bool _nameIsFormalParameter; @@ -728,6 +748,7 @@ protected override void ProcessRecord() { _valueList = new ArrayList(); } + _valueList.Add(Value); } } @@ -736,6 +757,7 @@ protected override void ProcessRecord() SetVariable(Name, Value); } } + private ArrayList _valueList; /// @@ -856,6 +878,7 @@ private void SetVariable(string[] varNames, object varValue) { Description = String.Empty; } + varToSet.Description = Description; // If visibility was specified, set it on the variable @@ -1064,11 +1087,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; #endregion parameters @@ -1220,6 +1245,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; /// @@ -1232,11 +1258,13 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; } } + private bool _passThru; #endregion parameters @@ -1348,6 +1376,7 @@ private PSVariable ClearValue(PSVariable matchingVariable) SessionState.PSVariable.Set(matchingVariable.Name, null); result = SessionState.PSVariable.Get(matchingVariable.Name); } + return result; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 8281062e3af..cc8fbae3b83 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -26,12 +26,14 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } + private string _sourceIdentifier = null; /// @@ -47,11 +49,13 @@ public int Timeout { return _timeoutInSeconds; } + set { _timeoutInSeconds = value; } } + private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs index e19617506ed..f0cd5d4b20e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs @@ -23,6 +23,7 @@ public sealed class WriteOutputCommand : PSCmdlet public PSObject[] InputObject { get { return _inputObjects; } + set { _inputObjects = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs index 19aba7620ac..b1a38d3930b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -56,6 +56,7 @@ public SwitchParameter PassThru _passThru = value; } } + private bool _passThru; /// @@ -81,6 +82,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; #endregion Parameters } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 66dc44a310c..eb9318f4305 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -31,6 +31,7 @@ public SwitchParameter NoNewline { return _notAppendNewline; } + set { _notAppendNewline = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index 726d50f47a3..eb76bdc525e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -78,6 +78,7 @@ public SwitchParameter Completed { return _completed; } + set { _completed = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 1fa3f9befa5..04ff0404d3a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -52,12 +52,14 @@ public string LiteralPath { return Path; } + set { Path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -77,11 +79,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -95,11 +99,13 @@ public SwitchParameter NoClobber { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// @@ -149,6 +155,7 @@ protected override _serializer.Done(); _serializer = null; } + CleanUp(); } @@ -233,6 +240,7 @@ private void CreateFileStream() _xw.Dispose(); _xw = null; } + _fs.Dispose(); _fs = null; } @@ -258,6 +266,7 @@ private void CreateFileStream() { CleanUp(); } + _disposed = true; } @@ -290,12 +299,14 @@ public String[] LiteralPath { return Path; } + set { Path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; #endregion Command Line Parameters @@ -317,6 +328,7 @@ public void Dispose() _helper.Dispose(); _helper = null; } + _disposed = true; } } @@ -383,11 +395,13 @@ public SwitchParameter NoTypeInformation { return _notypeinformation; } + set { _notypeinformation = value; } } + private bool _notypeinformation; /// @@ -598,6 +612,7 @@ private void CleanUp() { CleanUp(); } + _disposed = true; } @@ -696,6 +711,7 @@ public void Dispose() { CleanUp(); } + _disposed = true; GC.SuppressFinalize(this); } @@ -811,12 +827,14 @@ public class SelectXmlCommand : PSCmdlet public String[] LiteralPath { get { return Path; } + set { Path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -891,6 +909,7 @@ private void ProcessXmlNode(XmlNode xmlNode, string filePath) { xList = xmlNode.SelectNodes(XPath); } + this.WriteResults(xList, filePath); } @@ -1029,9 +1048,11 @@ protected override void ProcessRecord() WriteError(er); continue; } + fullresolvedPaths.AddRange(resolvedPaths); } } + foreach (string file in fullresolvedPaths) { ProcessXmlFile(file); @@ -1090,6 +1111,7 @@ public string Path { return _path; } + set { if (String.IsNullOrEmpty(value)) @@ -1102,6 +1124,7 @@ public string Path } } } + private string _path; /// @@ -1148,6 +1171,7 @@ internal string GetNodeText() nodeText = Node.InnerXml.Trim(); } } + return nodeText; } @@ -1177,6 +1201,7 @@ private string RelativePath(string directory) } } } + return relPath; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs index 6a3ab5e59cf..536d5044adf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs @@ -47,8 +47,10 @@ public sealed class CompareObjectCommand : ObjectCmdletBase public SwitchParameter IgnoreWhiteSpace { get { return _ignoreWhiteSpace; } + set { _ignoreWhiteSpace = value; } } + private bool _ignoreWhiteSpace = false; */ @@ -58,8 +60,10 @@ public SwitchParameter IgnoreWhiteSpace public SwitchParameter ExcludeDifferent { get { return _excludeDifferent; } + set { _excludeDifferent = value; } } + private bool _excludeDifferent /*=false*/; /// @@ -68,12 +72,14 @@ public SwitchParameter ExcludeDifferent public SwitchParameter IncludeEqual { get { return _includeEqual; } + set { _isIncludeEqualSpecified = true; _includeEqual = value; } } + private bool _includeEqual /* = false */; private bool _isIncludeEqualSpecified /* = false */; @@ -83,8 +89,10 @@ public SwitchParameter IncludeEqual public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private bool _passThru /* = false */; #endregion Parameters @@ -203,6 +211,7 @@ private void Process(OrderByPropertyEntry differenceEntry) EmitDifferenceOnly(_differenceEntryBacklog[0]); _differenceEntryBacklog.RemoveAt(0); } + _differenceEntryBacklog.Add(differenceEntry); } else @@ -228,6 +237,7 @@ private void Process(OrderByPropertyEntry differenceEntry) EmitReferenceOnly(_referenceEntryBacklog[0]); _referenceEntryBacklog.RemoveAt(0); } + _referenceEntryBacklog.Add(referenceEntry); } else @@ -276,6 +286,7 @@ private OrderByPropertyEntry MatchAndRemove( return listEntry; } } + return null; } @@ -347,6 +358,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) } } } + mshobj.Properties.Remove(SideIndicatorPropertyName); PSNoteProperty sideNote = new PSNoteProperty( SideIndicatorPropertyName, sideIndicator); @@ -370,6 +382,7 @@ protected override void BeginProcessing() { return; } + if (_isIncludeEqualSpecified && !_includeEqual) { return; @@ -429,11 +442,13 @@ protected override void EndProcessing() { EmitDifferenceOnly(differenceEntry); } + _differenceEntryBacklog.Clear(); foreach (OrderByPropertyEntry referenceEntry in _referenceEntryBacklog) { EmitReferenceOnly(referenceEntry); } + _referenceEntryBacklog.Clear(); } #endregion Overrides diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs index 34f55b0d2d5..c0f05a4f0de 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs @@ -32,11 +32,13 @@ public PSObject InputObject { return _inputObject; } + set { _inputObject = value; } } + private PSObject _inputObject; /// @@ -51,11 +53,13 @@ public object[] Property { return _property; } + set { _property = value; } } + private object[] _property; /// @@ -69,11 +73,13 @@ public string[] Body { return _body; } + set { _body = value; } } + private string[] _body; /// @@ -87,11 +93,13 @@ public string[] Head { return _head; } + set { _head = value; } } + private string[] _head; /// @@ -110,11 +118,13 @@ public string Title { return _title; } + set { _title = value; } } + private string _title = "HTML TABLE"; /// @@ -132,11 +142,13 @@ public string As { return _as; } + set { _as = value; } } + private string _as = "Table"; /// @@ -153,12 +165,14 @@ public Uri CssUri { return _cssuri; } + set { _cssuri = value; _cssuriSpecified = true; } } + private Uri _cssuri; private bool _cssuriSpecified; @@ -175,11 +189,13 @@ public SwitchParameter Fragment { return _fragment; } + set { _fragment = value; } } + private SwitchParameter _fragment; /// @@ -194,11 +210,13 @@ public string[] PostContent { return _postContent; } + set { _postContent = value; } } + private string[] _postContent; /// @@ -213,11 +231,13 @@ public string[] PreContent { return _preContent; } + set { _preContent = value; } } + private string[] _preContent; /// @@ -232,12 +252,14 @@ public Hashtable Meta { return _meta; } + set { _meta = value; _metaSpecified = true; } } + private Hashtable _meta; private bool _metaSpecified = false; @@ -253,12 +275,14 @@ public string Charset { return _charset; } + set { _charset = value; _charsetSpecified = true; } } + private string _charset; private bool _charsetSpecified = false; @@ -275,11 +299,13 @@ public SwitchParameter Transitional { return _transitional; } + set { _transitional = true; } } + private bool _transitional = false; /// @@ -320,6 +346,7 @@ private List ProcessParameter(object[] properties) { properties = new object[] { "*" }; } + return processor.ProcessParameters(properties, invocationContext); } @@ -345,6 +372,7 @@ private void InitializeResolvedNameMshParameters() resolvedNameProperty.Add(ht); } } + _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray()); } @@ -358,14 +386,17 @@ private static Hashtable CreateAuxPropertyHT( { ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label); } + if (alignment != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment); } + if (width != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width); } + return ht; } @@ -380,6 +411,7 @@ private static string SafeToString(object obj) { return string.Empty; } + try { return obj.ToString(); @@ -388,6 +420,7 @@ private static string SafeToString(object obj) { // eats exception if safe } + return string.Empty; } @@ -424,12 +457,14 @@ protected override void BeginProcessing() { WriteObject(""); } + WriteObject(""); WriteObject(""); if (_charsetSpecified) { WriteObject(""); } + if (_metaSpecified) { List useditems = new List(); @@ -462,29 +497,35 @@ protected override void BeginProcessing() { record.SetInvocationInfo(invocationInfo); } + mshCommandRuntime.WriteWarning(record); WriteObject(""); break; } + useditems.Add(s); } } } + WriteObject(_head ?? new string[] { "" + _title + "" }, true); if (_cssuriSpecified) { WriteObject(""); } + WriteObject(""); if (_body != null) { WriteObject(_body, true); } } + if (_preContent != null) { WriteObject(_preContent, true); } + WriteObject(""); _isTHWritten = false; _propertyCollector = new StringCollection(); @@ -509,6 +550,7 @@ private void WriteColumns(List mshParams) COLTag.Append(width); COLTag.Append("\""); } + string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; if (alignment != null) { @@ -516,6 +558,7 @@ private void WriteColumns(List mshParams) COLTag.Append(alignment); COLTag.Append("\""); } + COLTag.Append("/>"); } @@ -584,8 +627,10 @@ private void WritePropertyValue(StringBuilder Listtag, MshParameter p) string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result)); Listtag.Append(htmlEncodedResult); } + Listtag.Append(", "); } + if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal)) { Listtag.Remove(Listtag.Length - 2, 2); @@ -634,6 +679,7 @@ protected override void ProcessRecord() { return; } + _numberObjects++; if (!_isTHWritten) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/join-string.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/join-string.cs index 35be218ce5d..0e6c91a221e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/join-string.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/join-string.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs index 06bd984898d..ff334766d21 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs @@ -166,6 +166,7 @@ protected override void BeginProcessing() ErrorCategory.InvalidType, targetObject: null)); } + throw e; } @@ -211,6 +212,7 @@ protected override void BeginProcessing() // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } + WriteObject(_newObject); return; } @@ -235,6 +237,7 @@ protected override void BeginProcessing() "ConstructorCalledThrowException", ErrorCategory.InvalidOperation, null)); } + WriteObject(_newObject); return; } @@ -251,6 +254,7 @@ protected override void BeginProcessing() // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } + WriteObject(_newObject); return; } @@ -308,11 +312,13 @@ protected override void BeginProcessing() ErrorCategory.InvalidArgument, comObject)); } } + if (comObject != null && Property != null) { // Win8:649519 comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } + WriteObject(comObject); } #endif @@ -418,6 +424,7 @@ private void STAComCreateThreadProc(Object createstruct) info.success = false; return; } + info.objectCreated = SafeCreateInstance(type, ArgumentList); info.success = true; } @@ -443,6 +450,7 @@ private object CreateComObject() ThrowTerminatingError( new ErrorRecord(mshArgE, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); } + return SafeCreateInstance(type, ArgumentList); } catch (COMException e) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs index df1e3612c04..e527c9da505 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs @@ -26,11 +26,13 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; } } + private string _sourceIdentifier = null; /// @@ -44,11 +46,13 @@ public PSObject Sender { return _sender; } + set { _sender = value; } } + private PSObject _sender = null; /// @@ -62,6 +66,7 @@ public PSObject[] EventArguments { return _eventArguments; } + set { if (_eventArguments != null) @@ -70,6 +75,7 @@ public PSObject[] EventArguments } } } + private PSObject[] _eventArguments = new PSObject[0]; /// @@ -82,11 +88,13 @@ public PSObject MessageData { return _messageData; } + set { _messageData = value; } } + private PSObject _messageData = null; #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs index aece2f1466d..ca40cb9e00c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs @@ -47,6 +47,7 @@ internal bool IsMatch(PSPropertyExpression expression) if (_wildcardPatterns[k].IsMatch(expression.ToString())) return true; } + return false; } @@ -104,8 +105,10 @@ public sealed class SelectObjectCommand : PSCmdlet public SwitchParameter Unique { get { return _unique; } + set { _unique = value; } } + private bool _unique; /// @@ -118,8 +121,10 @@ public SwitchParameter Unique public int Last { get { return _last; } + set { _last = value; _firstOrLastSpecified = true; } } + private int _last = 0; /// @@ -132,8 +137,10 @@ public int Last public int First { get { return _first; } + set { _first = value; _firstOrLastSpecified = true; } } + private int _first = 0; private bool _firstOrLastSpecified; @@ -173,6 +180,7 @@ public int[] Index { return _index; } + set { _index = value; @@ -195,6 +203,7 @@ public int[] SkipIndex { return _index; } + set { _index = value; @@ -241,6 +250,7 @@ public bool AllRequestedObjectsProcessed { base.Dequeue(); } + base.Enqueue(obj); } @@ -316,6 +326,7 @@ internal UniquePSObjectHelper(PSObject o, int notePropertyCount) WrittenObject = o; NotePropertyCount = notePropertyCount; } + internal readonly PSObject WrittenObject; internal int NotePropertyCount { get; } } @@ -330,6 +341,7 @@ private void ProcessExpressionParameter() if ((Property != null) && (Property.Length != 0)) { // Build property list taking into account the wildcards and @{name=;expression=} + _propertyMshParameterList = processor.ProcessParameters(Property, invocationContext); } else @@ -399,6 +411,7 @@ private void ProcessObject(PSObject inputObject) } } } + FilteredWriteObject(result, matchedProperties); } else @@ -467,15 +480,18 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List matchedProperties) { @@ -491,6 +507,7 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, inputObject); throw new SelectObjectException(errorRecord); } + if (expressionResults.Count > 1) { ErrorRecord errorRecord = new ErrorRecord( @@ -580,6 +597,7 @@ private void WriteAlreadyExistingPropertyError(string name, object inputObject, inputObject); WriteError(errorRecord); } + private void FilteredWriteObject(PSObject obj, List addedNoteProperties) { Diagnostics.Assert(obj != null, "This command should never write null"); @@ -591,6 +609,7 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro SetPSCustomObject(obj); WriteObject(obj); } + return; } //if only unique is mentioned @@ -613,6 +632,7 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro break; } } + if (found) { isObjUnique = false; @@ -624,6 +644,7 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro continue; } } + if (isObjUnique) { SetPSCustomObject(obj); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs index 9b03cefb750..b21428dbe7e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs @@ -23,6 +23,7 @@ public sealed class SortObjectCommand : OrderObjectBase public SwitchParameter Descending { get { return DescendingOrder; } + set { DescendingOrder = value; } } /// @@ -33,8 +34,10 @@ public SwitchParameter Descending public SwitchParameter Unique { get { return _unique; } + set { _unique = value; } } + private bool _unique; #endregion @@ -156,6 +159,7 @@ private int Heapify(List dataToSort, OrderByPropertyCompar dataToSort[dataIndex] = dataToSort[dataToSort.Count - discardedDuplicates]; dataIndex--; } + continue; } @@ -178,6 +182,7 @@ private int Heapify(List dataToSort, OrderByPropertyCompar childIndex = parentIndex; } + heapCount++; // If the heap size is too large, remove the root and rearrange the heap diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs index 63914fbbf62..541969ba498 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs @@ -20,8 +20,10 @@ public sealed class TeeObjectCommand : PSCmdlet, IDisposable public PSObject InputObject { get { return _inputObject; } + set { _inputObject = value; } } + private PSObject _inputObject; /// @@ -32,8 +34,10 @@ public PSObject InputObject public string FilePath { get { return _fileName; } + set { _fileName = value; } } + private string _fileName; /// @@ -47,6 +51,7 @@ public string LiteralPath { return _fileName; } + set { _fileName = value; @@ -60,8 +65,10 @@ public string LiteralPath public SwitchParameter Append { get { return _append; } + set { _append = value; } } + private bool _append; /// @@ -71,8 +78,10 @@ public SwitchParameter Append public string Variable { get { return _variable; } + set { _variable = value; } } + private string _variable; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs index d156af65924..282396fcac8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs @@ -134,14 +134,17 @@ private Hashtable CreateHashtable() { hash.Add("Add", Add); } + if (Remove != null) { hash.Add("Remove", Remove); } + if (Replace != null) { hash.Add("Replace", Replace); } + return hash; } @@ -155,6 +158,7 @@ private PSListModifier CreatePSListModifier() listModifier.Add.Add(obj); } } + if (Remove != null) { foreach (object obj in Remove) @@ -162,6 +166,7 @@ private PSListModifier CreatePSListModifier() listModifier.Remove.Add(obj); } } + if (Replace != null) { foreach (object obj in Replace) @@ -169,6 +174,7 @@ private PSListModifier CreatePSListModifier() listModifier.Replace.Add(obj); } } + return listModifier; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs index 097c85ad1dc..94ab8510d29 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs @@ -317,11 +317,13 @@ protected override void ProcessRecord() { e = new WriteErrorException(msg); } + string errid = ErrorId; if (String.IsNullOrEmpty(errid)) { errid = e.GetType().FullName; } + errorRecord = new ErrorRecord( e, errid, @@ -342,6 +344,7 @@ protected override void ProcessRecord() { errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString()); } + errorRecord.ErrorDetails.RecommendedAction = recact; } From dca7f25be6bcd7d9249abfb1de53e223377f9114 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:39 -0800 Subject: [PATCH 20/81] Update ShowCommand --- .../commands/utility/ShowCommand/ShowCommand.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 4ea4f5eaf15..56f2d7c3e8a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -99,6 +99,7 @@ public class ShowCommandCommand : PSCmdlet, IDisposable public SwitchParameter NoCommonParameter { get { return _noCommonParameter; } + set { _noCommonParameter = value; } } @@ -115,6 +116,7 @@ public SwitchParameter NoCommonParameter public SwitchParameter PassThru { get { return _passThrough; } + set { _passThrough = value; } } #endregion From c01083fe60ab17f8a4c17b66dfcdca60c9a8b7d7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:39 -0800 Subject: [PATCH 21/81] Update trace --- .../commands/utility/trace/GetTracerCommand.cs | 1 + .../commands/utility/trace/MshHostTraceListener.cs | 1 + .../commands/utility/trace/SetTracerCommand.cs | 10 ++++++++++ .../utility/trace/TraceExpressionCommand.cs | 13 +++++++++++++ .../utility/trace/TraceListenerCommandBase.cs | 11 +++++++++++ 5 files changed, 36 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index cffb46fbaeb..6b93c25cb9d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -38,6 +38,7 @@ public string[] Name _names = value; } } + private string[] _names = new string[] { "*" }; #endregion Parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index de86d31eb68..1f2ab5b94fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -89,6 +89,7 @@ public override void Write(string output) // We don't want tracing to bring down the process. } } + private StringBuilder _cachedWrite = new StringBuilder(); /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index f8ab3cb6dcc..1cbf6f56521 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -24,6 +24,7 @@ public class SetTraceSourceCommand : TraceListenerCommandBase public string[] Name { get { return base.NameInternal; } + set { base.NameInternal = value; } } @@ -34,6 +35,7 @@ public string[] Name public PSTraceSourceOptions Option { get { return base.OptionsInternal; } + set { base.OptionsInternal = value; @@ -47,6 +49,7 @@ public PSTraceSourceOptions Option public TraceOptions ListenerOption { get { return base.ListenerOptionsInternal; } + set { base.ListenerOptionsInternal = value; @@ -62,6 +65,7 @@ public TraceOptions ListenerOption public string FilePath { get { return base.FileListener; } + set { base.FileListener = value; } } @@ -72,6 +76,7 @@ public string FilePath public SwitchParameter Force { get { return base.ForceWrite; } + set { base.ForceWrite = value; } } @@ -83,6 +88,7 @@ public SwitchParameter Force public SwitchParameter Debugger { get { return base.DebuggerListener; } + set { base.DebuggerListener = value; } } @@ -94,6 +100,7 @@ public SwitchParameter Debugger public SwitchParameter PSHost { get { return base.PSHostListener; } + set { base.PSHostListener = value; } } @@ -120,8 +127,10 @@ public SwitchParameter PSHost public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } + private bool _passThru; #endregion Parameters @@ -146,6 +155,7 @@ protected override void ProcessRecord() WriteObject(matchingSources, true); WriteObject(preconfiguredTraceSources, true); } + break; case "removeAllListenersSet": diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index e6098c38a9d..93155079257 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -36,6 +36,7 @@ public class TraceCommandCommand : TraceListenerCommandBase, IDisposable public string[] Name { get { return base.NameInternal; } + set { base.NameInternal = value; } } @@ -47,6 +48,7 @@ public string[] Name public PSTraceSourceOptions Option { get { return base.OptionsInternal; } + set { base.OptionsInternal = value; @@ -82,6 +84,7 @@ public PSTraceSourceOptions Option public TraceOptions ListenerOption { get { return base.ListenerOptionsInternal; } + set { base.ListenerOptionsInternal = value; @@ -97,6 +100,7 @@ public TraceOptions ListenerOption public string FilePath { get { return base.FileListener; } + set { base.FileListener = value; } } @@ -107,6 +111,7 @@ public string FilePath public SwitchParameter Force { get { return base.ForceWrite; } + set { base.ForceWrite = value; } } @@ -118,6 +123,7 @@ public SwitchParameter Force public SwitchParameter Debugger { get { return base.DebuggerListener; } + set { base.DebuggerListener = value; } } @@ -129,6 +135,7 @@ public SwitchParameter Debugger public SwitchParameter PSHost { get { return base.PSHostListener; } + set { base.PSHostListener = value; } } @@ -177,6 +184,7 @@ protected override void BeginProcessing() _pipeline.ExternalErrorOutput = new TracePipelineWriter(this, true, _matchingSources); _pipeline.ExternalSuccessOutput = new TracePipelineWriter(this, false, _matchingSources); } + ResetTracing(_matchingSources); } @@ -199,6 +207,7 @@ protected override void ProcessRecord() result = StepCommand(); break; } + ResetTracing(_matchingSources); if (result == null) @@ -228,6 +237,7 @@ protected override void EndProcessing() WriteObject(results, true); } + this.Dispose(); } @@ -261,6 +271,7 @@ private object StepCommand() { _pipeline.Step(InputObject); } + return null; } @@ -299,9 +310,11 @@ public void Dispose() fileStream.Dispose(); } } + GC.SuppressFinalize(this); } } + private bool _disposed; #endregion IDisposable } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index 28b4af6489e..a30fe500b45 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -34,12 +34,14 @@ public class TraceListenerCommandBase : TraceCommandBase internal PSTraceSourceOptions OptionsInternal { get { return _options; } + set { _options = value; optionsSpecified = true; } } + private PSTraceSourceOptions _options = PSTraceSourceOptions.All; /// @@ -53,12 +55,14 @@ internal PSTraceSourceOptions OptionsInternal internal TraceOptions ListenerOptionsInternal { get { return _traceOptions; } + set { traceOptionsSpecified = true; _traceOptions = value; } } + private TraceOptions _traceOptions = TraceOptions.None; /// @@ -94,8 +98,10 @@ internal TraceOptions ListenerOptionsInternal internal SwitchParameter PSHostListener { get { return _host; } + set { _host = value; } } + private bool _host = false; #endregion Parameters @@ -195,6 +201,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc // Note, this is not meant to be localized. _defaultListener.Name = "Debug"; } + AddListenerToSources(matchingSources, _defaultListener); } @@ -208,6 +215,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc // Note, this is not meant to be localized. _hostListener.Name = "Host"; } + AddListenerToSources(matchingSources, _hostListener); } @@ -262,6 +270,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc FileListener, provider.FullName)); } + resolvedPaths.Add(path); } @@ -361,6 +370,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc } } } + private DefaultTraceListener _defaultListener; private PSHostTraceListener _hostListener; private Collection _fileListeners; @@ -582,6 +592,7 @@ protected void ClearStoredState() listener.Dispose(); } } + _storedTraceSourceState.Clear(); } From cd6b0dd823c1df0be2319726f86425e45b03b46b Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:39 -0800 Subject: [PATCH 22/81] Update WebCmdlet --- .../commands/utility/WebCmdlet/ConvertToJsonCommand.cs | 4 ++++ .../commands/utility/WebCmdlet/FormObjectCollection.cs | 1 + .../commands/utility/WebCmdlet/StreamHelper.cs | 3 +++ .../commands/utility/WebCmdlet/WebRequestSession.cs | 1 + 4 files changed, 9 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 7848a61b227..3d55a02ef62 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -134,6 +134,7 @@ protected override void EndProcessing() { return; } + JsonSerializerSettings jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, @@ -144,10 +145,12 @@ protected override void EndProcessing() { jsonSettings.Converters.Add(new StringEnumConverter()); } + if (!Compress) { jsonSettings.Formatting = Formatting.Indented; } + string output = JsonConvert.SerializeObject(preprocessedObject, jsonSettings); WriteObject(output); } @@ -450,6 +453,7 @@ private object ProcessCustomObject(object o, int depth) } } } + return result; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs index 7069ef298f4..53c60384136 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -29,6 +29,7 @@ public FormObject this[string key] break; } } + return (form); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index f2537744b70..903eceb7355 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -211,6 +211,7 @@ protected override void Dispose(bool disposing) private void Initialize() { if (_isInitialized) { return; } + _isInitialized = true; try { @@ -396,6 +397,7 @@ internal static string DecodeStream(Stream stream, string characterSet, out Enco { encoding = null; } + return DecodeStream(stream, ref encoding); } @@ -411,6 +413,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) { encoding = null; } + return result; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index e794291de98..3289e1c51d2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -108,6 +108,7 @@ internal void AddCertificate(X509Certificate certificate) { Certificates = new X509CertificateCollection(); } + Certificates.Add(certificate); } } From eac7fd7aeab574fae9e94a5fbe10f13e84c935e3 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 23/81] Update Common --- .../WebCmdlet/Common/ContentHelper.Common.cs | 1 + .../Common/InvokeRestMethodCommand.Common.cs | 8 ++++++ .../Common/WebRequestPSCmdlet.Common.cs | 28 +++++++++++++++++++ .../Common/WebResponseObject.Common.cs | 1 + 4 files changed, 38 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 751ff60d872..b33ae6610dc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -91,6 +91,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { continue; } + foreach (var header in headerCollection) { // Headers may have multiple entries with different values diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index e492a614987..6b6a3700fa7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -24,6 +24,7 @@ public partial class InvokeRestMethodCommand public override WebRequestMethod Method { get { return base.Method; } + set { base.Method = value; } } @@ -37,6 +38,7 @@ public override WebRequestMethod Method public override string CustomMethod { get { return base.CustomMethod; } + set { base.CustomMethod = value; } } @@ -48,6 +50,7 @@ public override string CustomMethod public SwitchParameter FollowRelLink { get { return base._followRelLink; } + set { base._followRelLink = value; } } @@ -60,6 +63,7 @@ public SwitchParameter FollowRelLink public int MaximumFollowRelLink { get { return base._maximumFollowRelLink; } + set { base._maximumFollowRelLink = value; } } @@ -166,6 +170,7 @@ private bool TryConvertToXml(string xml, out object doc, ref Exception exRef) exRef = ex; doc = null; } + return (doc != null); } @@ -210,6 +215,7 @@ private bool TryConvertToJson(string json, out object obj, ref Exception exRef) exRef = new ArgumentException(msg, ex); obj = null; } + return converted; } @@ -276,11 +282,13 @@ public override long Length { get { return _length; } } + private long _length; public override long Position { get { return _streamBuffer.Position; } + set { _streamBuffer.Position = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 2216245d23f..6187b2ad331 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -225,8 +225,10 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet public virtual int MaximumRedirection { get { return _maximumRedirection; } + set { _maximumRedirection = value; } } + private int _maximumRedirection = -1; /// @@ -255,8 +257,10 @@ public virtual int MaximumRedirection public virtual WebRequestMethod Method { get { return _method; } + set { _method = value; } } + private WebRequestMethod _method = WebRequestMethod.Default; /// @@ -269,8 +273,10 @@ public virtual WebRequestMethod Method public virtual string CustomMethod { get { return _customMethod; } + set { _customMethod = value; } } + private string _customMethod; #endregion @@ -397,30 +403,35 @@ internal virtual void ValidateParameters() "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } + if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } + if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } + if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https")) { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } + if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, @@ -457,12 +468,14 @@ internal virtual void ValidateParameters() "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } + if ((Body != null) && (Form != null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } + if ((InFile != null) && (Form != null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, @@ -504,6 +517,7 @@ internal virtual void ValidateParameters() errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); } + _originalFilePath = InFile; InFile = providerPaths[0]; } @@ -592,6 +606,7 @@ internal virtual void PrepareSession() CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound); throw ex; } + foreach (X509Certificate2 tbCert in tbCollection) { X509Certificate certificate = (X509Certificate)tbCert; @@ -627,6 +642,7 @@ internal virtual void PrepareSession() // UseDefaultCredentials will overwrite the supplied credentials. webProxy.UseDefaultCredentials = true; } + WebSession.Proxy = webProxy; } @@ -705,6 +721,7 @@ private Uri PrepareUri(Uri uri) { uriBuilder.Query = FormatDictionary(bodyAsDictionary); } + uri = uriBuilder.Uri; // set body to null to prevent later FillRequestStream Body = null; @@ -721,6 +738,7 @@ private Uri CheckProtocol(Uri uri) { uri = new Uri("http://" + uri.OriginalString); } + return (uri); } @@ -755,6 +773,7 @@ private string FormatDictionary(IDictionary content) bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue); } + return bodyBuilder.ToString(); } @@ -1034,6 +1053,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) // set the method if the parameter was provided httpMethod = new HttpMethod(CustomMethod.ToString().ToUpperInvariant()); } + break; } @@ -1163,6 +1183,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) // AddMultipartContent will handle PSObject unwrapping, Object type determination and enumerateing top level IEnumerables. AddMultipartContent(fieldName: formEntry.Key, fieldValue: formEntry.Value, formData: formData, enumerate: true); } + SetRequestContent(request, formData); } // coerce body into a usable form @@ -1303,6 +1324,7 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { if (client == null) { throw new ArgumentNullException("client"); } + if (request == null) { throw new ArgumentNullException("request"); } // Add 1 to account for the first request. @@ -1522,10 +1544,12 @@ protected override void ProcessRecord() reader.Dispose(); } } + if (!String.IsNullOrEmpty(detailMsg)) { er.ErrorDetails = new ErrorDetails(detailMsg); } + ThrowTerminatingError(er); } @@ -1533,6 +1557,7 @@ protected override void ProcessRecord() { ParseLinkHeader(response, uri); } + ProcessResponse(response); UpdateSession(response); @@ -1559,6 +1584,7 @@ protected override void ProcessRecord() { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } + ThrowTerminatingError(er); } @@ -1568,6 +1594,7 @@ protected override void ProcessRecord() { return; } + uri = new Uri(_relationLink["next"]); followedRelLink++; } @@ -1751,6 +1778,7 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon { throw new ArgumentNullException("request"); } + if (multipartContent == null) { throw new ArgumentNullException("multipartContent"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 179ba3820cd..c774d1178cf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -201,6 +201,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) { contentLength = StreamHelper.DefaultReadBuffer; } + int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, null); } From 36dfd2ae5fda4e206d22a1c83b7046522a09a154 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 24/81] Update CoreCLR --- .../commands/utility/WebCmdlet/CoreCLR/WebProxy.cs | 2 ++ .../WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs | 1 + 2 files changed, 3 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index a3fbb5b7049..4a3db09fbde 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -24,6 +24,7 @@ internal WebProxy(Uri address) public ICredentials Credentials { get { return _credentials; } + set { _credentials = value; } } @@ -38,6 +39,7 @@ internal bool UseDefaultCredentials { return _credentials == CredentialCache.DefaultCredentials; } + set { _credentials = value ? CredentialCache.DefaultCredentials : null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs index 0e7689788eb..bb1f9a1f480 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs @@ -21,6 +21,7 @@ internal static WebResponseObject GetResponseObject(HttpResponseMessage response { output = new WebResponseObject(response, responseStream); } + return (output); } } From 252a4ff34a26d1d5575aa915c976c932e13aa3fe Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 25/81] Update common --- .../FormatAndOutput/common/GetFormatDataCommand.cs | 5 +++++ .../FormatAndOutput/common/WriteFormatDataCommand.cs | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index d46c9e20d27..3a511e30bd9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -35,6 +35,7 @@ public String[] TypeName { return _typename; } + set { _typename = value; @@ -166,6 +167,7 @@ protected override void ProcessRecord() viewList = new List(); typedefs.Add(consolidatedTypeName, viewList); } + viewList.Add(formatdef); }// foreach(ViewDefinition... @@ -189,6 +191,7 @@ protected override void ProcessRecord() { etd.TypeNames.Add(typeNames[i]); } + WriteObject(etd); } } @@ -219,6 +222,7 @@ private static ConsolidatedString CreateConsolidatedTypeName(ViewDefinition defi consolidatedTypeName.Add(item.name); } } + return consolidatedTypeName; } @@ -234,6 +238,7 @@ private bool ShouldGenerateView(ConsolidatedString consolidatedTypeName) } } } + return false; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index 8c99ede3a42..89c44c87016 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -27,6 +27,7 @@ public ExtendedTypeDefinition[] InputObject { return _typeDefinition; } + set { _typeDefinition = value; @@ -46,6 +47,7 @@ public String Path { return _filepath; } + set { _filepath = value; @@ -63,12 +65,14 @@ public String LiteralPath { return _filepath; } + set { _filepath = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; private List _typeDefinitions = new List(); @@ -85,6 +89,7 @@ public SwitchParameter Force { return _force; } + set { _force = value; @@ -102,11 +107,13 @@ public SwitchParameter NoClobber { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// @@ -119,11 +126,13 @@ public SwitchParameter IncludeScriptBlock { return _includescriptblock; } + set { _includescriptblock = value; } } + private bool _includescriptblock; /// From eb1c189a377e8f0ce028c5591298bc9aa078634f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 26/81] Update format-object --- .../utility/FormatAndOutput/format-object/format-object.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs index 7c9448c9ec8..99095c1fee5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs @@ -32,6 +32,7 @@ public FormatCustomCommand() public object[] Property { get { return _props; } + set { _props = value; } } @@ -45,6 +46,7 @@ public object[] Property public int Depth { get { return _depth; } + set { _depth = value; } } @@ -70,6 +72,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { ReportCannotSpecifyViewAndProperty(); } + parameters.viewName = this.View; } From be5470e397ab9ff4206fa40d2c4a178c2c83c738 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 27/81] Update format-wide --- .../utility/FormatAndOutput/format-wide/Format-Wide.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index 991e04dd4d9..e50331c8eec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -34,6 +34,7 @@ public FormatWideCommand() public object Property { get { return _prop; } + set { _prop = value; } } @@ -52,8 +53,10 @@ public SwitchParameter AutoSize return _autosize.Value; return false; } + set { _autosize = value; } } + private bool? _autosize = null; /// @@ -70,8 +73,10 @@ public int Column return _column.Value; return -1; } + set { _column = value; } } + private int? _column = null; #endregion @@ -94,6 +99,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { ReportCannotSpecifyViewAndProperty(); } + parameters.viewName = this.View; } @@ -134,6 +140,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { wideSpecific.columns = _column.Value; } + return parameters; } } From 7e6d86e3d6dcda6ba722f51aed01d50cb4bf47f2 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:40 -0800 Subject: [PATCH 28/81] Update out-file --- .../utility/FormatAndOutput/out-file/Out-File.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index 5f655f7b61f..57fc1a879b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -43,6 +43,7 @@ public OutFileCommand() public string FilePath { get { return _fileName; } + set { _fileName = value; } } @@ -59,12 +60,14 @@ public string LiteralPath { return _fileName; } + set { _fileName = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -83,8 +86,10 @@ public string LiteralPath public SwitchParameter Append { get { return _append; } + set { _append = value; } } + private bool _append; /// @@ -94,8 +99,10 @@ public SwitchParameter Append public SwitchParameter Force { get { return _force; } + set { _force = value; } } + private bool _force; /// @@ -106,8 +113,10 @@ public SwitchParameter Force public SwitchParameter NoClobber { get { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// @@ -118,6 +127,7 @@ public SwitchParameter NoClobber public int Width { get { return (_width != null) ? _width.Value : 0; } + set { _width = value; } } @@ -133,6 +143,7 @@ public SwitchParameter NoNewline { return _suppressNewline; } + set { _suppressNewline = value; From 1396ccc308aff68ed51b2dde376a905d94dedd70 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:41 -0800 Subject: [PATCH 29/81] Update out-printer --- .../commands/utility/FormatAndOutput/out-printer/out-printer.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs index ca6e3bafb40..df7b63cfde8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs @@ -29,6 +29,7 @@ public OutPrinterCommand() public string Name { get { return _printerName; } + set { _printerName = value; } } From 4d38fe4604fe3303b1a7a3540bdcd6997ac7cdd1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:41 -0800 Subject: [PATCH 30/81] Update out-string --- .../commands/utility/FormatAndOutput/out-string/out-string.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs index 4be5f363c65..91cae22ca6b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs @@ -26,6 +26,7 @@ public class OutStringCommand : FrontEndCommandBase public SwitchParameter Stream { get { return _stream; } + set { _stream = value; } } @@ -39,6 +40,7 @@ public SwitchParameter Stream public int Width { get { return (_width != null) ? _width.Value : 0; } + set { _width = value; } } @@ -51,6 +53,7 @@ public int Width public SwitchParameter NoNewline { get { return _noNewLine; } + set { _noNewLine = value; } } From 172b9d44afbec9f7a9ef30ff5abe58a5fe1458d6 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:41 -0800 Subject: [PATCH 31/81] Update OutGridView --- .../utility/FormatAndOutput/OutGridView/ColumnInfo.cs | 1 + .../utility/FormatAndOutput/OutGridView/HeaderInfo.cs | 1 + .../FormatAndOutput/OutGridView/OriginalColumnInfo.cs | 1 + .../FormatAndOutput/OutGridView/OutGridViewCommand.cs | 5 +++++ .../FormatAndOutput/OutGridView/OutWindowProxy.cs | 2 ++ .../FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs | 1 + .../utility/FormatAndOutput/OutGridView/TableView.cs | 9 +++++++++ 7 files changed, 20 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index 18e1ee4f280..12a5eef8ff2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -37,6 +37,7 @@ internal Type GetValueType(PSObject liveObject, out object columnValue) { return columnValue.GetType(); } + return typeof(string); // Use the String type as default. } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index a6b86061673..5c01909c819 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -54,6 +54,7 @@ internal PSObject CreateStalePSObject(PSObject liveObject) staleObject.Properties.Add(new PSNoteProperty(column.StaleObjectPropertyName(), column.GetValue(liveObject))); } + return staleObject; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index a02cf72f71a..14be5c48500 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -65,6 +65,7 @@ internal override Object GetValue(PSObject liveObject) { // ignore } + return null; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index 6c55d6a81dd..c7959fee0b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -97,6 +97,7 @@ public OutGridViewCommand() public SwitchParameter PassThru { set { this.OutputMode = value.IsPresent ? OutputModeOption.Multiple : OutputModeOption.None; } + get { return OutputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); } } @@ -226,6 +227,7 @@ internal string ConvertToString(PSObject liveObject) liveObject) ); } + return smartToString; } @@ -249,6 +251,7 @@ private void ProcessObject(PSObject input) // Stop the pipeline cleanly. pipeline.StopAsync(); } + return; } @@ -313,6 +316,7 @@ internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewComman { return new ScalarTypeHeader(parentCmd, input); } + return new NonscalarTypeHeader(parentCmd, input); } @@ -381,6 +385,7 @@ internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : bas { break; } + _appliesTo.AddAppliesToType(typeName); index++; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 7c4112a563f..c0f3021c0ec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -60,10 +60,12 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t { throw new ArgumentNullException("propertyNames"); } + if (displayNames == null) { throw new ArgumentNullException("displayNames"); } + if (types == null) { throw new ArgumentNullException("types"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index e8204464c95..adb2186b5c1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -24,6 +24,7 @@ internal override Object GetValue(PSObject liveObject) { return ColumnInfo.LimitString(baseObject); } + return null; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index a803a2f8eaa..72edb5f2145 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -76,6 +76,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } + if (fpt.expression.isScriptBlock) { PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); @@ -107,10 +108,12 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } } } + if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } + col++; } } @@ -165,14 +168,17 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parent if (key != AutomationNull.Value) propertyName = (string)key; } + if (propertyName == null) { propertyName = association.ResolvedExpression.ToString(); } + ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); headerInfo.AddColumn(columnInfo); } + return headerInfo; } @@ -225,6 +231,7 @@ private List GetActiveTableRowDefinition(TableControlBod break; } } + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; @@ -245,6 +252,7 @@ private List GetActiveTableRowDefinition(TableControlBod break; } } + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; @@ -274,6 +282,7 @@ private List GetActiveTableRowDefinition(TableControlBod // Use the override activeRowItemDefinitionList.Add(rowItem); } + col++; } From adb671cd1328e47476ba0c5df9050d2cc9b9907c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:42 -0800 Subject: [PATCH 32/81] Update LocalAccounts --- .../LocalAccounts/Sam.cs | 11 +++++++++++ .../LocalAccounts/StringUtil.cs | 1 + 2 files changed, 12 insertions(+) diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index 6afc175ae84..dbc6ea84fd5 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -1277,6 +1277,7 @@ private LocalUser CreateUser(LocalUser userInfo, System.Security.SecureString pa { SamApi.SamDeleteUser(userHandle); } + throw; } finally @@ -1374,6 +1375,7 @@ private void RenameGroup(SecurityIdentifier sid, string newName) Marshal.DestroyStructure(buffer); Marshal.FreeHGlobal(buffer); } + if (aliasHandle != IntPtr.Zero) status = SamApi.SamCloseHandle(aliasHandle); } @@ -1763,6 +1765,7 @@ private void RenameUser(SecurityIdentifier sid, string newName) Marshal.DestroyStructure(buffer); Marshal.FreeHGlobal(buffer); } + if (userHandle != IntPtr.Zero) status = SamApi.SamCloseHandle(userHandle); } @@ -1998,6 +2001,7 @@ private void UpdateGroup(LocalGroup group, LocalGroup changed) Marshal.DestroyStructure(buffer); Marshal.FreeHGlobal(buffer); } + if (aliasHandle != IntPtr.Zero) status = SamApi.SamCloseHandle(aliasHandle); } @@ -2200,11 +2204,13 @@ private void SetUserData(IntPtr userHandle, ? sourceUser.AccountExpires.Value.ToFileTime() : 0L; } + if (setFlags.HasFlag(UserProperties.Description)) { which |= SamApi.USER_ALL_ADMINCOMMENT; info.AdminComment = new UNICODE_STRING(sourceUser.Description); } + if (setFlags.HasFlag(UserProperties.Enabled)) { which |= SamApi.USER_ALL_USERACCOUNTCONTROL; @@ -2213,6 +2219,7 @@ private void SetUserData(IntPtr userHandle, else uac |= SamApi.USER_ACCOUNT_DISABLED; } + if (setFlags.HasFlag(UserProperties.FullName)) { which |= SamApi.USER_ALL_FULLNAME; @@ -2365,6 +2372,7 @@ private RawAcl GetSamDacl(IntPtr objectHandle) if (IntPtr.Zero != securityObject) status = SamApi.SamFreeMemory(securityObject); } + return rv; } @@ -2657,6 +2665,7 @@ private SecurityIdentifier RidToSid(IntPtr domainHandle, uint rid) if (IntPtr.Zero != sidBytes) status = SamApi.SamFreeMemory(sidBytes); } + return sid; } @@ -2778,6 +2787,7 @@ private AccountInfo LookupAccountInfo(string accountName) { accountName = accountName.Substring(index + 1); } + return new AccountInfo { AccountName = accountName, @@ -3196,6 +3206,7 @@ private OperatingSystem GetOperatingSystem() Version ver = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor); localOs = new OperatingSystem(ver, osviex.CSDVersion); } + return localOs; #else return Environment.OSVersion; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs index 24943c563c3..6e3fce7e378 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs @@ -38,6 +38,7 @@ internal static string Format(string fmt, uint p0) { return string.Format(CultureInfo.CurrentCulture, fmt, p0); } + internal static string Format(string fmt, int p0) { return string.Format(CultureInfo.CurrentCulture, fmt, p0); From 6bfbb714b600a7d8a85af35de15fc1f47b0f0382 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:42 -0800 Subject: [PATCH 33/81] Update Commands --- .../Commands/AddLocalGroupMemberCommand.cs | 9 ++++++++ .../Commands/DisableLocalUserCommand.cs | 6 ++++++ .../Commands/EnableLocalUserCommand.cs | 6 ++++++ .../Commands/GetLocalGroupCommand.cs | 4 ++++ .../Commands/GetLocalGroupMemberCommand.cs | 8 +++++++ .../Commands/GetLocalUserCommand.cs | 3 +++ .../Commands/NewLocalGroupCommand.cs | 4 ++++ .../Commands/NewLocalUserCommand.cs | 21 +++++++++++++++++++ .../Commands/RemoveLocalGroupCommand.cs | 6 ++++++ .../Commands/RemoveLocalGroupMemberCommand.cs | 8 +++++++ .../Commands/RemoveLocalUserCommand.cs | 6 ++++++ .../Commands/RenameLocalGroupCommand.cs | 8 +++++++ .../Commands/RenameLocalUserCommand.cs | 8 +++++++ .../Commands/SetLocalGroupCommand.cs | 8 +++++++ .../Commands/SetLocalUserCommand.cs | 21 +++++++++++++++++++ 15 files changed, 126 insertions(+) diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs index 93daf95694c..bb113106509 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs @@ -42,8 +42,10 @@ public class AddLocalGroupMemberCommand : PSCmdlet public Microsoft.PowerShell.Commands.LocalGroup Group { get { return this.group;} + set { this.group = value; } } + private Microsoft.PowerShell.Commands.LocalGroup group; /// @@ -61,8 +63,10 @@ public Microsoft.PowerShell.Commands.LocalGroup Group public Microsoft.PowerShell.Commands.LocalPrincipal[] Member { get { return this.member;} + set { this.member = value; } } + private Microsoft.PowerShell.Commands.LocalPrincipal[] member; /// @@ -76,8 +80,10 @@ public Microsoft.PowerShell.Commands.LocalPrincipal[] Member public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -91,8 +97,10 @@ public string Name public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties @@ -202,6 +210,7 @@ private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) } } } + if (CheckShouldProcess(principal, groupId)) return principal; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs index eb47f20ec8a..64d05a7e478 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs @@ -50,8 +50,10 @@ public class DisableLocalUserCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalUser[] InputObject { get { return this.inputobject; } + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; /// @@ -69,8 +71,10 @@ public Microsoft.PowerShell.Commands.LocalUser[] InputObject public string[] Name { get { return this.name; } + set { this.name = value; } } + private string[] name; /// @@ -88,8 +92,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs index f872439c55c..2e0c1a9804b 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs @@ -50,8 +50,10 @@ public class EnableLocalUserCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalUser[] InputObject { get { return this.inputobject; } + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; /// @@ -69,8 +71,10 @@ public Microsoft.PowerShell.Commands.LocalUser[] InputObject public string[] Name { get { return this.name; } + set { this.name = value; } } + private string[] name; /// @@ -88,8 +92,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs index 69c1416a787..d7b0f69df63 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs @@ -41,8 +41,10 @@ public class GetLocalGroupCommand : Cmdlet public string[] Name { get { return this.name; } + set { this.name = value; } } + private string[] name; /// @@ -58,8 +60,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs index a9f28b792c3..306cebba950 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs @@ -40,8 +40,10 @@ public class GetLocalGroupMemberCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalGroup Group { get { return this.group;} + set { this.group = value; } } + private Microsoft.PowerShell.Commands.LocalGroup group; /// @@ -55,8 +57,10 @@ public Microsoft.PowerShell.Commands.LocalGroup Group public string Member { get { return this.member;} + set { this.member = value; } } + private string member; /// @@ -72,8 +76,10 @@ public string Member public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -89,8 +95,10 @@ public string Name public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs index d5a33ac357e..8b9ca15c1c1 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs @@ -46,6 +46,7 @@ public string[] Name set { this.name = value; } } + private string[] name; /// @@ -61,8 +62,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid; } + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs index d7283d54308..180857e7e20 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs @@ -37,8 +37,10 @@ public class NewLocalGroupCommand : Cmdlet public string Description { get { return this.description;} + set { this.description = value; } } + private string description; /// @@ -54,8 +56,10 @@ public string Description public string Name { get { return this.name;} + set { this.name = value; } } + private string name; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs index 566a3039c0c..de871df89b6 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs @@ -50,8 +50,10 @@ public class NewLocalUserCommand : PSCmdlet public System.DateTime AccountExpires { get { return this.accountexpires;} + set { this.accountexpires = value; } } + private System.DateTime accountexpires; // This parameter added by hand (copied from SetLocalUserCommand), not by Cmdlet Designer @@ -63,8 +65,10 @@ public System.DateTime AccountExpires public System.Management.Automation.SwitchParameter AccountNeverExpires { get { return this.accountneverexpires;} + set { this.accountneverexpires = value; } } + private System.Management.Automation.SwitchParameter accountneverexpires; /// @@ -76,8 +80,10 @@ public System.Management.Automation.SwitchParameter AccountNeverExpires public string Description { get { return this.description;} + set { this.description = value; } } + private string description; /// @@ -88,8 +94,10 @@ public string Description public System.Management.Automation.SwitchParameter Disabled { get { return this.disabled;} + set { this.disabled = value; } } + private System.Management.Automation.SwitchParameter disabled; /// @@ -102,8 +110,10 @@ public System.Management.Automation.SwitchParameter Disabled public string FullName { get { return this.fullname;} + set { this.fullname = value; } } + private string fullname; /// @@ -120,8 +130,10 @@ public string FullName public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -136,8 +148,10 @@ public string Name public System.Security.SecureString Password { get { return this.password;} + set { this.password = value; } } + private System.Security.SecureString password; /// @@ -150,8 +164,10 @@ public System.Security.SecureString Password public System.Management.Automation.SwitchParameter NoPassword { get { return this.nopassword; } + set { this.nopassword = value; } } + private System.Management.Automation.SwitchParameter nopassword; /// @@ -163,8 +179,10 @@ public System.Management.Automation.SwitchParameter NoPassword public System.Management.Automation.SwitchParameter PasswordNeverExpires { get { return this.passwordneverexpires; } + set { this.passwordneverexpires = value; } } + private System.Management.Automation.SwitchParameter passwordneverexpires; /// @@ -176,8 +194,10 @@ public System.Management.Automation.SwitchParameter PasswordNeverExpires public System.Management.Automation.SwitchParameter UserMayNotChangePassword { get { return this.usermaynotchangepassword;} + set { this.usermaynotchangepassword = value; } } + private System.Management.Automation.SwitchParameter usermaynotchangepassword; #endregion Parameter Properties @@ -192,6 +212,7 @@ protected override void BeginProcessing() InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); ThrowTerminatingError(ex.MakeErrorRecord()); } + sam = new Sam(); } diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs index cccc31e7915..eaf4b76785a 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs @@ -43,8 +43,10 @@ public class RemoveLocalGroupCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalGroup[] InputObject { get { return this.inputobject; } + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalGroup[] inputobject; /// @@ -62,8 +64,10 @@ public Microsoft.PowerShell.Commands.LocalGroup[] InputObject public string[] Name { get { return this.name; } + set { this.name = value; } } + private string[] name; /// @@ -81,8 +85,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid; } + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs index d18d61f8698..a6cab2dc114 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs @@ -42,8 +42,10 @@ public class RemoveLocalGroupMemberCommand : PSCmdlet public Microsoft.PowerShell.Commands.LocalGroup Group { get { return this.group;} + set { this.group = value; } } + private Microsoft.PowerShell.Commands.LocalGroup group; /// @@ -61,8 +63,10 @@ public Microsoft.PowerShell.Commands.LocalGroup Group public Microsoft.PowerShell.Commands.LocalPrincipal[] Member { get { return this.member;} + set { this.member = value; } } + private Microsoft.PowerShell.Commands.LocalPrincipal[] member; /// @@ -76,8 +80,10 @@ public Microsoft.PowerShell.Commands.LocalPrincipal[] Member public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -91,8 +97,10 @@ public string Name public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs index a5e36fcc81f..c8edffce501 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs @@ -44,8 +44,10 @@ public class RemoveLocalUserCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalUser[] InputObject { get { return this.inputobject;} + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalUser[] inputobject; /// @@ -63,8 +65,10 @@ public Microsoft.PowerShell.Commands.LocalUser[] InputObject public string[] Name { get { return this.name; } + set { this.name = value; } } + private string[] name; /// @@ -82,8 +86,10 @@ public string[] Name public System.Security.Principal.SecurityIdentifier[] SID { get { return this.sid; } + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier[] sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs index a1e458e6d10..d0b9e04b64f 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs @@ -42,8 +42,10 @@ public class RenameLocalGroupCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalGroup InputObject { get { return this.inputobject;} + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalGroup inputobject; /// @@ -60,8 +62,10 @@ public Microsoft.PowerShell.Commands.LocalGroup InputObject public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -75,8 +79,10 @@ public string Name public string NewName { get { return this.newname;} + set { this.newname = value; } } + private string newname; /// @@ -92,8 +98,10 @@ public string NewName public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs index c731820caa6..45bc21bb547 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs @@ -42,8 +42,10 @@ public class RenameLocalUserCommand : Cmdlet public Microsoft.PowerShell.Commands.LocalUser InputObject { get { return this.inputobject;} + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalUser inputobject; /// @@ -60,8 +62,10 @@ public Microsoft.PowerShell.Commands.LocalUser InputObject public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -75,8 +79,10 @@ public string Name public string NewName { get { return this.newname;} + set { this.newname = value; } } + private string newname; /// @@ -92,8 +98,10 @@ public string NewName public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs index b22806aad9d..9ccd3273e57 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs @@ -37,8 +37,10 @@ public class SetLocalGroupCommand : Cmdlet public string Description { get { return this.description;} + set { this.description = value; } } + private string description; /// @@ -55,8 +57,10 @@ public string Description public Microsoft.PowerShell.Commands.LocalGroup InputObject { get { return this.inputobject;} + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalGroup inputobject; /// @@ -73,8 +77,10 @@ public Microsoft.PowerShell.Commands.LocalGroup InputObject public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -90,8 +96,10 @@ public string Name public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs index 2ae6c921658..599bd53d978 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs @@ -54,8 +54,10 @@ public class SetLocalUserCommand : PSCmdlet public System.DateTime AccountExpires { get { return this.accountexpires;} + set { this.accountexpires = value; } } + private System.DateTime accountexpires; /// @@ -66,8 +68,10 @@ public System.DateTime AccountExpires public System.Management.Automation.SwitchParameter AccountNeverExpires { get { return this.accountneverexpires;} + set { this.accountneverexpires = value; } } + private System.Management.Automation.SwitchParameter accountneverexpires; /// @@ -79,8 +83,10 @@ public System.Management.Automation.SwitchParameter AccountNeverExpires public string Description { get { return this.description;} + set { this.description = value; } } + private string description; /// @@ -93,8 +99,10 @@ public string Description public string FullName { get { return this.fullname;} + set { this.fullname = value; } } + private string fullname; /// /// The following is the definition of the input parameter "InputObject". @@ -110,8 +118,10 @@ public string FullName public Microsoft.PowerShell.Commands.LocalUser InputObject { get { return this.inputobject;} + set { this.inputobject = value; } } + private Microsoft.PowerShell.Commands.LocalUser inputobject; /// @@ -127,8 +137,10 @@ public Microsoft.PowerShell.Commands.LocalUser InputObject public string Name { get { return this.name;} + set { this.name = value; } } + private string name; /// @@ -140,8 +152,10 @@ public string Name public System.Security.SecureString Password { get { return this.password;} + set { this.password = value; } } + private System.Security.SecureString password; /// @@ -152,8 +166,10 @@ public System.Security.SecureString Password public bool PasswordNeverExpires { get { return this.passwordneverexpires; } + set { this.passwordneverexpires = value; } } + private bool passwordneverexpires; /// @@ -169,8 +185,10 @@ public bool PasswordNeverExpires public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} + set { this.sid = value; } } + private System.Security.Principal.SecurityIdentifier sid; /// @@ -182,8 +200,10 @@ public System.Security.Principal.SecurityIdentifier SID public bool UserMayChangePassword { get { return this.usermaychangepassword;} + set { this.usermaychangepassword = value; } } + private bool usermaychangepassword; #endregion Parameter Properties @@ -198,6 +218,7 @@ protected override void BeginProcessing() InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); ThrowTerminatingError(ex.MakeErrorRecord()); } + sam = new Sam(); } From b2764e1b189c53fdec2b048de6d8437e3114f445 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:43 -0800 Subject: [PATCH 34/81] Update security --- .../security/AclCommands.cs | 21 +++++++++++++++ .../security/CatalogCommands.cs | 9 +++++++ .../security/CertificateCommands.cs | 2 ++ .../security/CertificateProvider.cs | 27 +++++++++++++++++++ .../security/CmsCommands.cs | 10 +++++++ .../security/CredentialCommands.cs | 6 +++++ .../security/ExecutionPolicyCommands.cs | 10 +++++++ .../security/SecureStringCommands.cs | 4 +++ .../security/SignatureCommands.cs | 14 ++++++++++ 9 files changed, 103 insertions(+) diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 79c63d4e427..1a044720a8e 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -306,6 +306,7 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); dacl = dos.GetAccessRules(true, true, typeof(NTAccount)); } + return dacl; } @@ -343,6 +344,7 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); sacl = dos.GetAuditRules(true, true, typeof(NTAccount)); } + return sacl; } @@ -379,10 +381,12 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) { throw new Win32Exception((int)rs); } + if (pSacl == IntPtr.Zero) { return null; } + NativeMethods.ACL sacl = new NativeMethods.ACL(); sacl = Marshal.PtrToStructure(pSacl); if (sacl.AceCount == 0) @@ -403,8 +407,10 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) { break; } + pAce += ace.AceSize; } + IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) - Marshal.SizeOf(new uint()); bool ret = NativeMethods.IsValidSid(pSid); @@ -441,6 +447,7 @@ public static string GetCentralAccessPolicyName(PSObject instance) { return null; // file does not have the scope ace } + int capIdSize = capId.BinaryLength; byte[] capIdArray = new byte[capIdSize]; capId.GetBinaryForm(capIdArray, 0); @@ -463,6 +470,7 @@ public static string GetCentralAccessPolicyName(PSObject instance) { throw new Win32Exception((int)rs); } + if (capCount == 0 || caps == IntPtr.Zero) { return null; @@ -512,6 +520,7 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) { throw new Win32Exception((int)rs); } + Dbg.Diagnostics.Assert(capCount < 0xFFFF, "Too many central access policies"); if (capCount == 0 || caps == IntPtr.Zero) @@ -543,11 +552,13 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) { throw new Win32Exception(Marshal.GetLastWin32Error()); } + SecurityIdentifier sid = new SecurityIdentifier(pCapId); policies[capIdx] += " (" + sid.ToString() + ")"; capPtr += Marshal.SizeOf(cap); } + return policies; } finally @@ -686,6 +697,7 @@ public string[] LiteralPath _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -705,6 +717,7 @@ public SwitchParameter Audit _audit = value; } } + private SwitchParameter _audit; #if CORECLR @@ -735,6 +748,7 @@ public SwitchParameter AllCentralAccessPolicies allCentralAccessPolicies = value; } } + private SwitchParameter allCentralAccessPolicies; #endif @@ -950,6 +964,7 @@ public string[] LiteralPath _isLiteralPath = true; } } + private bool _isLiteralPath = false; private object _securityDescriptor; @@ -1126,6 +1141,7 @@ private IntPtr GetSaclWithCapId(string capStr) { throw new Win32Exception((int)rs); } + Dbg.Diagnostics.Assert(capCount < 0xFFFF, "Too many central access policies"); if (capCount == 0 || caps == IntPtr.Zero) @@ -1150,9 +1166,11 @@ private IntPtr GetSaclWithCapId(string capStr) pCapId = cap.CAPID; break; } + capPtr += Marshal.SizeOf(cap); } } + if (pCapId == IntPtr.Zero) { Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier); @@ -1163,11 +1181,13 @@ private IntPtr GetSaclWithCapId(string capStr) AclObject)); return IntPtr.Zero; } + ret = NativeMethods.IsValidSid(pCapId); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } + uint sidSize = NativeMethods.GetLengthSid(pCapId); // Calculate the size of the SACL with one CAPID ACE, align to DWORD. @@ -1214,6 +1234,7 @@ private IntPtr GetSaclWithCapId(string capStr) Marshal.FreeHGlobal(pSacl); pSacl = IntPtr.Zero; } + rs = NativeMethods.LsaFreeMemory(caps); Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index 4864346883f..970cba32357 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -30,11 +30,13 @@ public string CatalogFilePath { return catalogFilePath; } + set { catalogFilePath = value; } } + private string catalogFilePath; /// @@ -47,11 +49,13 @@ public string[] Path { return path; } + set { path = value; } } + private string[] path; // // name of this command @@ -152,6 +156,7 @@ public int CatalogVersion { return catalogVersion; } + set { catalogVersion = value; @@ -226,8 +231,10 @@ public TestFileCatalogCommand() : base("Test-FileCatalog") { } public SwitchParameter Detailed { get { return detailed; } + set { detailed = value; } } + private bool detailed = false; /// @@ -240,6 +247,7 @@ public string[] FilesToSkip { return filesToSkip; } + set { filesToSkip = value; @@ -250,6 +258,7 @@ public string[] FilesToSkip } } } + private string[] filesToSkip = null; internal WildcardPattern[] excludedPatterns = null; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index d748526894f..4e9f5c17d4d 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -38,6 +38,7 @@ public string[] FilePath _path = value; } } + private string[] _path; /// @@ -60,6 +61,7 @@ public string[] LiteralPath _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 8f7df3cbb58..0dc198003ee 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -48,6 +48,7 @@ internal sealed class CertificateProviderCodeSigningDynamicParameters public SwitchParameter CodeSigningCert { get { return _codeSigningCert; } + set { _codeSigningCert = value; } } @@ -113,6 +114,7 @@ public bool Equals(DnsNameRepresentation dnsName) { match = true; } + return match; } @@ -213,12 +215,14 @@ protected override bool ReleaseHandle() fResult = Security.NativeMethods.CertCloseStore(handle, 0); handle = IntPtr.Zero; } + return fResult; } public IntPtr Handle { get { return handle; } + set { handle = value; } } } @@ -245,6 +249,7 @@ public void Open(bool includeArchivedCerts) { _storeHandle = null; // release the old handle } + if (_storeHandle == null) { _valid = false; @@ -325,6 +330,7 @@ public IntPtr GetNextCert(IntPtr certContext) throw Marshal.GetExceptionForHR( Security.NativeMethods.CRYPT_E_NOT_FOUND); } + if (Valid) { certContext = Security.NativeMethods.CertEnumCertificatesInStore( @@ -335,6 +341,7 @@ public IntPtr GetNextCert(IntPtr certContext) { certContext = IntPtr.Zero; } + return certContext; } @@ -347,6 +354,7 @@ public IntPtr GetCertByName(string Name) throw Marshal.GetExceptionForHR( Security.NativeMethods.CRYPT_E_NOT_FOUND); } + if (Valid) { if (DownLevelHelper.HashLookupSupported()) @@ -375,6 +383,7 @@ public IntPtr GetCertByName(string Name) { break; } + X509Certificate2 cert = new X509Certificate2(certContext); if (String.Equals( cert.Thumbprint, @@ -386,6 +395,7 @@ public IntPtr GetCertByName(string Name) } } } + return certContext; } @@ -567,6 +577,7 @@ private static Regex CertPathRegex s_certPathRegex = new Regex(certPathPattern, options); } } + return s_certPathRegex; } } @@ -903,6 +914,7 @@ protected override void NewItem( string errorId = "CannotCreateUserStore"; ThrowInvalidOperation(errorId, message); } + Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | @@ -1019,6 +1031,7 @@ protected override bool HasChildItems(string path) } } } + return result; } @@ -1654,6 +1667,7 @@ private void DoDeleteKey(IntPtr pProvInfo) { ThrowErrorRemoting(stat); } + hCNGKey = IntPtr.Zero; } finally @@ -1993,6 +2007,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) { ThrowItemNotFound(path, CertificateProviderItem.StoreLocation); } + break; case 2: @@ -2051,6 +2066,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) { item = new X509Certificate2(certContext); } + store.FreeCert(certContext); break; @@ -2297,6 +2313,7 @@ private void GetChildItemsOrNames( { WriteItemObject(thingToReturn, l.LocationName, true); } + childPath = l.LocationName; if (recurse) { @@ -2398,8 +2415,10 @@ private void GetCertificatesOrNames(string path, PSObject myPsObj = new PSObject(cert); thingToReturn = (object)myPsObj; } + WriteItemObject(thingToReturn, certPath, false); } + certContext = store.GetNextCert(certContext); } } @@ -2469,6 +2488,7 @@ private X509NativeStore GetStore(string storePath, { ThrowItemNotFound(storePath, CertificateProviderItem.Store); } + if (s_storeCache != null) { if (s_storeCache.Location != storeLocation || @@ -2598,6 +2618,7 @@ private CertificateFilterInfo GetFilter() } } } + return filter; } @@ -2609,6 +2630,7 @@ private bool IncludeArchivedCerts() { includeArchivedCerts = true; } + return includeArchivedCerts; } @@ -2635,6 +2657,7 @@ private static bool MatchesFilter(X509Certificate2 cert, { return true; } + break; case CertificatePurpose.DocumentEncryption: @@ -2642,6 +2665,7 @@ private static bool MatchesFilter(X509Certificate2 cert, { return true; } + break; default: @@ -2825,6 +2849,7 @@ public StoreLocation Location _location = value; } } + private StoreLocation _location = StoreLocation.CurrentUser; /// @@ -2908,6 +2933,7 @@ public bool Equals(EnhancedKeyUsageRepresentation keyUsage) { match = true; } + return match; } @@ -3258,6 +3284,7 @@ internal static bool IsWin8AndAbove() s_isWin8Set = true; } + return s_isWin8; } diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 221f98d1c59..6196a29e30f 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -44,6 +44,7 @@ public PSObject Content get; set; } + private PSDataCollection _inputObjects = new PSDataCollection(); /// @@ -65,6 +66,7 @@ public string LiteralPath get; set; } + private string _resolvedPath = null; /// @@ -76,6 +78,7 @@ public string OutFile get; set; } + private string _resolvedOutFile = null; /// @@ -204,6 +207,7 @@ public string Content get; set; } + private StringBuilder _contentBuffer = new StringBuilder(); /// @@ -225,6 +229,7 @@ public string LiteralPath get; set; } + private string _resolvedPath = null; /// @@ -316,6 +321,7 @@ protected override void EndProcessing() { recipients.Add(recipient.RecipientIdentifier.Value); } + result.Properties.Add( new PSNoteProperty("Recipients", recipients)); result.Properties.Add( @@ -346,6 +352,7 @@ public string Content get; set; } + private StringBuilder _contentBuffer = new StringBuilder(); /// @@ -378,6 +385,7 @@ public string LiteralPath get; set; } + private string _resolvedPath = null; /// @@ -524,6 +532,7 @@ private string Decrypt(string actualContent) { preContext = actualContent.Substring(0, startIndex); } + if (endIndex > -1) { postContext = actualContent.Substring(endIndex); @@ -568,6 +577,7 @@ private string Decrypt(string actualContent) { resultString = preContext + resultString; } + if (postContext != null) { resultString = resultString + postContext; diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index 644771c9e5c..9b60b1e3133 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -45,8 +45,10 @@ public sealed class GetCredentialCommand : PSCmdlet public string Message { get { return _message; } + set { _message = value; } } + private string _message = UtilsStrings.PromptForCredential_DefaultMessage; /// @@ -57,8 +59,10 @@ public string Message public string UserName { get { return _userName; } + set { _userName = value; } } + private string _userName = null; /// @@ -69,8 +73,10 @@ public string UserName public string Title { get { return _title; } + set { _title = value; } } + private string _title = UtilsStrings.PromptForCredential_DefaultCaption; /// diff --git a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs index f0c318021af..8f943cdc5b4 100644 --- a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs @@ -35,8 +35,10 @@ public class GetExecutionPolicyCommand : PSCmdlet public ExecutionPolicyScope Scope { get { return _executionPolicyScope; } + set { _executionPolicyScope = value; _scopeSpecified = true; } } + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; private bool _scopeSpecified = false; @@ -48,8 +50,10 @@ public ExecutionPolicyScope Scope public SwitchParameter List { get { return _list; } + set { _list = value; } } + private bool _list; /// @@ -122,8 +126,10 @@ public class SetExecutionPolicyCommand : PSCmdlet public ExecutionPolicy ExecutionPolicy { get { return _executionPolicy; } + set { _executionPolicy = value; } } + private ExecutionPolicy _executionPolicy; /// @@ -133,8 +139,10 @@ public ExecutionPolicy ExecutionPolicy public ExecutionPolicyScope Scope { get { return _executionPolicyScope; } + set { _executionPolicyScope = value; } } + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; /// @@ -148,11 +156,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private SwitchParameter _force; /// diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 78121411bfc..16beea946c9 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -27,6 +27,7 @@ public abstract class SecureStringCommandBase : PSCmdlet protected SecureString SecureStringData { get { return _ss; } + set { _ss = value; } } @@ -232,6 +233,7 @@ public String String _s = value; } } + private string _s; /// @@ -251,6 +253,7 @@ public SwitchParameter AsPlainText _asPlainText = value; } } + private bool _asPlainText; /// @@ -270,6 +273,7 @@ public SwitchParameter Force _force = value; } } + private bool _force; /// diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 4bad0ac230f..745aebe150a 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -42,6 +42,7 @@ public string[] FilePath _path = value; } } + private string[] _path; /// @@ -64,6 +65,7 @@ public string[] LiteralPath _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -73,8 +75,10 @@ public string[] LiteralPath protected Signature Signature { get { return _signature; } + set { _signature = value; } } + private Signature _signature; /// @@ -95,6 +99,7 @@ public string[] SourcePathOrExtension _sourcePathOrExtension = value; } } + private string[] _sourcePathOrExtension; /// @@ -106,11 +111,13 @@ public string[] SourcePathOrExtension public byte[] Content { get { return _content; } + set { _content = value; } } + private byte[] _content; // @@ -325,6 +332,7 @@ public X509Certificate2 Certificate _certificate = value; } } + private X509Certificate2 _certificate; /// @@ -351,6 +359,7 @@ public string IncludeChain _includeChain = value; } } + private string _includeChain = "notroot"; /// @@ -372,9 +381,11 @@ public string TimestampServer { value = String.Empty; } + _timestampServer = value; } } + private string _timestampServer = string.Empty; /// @@ -395,6 +406,7 @@ public string HashAlgorithm _hashAlgorithm = value; } } + private string _hashAlgorithm = null; /// @@ -407,11 +419,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// From b623a99b4c38f025d1374253b9c87cd1c3c7b1a2 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:45 -0800 Subject: [PATCH 35/81] Update CoreCLR --- .../CoreCLR/CorePsAssemblyLoadContext.cs | 1 + .../CoreCLR/CorePsPlatform.cs | 12 ++++++++++++ .../CoreCLR/CorePsStub.cs | 3 +++ .../CoreCLR/EventResource.cs | 1 + 4 files changed, 17 insertions(+) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index b38c8349f24..5dc3ab315d6 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -83,6 +83,7 @@ private PowerShellAssemblyLoadContext(string basePaths) string message = string.Format(CultureInfo.CurrentCulture, BaseFolderDoesNotExist, basePath); throw new ArgumentException(message, "basePaths"); } + _probingPaths[i] = basePath.Trim(); } } diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index f55ae105c81..06204e664a8 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -192,6 +192,7 @@ internal static void RemoveTemporaryDirectory() { // ignore if there is a failure } + _tempDirectory = null; } @@ -244,6 +245,7 @@ public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) { envHome = GetTemporaryDirectory(); } + string xdgConfigHomeDefault = Path.Combine(envHome, ".config", "powershell"); string xdgDataHomeDefault = Path.Combine(envHome, ".local", "share", "powershell"); string xdgModuleDefault = Path.Combine(xdgDataHomeDefault, "Modules"); @@ -281,6 +283,7 @@ public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) return GetTemporaryDirectory(); } } + return xdgDataHomeDefault; } else @@ -305,6 +308,7 @@ public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) return GetTemporaryDirectory(); } } + return xdgModuleDefault; } else @@ -403,20 +407,24 @@ private static string InternalGetFolderPath(System.Environment.SpecialFolder fol { envHome = Platform.GetTemporaryDirectory(); } + switch (folder) { case System.Environment.SpecialFolder.ProgramFiles: folderPath = "/bin"; if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } + break; case System.Environment.SpecialFolder.ProgramFilesX86: folderPath = "/usr/bin"; if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } + break; case System.Environment.SpecialFolder.System: case System.Environment.SpecialFolder.SystemX86: folderPath = "/sbin"; if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } + break; case System.Environment.SpecialFolder.Personal: folderPath = envHome; @@ -435,6 +443,7 @@ private static string InternalGetFolderPath(System.Environment.SpecialFolder fol folderPath = String.Empty; } } + break; default: throw new NotSupportedException(); @@ -572,6 +581,7 @@ public static string UserName { s_userName = NativeMethods.GetUserName(); } + return s_userName ?? string.Empty; } } @@ -591,6 +601,7 @@ public static string TemporaryDirectory return dir; } } + return "/tmp"; } } @@ -637,6 +648,7 @@ public static int GetProcFSParentPid(int pid) { return invalidPid; } + return Int32.Parse(parts[3]); } catch (Exception) diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 6ed4d61045c..f0fd3e70c41 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -22,6 +22,7 @@ namespace System.Management.Automation public sealed class PSTransactionContext : IDisposable { internal PSTransactionContext(Internal.PSTransactionManager transactionManager) { } + public void Dispose() { } } @@ -396,6 +397,7 @@ public void SetValue(string name, object value, RegistryValueKind valueKind) { throw new NotImplementedException("SetValue(string name, obj value, RegistryValueKind valueKind) is not implemented. TransactedRegistry related APIs should not be used."); } + public string[] GetValueNames() { throw new NotImplementedException("GetValueNames() is not implemented. TransactedRegistry related APIs should not be used."); @@ -447,6 +449,7 @@ public void Close() } public abstract string Name { get; } + public abstract int SubKeyCount { get; } public void SetAccessControl(ObjectSecurity securityDescriptor) diff --git a/src/System.Management.Automation/CoreCLR/EventResource.cs b/src/System.Management.Automation/CoreCLR/EventResource.cs index dffa359a032..b0890e7ee05 100755 --- a/src/System.Management.Automation/CoreCLR/EventResource.cs +++ b/src/System.Management.Automation/CoreCLR/EventResource.cs @@ -617,6 +617,7 @@ public static string GetMessage(int eventId, out int parameterCount) parameterCount = 3; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_DISCONNECT"; } + parameterCount = 0; return null; } From b2023576c58b3dda3647617b48267d4517de9a5a Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:45 -0800 Subject: [PATCH 36/81] Update DscSupport --- .../DscSupport/CimDSCParser.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 7f1dc774d15..ee831a13235 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -58,6 +58,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins { innerException = powerShell.Streams.Error[0].Exception; } + errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InstantiatePSClassObjectFailed, className); var invalidOperationException = new InvalidOperationException(errorMessage, innerException); throw invalidOperationException; @@ -102,11 +103,13 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins { targetValue = ConvertCimInstanceToObject(memberType, cimPropertyInstance, moduleName); } + if (targetValue == null) { return null; } } + break; case CimType.InstanceArray: { @@ -133,11 +136,14 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins { return null; } + targetArray.SetValue(obj, i); } + targetValue = targetArray; } } + break; default: targetValue = LanguagePrimitives.ConvertTo(property.Value, memberType, CultureInfo.InvariantCulture); @@ -155,12 +161,14 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins { ((FieldInfo)member).SetValue(targetObject, targetValue); } + if (member is PropertyInfo) { ((PropertyInfo)member).SetValue(targetObject, targetValue); } } } + return targetObject; } @@ -188,6 +196,7 @@ private static object ConvertCimInstanceHashtable(string providerName, CimInstan var invalidOperationException = new InvalidOperationException(errorMessage); throw invalidOperationException; } + result.Add(LanguagePrimitives.ConvertTo(key.Value), LanguagePrimitives.ConvertTo(value.Value)); } } @@ -404,6 +413,7 @@ internal List ParseSchemaMof(string filePath) { fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex); } + var result = new List(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null)); foreach (CimClass c in result) { @@ -504,6 +514,7 @@ public static class DscClassCache { t_classCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } + return t_classCache; } } @@ -522,6 +533,7 @@ private static Dictionary> ByClassModuleCache { t_byClassModuleCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } + return t_byClassModuleCache; } } @@ -540,6 +552,7 @@ private static Dictionary> ByClassModuleCache { t_byFileClassCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } + return t_byFileClassCache; } } @@ -558,6 +571,7 @@ private static HashSet ScriptKeywordFileCache { t_scriptKeywordFileCache = new HashSet(StringComparer.OrdinalIgnoreCase); } + return t_scriptKeywordFileCache; } } @@ -595,6 +609,7 @@ private static bool CacheResourcesFromMultipleModuleVersions { return t_cacheResourcesFromMultipleModuleVersions; } + set { t_cacheResourcesFromMultipleModuleVersions = value; @@ -651,6 +666,7 @@ public static void Initialize(Collection errors, List moduleP { continue; } + foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) { ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); @@ -702,6 +718,7 @@ public static void Initialize(Collection errors, List moduleP { continue; } + foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) { ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); @@ -796,6 +813,7 @@ private static Tuple GetModuleInfoHelper(string moduleFolderPat { moduleName = Path.GetFileName(moduleFolderPath); } + string manifestPath = Path.Combine(moduleFolderPath, moduleName + ".psd1"); s_tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath); @@ -928,10 +946,12 @@ public static List ImportClasses(string path, Tuple m } } } + if (s_hiddenResourceCache.Contains(className)) { continue; } + if (!CacheResourcesFromMultipleModuleVersions) { // Find & remove the previous version of the resource. @@ -941,6 +961,7 @@ public static List ImportClasses(string path, Tuple m ClassCache.Remove(resourceList[0].Key); } } + ClassCache[moduleQualifiedResourceName] = new Tuple(DSCResourceRunAsCredential.Default, c); ByClassModuleCache[className] = moduleInfo; } @@ -1048,6 +1069,7 @@ where string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreC cachedClasses.Add(pair.Value.Item2); } } + return cachedClasses; } @@ -1147,6 +1169,7 @@ public static List ImportInstances(string path, int schemaValidatio throw PSTraceSource.NewArgumentNullException("path"); throw new ArgumentNullException("path"); } + if (schemaValidationOption < (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Default || schemaValidationOption > (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Ignore) { @@ -1196,6 +1219,7 @@ private static string GetFriendlyName(CimClass cimClass) { //exception means no DSCAlias } + return null; } @@ -1218,6 +1242,7 @@ public static Collection GetCachedKeywords() keywords.Add(keyword); } } + return keywords; } @@ -1280,6 +1305,7 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi { return null; } + var keyword = new DynamicKeyword() { BodyMode = DynamicKeywordBodyMode.Hashtable, @@ -1796,6 +1822,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceInsideNode))); break; } + keywordAst = Ast.GetAncestorAst(keywordAst.Parent); } @@ -1937,6 +1964,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse", string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString))); } + return; } } @@ -2142,6 +2170,7 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM { scriptPath = moduleInfo.Path; } + ImportKeywordsFromScriptFile(scriptPath, primaryModuleInfo, resourcesToImport, resourcesFound, functionsToDefine, errorList, extent); } @@ -2257,6 +2286,7 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s { sb.Append(" : OMI_BaseResource"); } + sb.Append("\n{\n"); ProcessMembers(sb, embeddedInstanceTypes, typeAst, className); @@ -2286,6 +2316,7 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s bases.Enqueue(b1); } } + continue; } } @@ -2363,6 +2394,7 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin { moduleFiles.Add(moduleInfo.Path); } + if (moduleInfo.NestedModules != null) { foreach (var nestedModule in moduleInfo.NestedModules.Where(m => !string.IsNullOrEmpty(m.Path))) @@ -2440,6 +2472,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan out isArrayType, out embeddedInstanceType, embeddedInstanceTypes, ref enumNames); } + string arrayAffix = isArrayType ? "[]" : String.Empty; sb.AppendFormat(CultureInfo.InvariantCulture, @@ -2495,9 +2528,11 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume { errorMessages.Add(error.ToString()); } + errorList.Add(new ParseError(extent, "FailToParseModuleScriptFile", string.Format(CultureInfo.CurrentCulture, ParserStrings.FailToParseModuleScriptFile, fileName, string.Join(Environment.NewLine, errorMessages)))); } + return false; } @@ -2512,6 +2547,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) return true; } } + return false; }, false); @@ -2626,11 +2662,13 @@ private static bool AreQualifiersSame(CimReadOnlyKeyedCollection o { return false; } + if ((qual.CimType != newQual.CimType) || (qual.Flags != newQual.Flags)) { return false; } + if ((qual.Value == null && newQual.Value != null) || (qual.Value != null && newQual.Value == null) || (qual.Value != null && newQual.Value != null && @@ -2641,8 +2679,10 @@ private static bool AreQualifiersSame(CimReadOnlyKeyedCollection o return false; } } + return true; } + private static bool ArePropertiesSame(CimReadOnlyKeyedCollection oldProperties, CimReadOnlyKeyedCollection newProperties) { if (oldProperties.Count != newProperties.Count) @@ -2664,13 +2704,16 @@ private static bool ArePropertiesSame(CimReadOnlyKeyedCollection sb.AppendFormat(CultureInfo.InvariantCulture, "{0}key", needComma ? ", " : string.Empty); needComma = true; } + if (dscProperty.Mandatory) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}required", needComma ? ", " : string.Empty); needComma = true; } + if (dscProperty.NotConfigurable) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}read", needComma ? ", " : string.Empty); needComma = true; } + continue; } @@ -2840,6 +2886,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable sbValues.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value); valueMapComma = true; } + sb.Append("}"); sb.Append(sbValues); sb.Append("}"); @@ -2862,6 +2909,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); needComma = true; } + sb.Append("}, Values{"); needComma = false; foreach (var name in enumNames) @@ -2869,12 +2917,14 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); needComma = true; } + sb.Append("}"); } else if (embeddedInstanceType != null) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}EmbeddedInstance(\"{1}\")", needComma ? ", " : string.Empty, embeddedInstanceType); } + sb.Append("]"); return sb.ToString(); } @@ -2926,6 +2976,7 @@ private static void ProcessEmbeddedInstanceTypes(List embeddedInstanceTy { GenerateMofForAst((TypeDefinitionAst)batchedTypes[i], nestedSb, embeddedInstanceTypes); } + nestedSb.Append('\n'); } @@ -2943,6 +2994,7 @@ private static void GenerateMofForType(Type type, StringBuilder sb, List { sb.Append(" : OMI_BaseResource"); } + sb.Append("\n{\n"); ProcessMembers(type, sb, embeddedInstanceTypes, className); @@ -2971,6 +3023,7 @@ private static void ProcessMembers(Type type, StringBuilder sb, List emb { continue; } + memberType = propertyInfo.PropertyType; } @@ -3047,6 +3100,7 @@ private static void ProcessMofForDynamicKeywords(PSModuleInfo module, ICollectio ClassCache.Remove(resourceList[0].Key); } } + var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className); ClassCache[moduleQualifiedResourceName] = new Tuple(runAsBehavior, c); ByClassModuleCache[className] = new Tuple(module.Name, module.Version); @@ -3118,6 +3172,7 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, DSCResourceRunAsCredential.Default); } } + return true; } else if (Directory.Exists(dscResourcesPath)) @@ -3565,6 +3620,7 @@ private static ScriptBlock CimKeywordImplementationFunction (s_cimKeywordImplementationFunction = ScriptBlock.Create(CimKeywordImplementationFunctionText)); } } + private static ScriptBlock s_cimKeywordImplementationFunction; private const string CimKeywordImplementationFunctionText = @" param ( @@ -3615,6 +3671,7 @@ function Test-DependsOn $DependsOnVar } } + $value['DependsOn']= $updatedDependsOn if($null -ne $DependsOn) From b26a424a9a99cd450cd31ab7f645c233cf701a5f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:51 -0800 Subject: [PATCH 37/81] Update engine --- .../engine/AliasInfo.cs | 4 + .../engine/ApplicationInfo.cs | 4 + .../engine/Attributes.cs | 29 +++++ .../engine/AutomationEngine.cs | 1 + .../engine/CmdletInfo.cs | 14 +++ .../engine/CmdletParameterBinderController.cs | 49 +++++++++ .../engine/CodeMethods.cs | 1 + .../engine/CommandBase.cs | 8 ++ .../engine/CommandDiscovery.cs | 25 +++++ .../engine/CommandInfo.cs | 12 +++ .../engine/CommandMetadata.cs | 16 +++ .../engine/CommandParameter.cs | 6 ++ .../engine/CommandPathSearch.cs | 1 + .../engine/CommandProcessor.cs | 7 ++ .../engine/CommandProcessorBase.cs | 13 +++ .../engine/CommandSearcher.cs | 15 +++ .../engine/CommonCommandParameters.cs | 13 +++ .../engine/CompiledCommandParameter.cs | 4 + .../engine/CoreAdapter.cs | 95 ++++++++++++++++ .../engine/Credential.cs | 2 + .../engine/DataStoreAdapter.cs | 4 + .../engine/DataStoreAdapterProvider.cs | 12 +++ .../engine/EnumExpressionEvaluator.cs | 9 ++ .../engine/EnumMinimumDisambiguation.cs | 3 + .../engine/ErrorPackage.cs | 40 +++++++ .../engine/EventManager.cs | 8 ++ .../engine/ExecutionContext.cs | 44 ++++++++ .../engine/ExtendedTypeSystemException.cs | 2 + .../engine/ExternalScriptInfo.cs | 11 ++ .../engine/ExtraAdapter.cs | 4 + .../engine/FunctionInfo.cs | 8 ++ .../engine/GetCommandCommand.cs | 34 ++++++ .../engine/GetEvent_Types_Ps1Xml.cs | 1 + .../engine/InformationRecord.cs | 10 ++ .../engine/InitialSessionState.cs | 83 ++++++++++++++ .../engine/InternalCommands.cs | 75 +++++++++++++ .../engine/InvocationInfo.cs | 6 ++ .../engine/LanguagePrimitives.cs | 55 ++++++++++ .../engine/ManagementObjectAdapter.cs | 8 ++ .../engine/MergedCommandParameterMetadata.cs | 9 ++ .../MinishellParameterBinderController.cs | 2 + .../engine/MshCmdlet.cs | 6 ++ .../engine/MshCommandRuntime.cs | 28 +++++ .../engine/MshMemberInfo.cs | 3 + .../engine/MshObject.cs | 65 +++++++++++ .../engine/MshObjectTypeDescriptor.cs | 25 +++++ .../engine/MshReference.cs | 1 + .../engine/MshSecurityException.cs | 3 + .../engine/MshSnapinQualifiedName.cs | 3 + .../engine/NativeCommand.cs | 1 + .../engine/NativeCommandParameterBinder.cs | 7 ++ .../engine/NativeCommandProcessor.cs | 15 +++ .../engine/ObjectEventRegistrationBase.cs | 13 +++ .../engine/PSConfiguration.cs | 5 + .../engine/PSVersionInfo.cs | 7 ++ .../engine/ParameterBinderBase.cs | 12 +++ .../engine/ParameterBinderController.cs | 11 ++ .../engine/ParameterSetInfo.cs | 3 + .../engine/ParameterSetSpecificMetadata.cs | 1 + .../engine/Pipe.cs | 15 +++ .../engine/ProcessCodeMethods.cs | 1 + .../engine/ProgressRecord.cs | 14 +++ .../engine/ProxyCommand.cs | 10 ++ .../engine/PseudoParameterBinder.cs | 2 + .../engine/PseudoParameters.cs | 10 ++ .../engine/ScopedItemSearcher.cs | 5 + .../engine/ScriptCommandProcessor.cs | 2 + .../engine/ScriptInfo.cs | 1 + .../engine/SessionState.cs | 7 ++ .../engine/SessionStateCmdletAPIs.cs | 2 + .../engine/SessionStateContainer.cs | 17 +++ .../engine/SessionStateContent.cs | 7 ++ .../engine/SessionStateDriveAPIs.cs | 6 ++ .../engine/SessionStateDynamicProperty.cs | 10 ++ .../engine/SessionStateFunctionAPIs.cs | 4 + .../engine/SessionStateItem.cs | 8 ++ .../engine/SessionStateLocationAPIs.cs | 4 + .../engine/SessionStateNavigation.cs | 8 ++ .../engine/SessionStateProperty.cs | 6 ++ .../engine/SessionStateProviderAPIs.cs | 10 ++ .../engine/SessionStatePublic.cs | 5 + .../engine/SessionStateScope.cs | 9 ++ .../engine/SessionStateScopeAPIs.cs | 3 + .../engine/SessionStateUtils.cs | 2 + .../engine/SessionStateVariableAPIs.cs | 4 + .../engine/ShellVariable.cs | 17 +++ .../engine/SpecialVariables.cs | 1 + .../engine/TransactedString.cs | 1 + .../engine/TransactionManager.cs | 7 ++ .../engine/TypeMetadata.cs | 26 +++++ .../engine/TypeTable.cs | 90 ++++++++++++++++ .../engine/Types_Ps1Xml.cs | 15 +++ .../engine/UserFeedbackParameters.cs | 5 + .../engine/Utils.cs | 10 ++ .../engine/VariablePath.cs | 2 + .../engine/WorkflowInfo.cs | 2 + .../engine/cmdlet.cs | 5 + .../engine/pipeline.cs | 27 +++++ .../engine/regex.cs | 9 ++ .../engine/scriptparameterbindercontroller.cs | 4 + .../engine/serialization.cs | 101 ++++++++++++++++++ 101 files changed, 1450 insertions(+) diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index 45065c3de1b..a3425bce270 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -161,6 +161,7 @@ public CommandInfo ResolvedCommand result = null; break; } + cyclePrevention.Add(result.Name); commandNameToResolve = result.Definition; @@ -191,6 +192,7 @@ public override string Definition return _definition; } } + private string _definition = String.Empty; /// @@ -323,6 +325,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) _options = newOptions; } + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -351,6 +354,7 @@ public override ReadOnlyCollection OutputType { return resolvedCommand.OutputType; } + return null; } } diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index ad0f0b2ecb8..c67724422ac 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -51,6 +51,7 @@ internal ApplicationInfo(string name, string path, ExecutionContext context) : b Extension = System.IO.Path.GetExtension(path); _context = context; } + private ExecutionContext _context; #endregion ctor @@ -111,6 +112,7 @@ public override SessionStateEntryVisibility Visibility { return _context.EngineSessionState.CheckApplicationVisibility(Path); } + set { throw PSTraceSource.NewNotImplementedException(); } } @@ -127,9 +129,11 @@ public override ReadOnlyCollection OutputType l.Add(new PSTypeName(typeof(string))); _outputType = new ReadOnlyCollection(l); } + return _outputType; } } + private ReadOnlyCollection _outputType = null; } } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index fb0037d39b5..784ab42ff61 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -257,6 +257,7 @@ protected sealed override void Validate(object arguments, EngineIntrinsics engin { ValidateElement(enumerator.Current); } + enumerator.Reset(); } @@ -365,6 +366,7 @@ public abstract class CmdletCommonMetadataAttribute : CmdletMetadataAttribute public bool SupportsTransactions { get { return _supportsTransactions; } + set { #if !CORECLR @@ -376,6 +378,7 @@ public bool SupportsTransactions #endif } } + private bool _supportsTransactions = false; /// @@ -544,8 +547,10 @@ public OutputTypeAttribute(params string[] type) public string[] ParameterSetName { get { return _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets }); } + set { _parameterSetName = value; } } + private string[] _parameterSetName; } @@ -660,9 +665,11 @@ private ExperimentAction EffectiveAction { _effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName, ExperimentAction); } + return _effectiveAction; } } + private ExperimentAction _effectiveAction = default(ExperimentAction); #endregion @@ -679,6 +686,7 @@ private ExperimentAction EffectiveAction public string ParameterSetName { get { return _parameterSetName; } + set { _parameterSetName = value; @@ -725,12 +733,14 @@ public string HelpMessage { return _helpMessage; } + set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("HelpMessage"); } + _helpMessage = value; } } @@ -746,12 +756,14 @@ public string HelpMessageBaseName { return _helpMessageBaseName; } + set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("HelpMessageBaseName"); } + _helpMessageBaseName = value; } } @@ -767,12 +779,14 @@ public string HelpMessageResourceId { return _helpMessageResourceId; } + set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("HelpMessageResourceId"); } + _helpMessageResourceId = value; } } @@ -925,15 +939,18 @@ public ValidateLengthAttribute(int minLength, int maxLength) : base() { throw PSTraceSource.NewArgumentOutOfRangeException("minLength", minLength); } + if (maxLength <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxLength", maxLength); } + if (maxLength < minLength) { throw new ValidationMetadataException("ValidateLengthMaxLengthSmallerThanMinLength", null, Metadata.ValidateLengthMaxLengthSmallerThanMinLength); } + MinLength = minLength; MaxLength = maxLength; } @@ -1046,10 +1063,12 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() { throw PSTraceSource.NewArgumentNullException("minRange"); } + if (maxRange == null) { throw PSTraceSource.NewArgumentNullException("maxRange"); } + if (maxRange.GetType() != minRange.GetType()) { bool failure = true; @@ -1067,6 +1086,7 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() } } } + if (failure) { throw new ValidationMetadataException("MinRangeNotTheSameTypeOfMaxRange", null, @@ -1098,6 +1118,7 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() throw new ValidationMetadataException("MaxRangeSmallerThanMinRange", null, Metadata.ValidateRangeMaxRangeSmallerThanMinRange); } + MinRange = minRange; MaxRange = maxRange; } @@ -1157,6 +1178,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) Metadata.ValidateRangePositiveFailure, element.ToString()); } + break; case ValidateRangeKind.NonNegative: if (dynamicZero.CompareTo(element) > 0) @@ -1167,6 +1189,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) Metadata.ValidateRangeNonNegativeFailure, element.ToString()); } + break; case ValidateRangeKind.Negative: if (dynamicZero.CompareTo(element) <= 0) @@ -1177,6 +1200,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) Metadata.ValidateRangeNegativeFailure, element.ToString()); } + break; case ValidateRangeKind.NonPositive: if (dynamicZero.CompareTo(element) < 0) @@ -1187,6 +1211,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) Metadata.ValidateRangeNonPositiveFailure, element.ToString()); } + break; } } @@ -1525,15 +1550,18 @@ public ValidateCountAttribute(int minLength, int maxLength) { throw PSTraceSource.NewArgumentOutOfRangeException("minLength", minLength); } + if (maxLength <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxLength", maxLength); } + if (maxLength < minLength) { throw new ValidationMetadataException("ValidateRangeMaxLengthSmallerThanMinLength", null, Metadata.ValidateCountMaxLengthSmallerThanMinLength); } + MinLength = minLength; MaxLength = maxLength; } @@ -2202,6 +2230,7 @@ internal object TransformInternal(EngineIntrinsics engineIntrinsics, object inpu { ExecutionContext.PropagateInputSource(inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode); } + return result; } diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 9646929465b..e2a22372660 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -84,6 +84,7 @@ internal ScriptBlock ParseScriptBlock(string script, string fileName, bool addTo { throw new IncompleteParseException(errors[0].Message, errors[0].ErrorId); } + throw new ParseException(errors); } diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 88f007dab1a..e1c1dc1d28f 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -148,6 +148,7 @@ public string Verb return _verb; } } + private string _verb = String.Empty; /// @@ -160,6 +161,7 @@ public string Noun return _noun; } } + private string _noun = String.Empty; internal static bool SplitCmdletName(string name, out string verb, out string noun) @@ -177,12 +179,14 @@ internal static bool SplitCmdletName(string name, out string verb, out string no break; } } + if (index > 0) { verb = name.Substring(0, index); noun = name.Substring(index + 1); return true; } + return false; } @@ -195,11 +199,13 @@ public string HelpFile { return _helpFilePath; } + internal set { _helpFilePath = value; } } + private string _helpFilePath = String.Empty; internal override HelpCategory HelpCategory @@ -217,6 +223,7 @@ public PSSnapInInfo PSSnapIn return _PSSnapin; } } + private PSSnapInInfo _PSSnapin; /// @@ -231,6 +238,7 @@ internal string PSSnapInName { result = _PSSnapin.Name; } + return result; } } @@ -270,6 +278,7 @@ public Type ImplementingType return _implementingType; } } + private Type _implementingType = null; /// @@ -370,6 +379,7 @@ public override ReadOnlyCollection OutputType } } } + if (provider == null) { // No path argument, so just use the current path to choose the provider. @@ -387,6 +397,7 @@ public override ReadOnlyCollection OutputType return new ReadOnlyCollection(_outputType); } } + private List _outputType = null; /// @@ -408,6 +419,7 @@ public ScopedItemOptions Options SetOptions(value, false); } } + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -454,6 +466,7 @@ private static string GetFullName(string moduleName, string cmdletName) { result = moduleName + '\\' + result; } + return result; } @@ -525,6 +538,7 @@ internal override CommandMetadata CommandMetadata (_cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context)); } } + private CommandMetadata _cmdletMetadata; internal override bool ImplementsDynamicParameters diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 89845be4529..97798378bd5 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -384,6 +384,7 @@ private void ApplyDefaultParameterBinding(string bindingStage, bool isDynamic) s_tracer.WriteLine("BIND DEFAULT after [{0}] result [{1}]", bindingStage, isSuccess); } + return; } @@ -465,6 +466,7 @@ private bool BindDefaultParameters(uint validParameterSetFlag, Dictionary GetQualifiedParameter { return result; } + return null; } @@ -653,6 +656,7 @@ private Dictionary GetDefaultParameterVa { keysToRemove.Add(entry.Key); } + continue; } @@ -730,6 +734,7 @@ private Dictionary GetDefaultParameterVa String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.MultipleParametersMatched, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } + continue; } @@ -749,6 +754,7 @@ private Dictionary GetDefaultParameterVa String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } + parametersToRemove.Add(matches[0]); } } @@ -943,6 +949,7 @@ private void VerifyArgumentsProcessed(ParameterBindingException originalBindingE "PositionalParameterNotFound"); } } + if (!DefaultParameterBindingInUse) { throw bindingException; @@ -1049,6 +1056,7 @@ private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCom { _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); } + break; } @@ -1182,6 +1190,7 @@ private Collection BindParameters(uint parameterSets, result.Add(argument); } } + return result; } @@ -1395,9 +1404,11 @@ internal override bool BindParameter( rethrow = false; break; } + e = e.InnerException; } } + if (rethrow) { throw; @@ -1499,6 +1510,7 @@ private bool BindParameter( parameter.Parameter, flags); } + break; } @@ -1597,6 +1609,7 @@ private void HandleRemainingArguments() ThrowElaboratedBindingException(bindingException); } } + varargsParameter = parameter; } } @@ -1662,6 +1675,7 @@ private void HandleRemainingArguments() ThrowElaboratedBindingException(pbex); } } + UnboundArguments.Clear(); } } @@ -1917,6 +1931,7 @@ private Collection GetMissingMandatoryParameters { availableParameterSetFlags = uint.MaxValue; } + commandMandatorySets = (_currentParameterSetFlag & availableParameterSetFlags); } @@ -2111,6 +2126,7 @@ private Collection GetMissingMandatoryParameters } } } + if (!latchOnToDefault) { // When we select a mandatory set to latch on, we should try to preserve other parameter sets that contain no mandatory parameters or contain only common mandatory parameters @@ -2327,6 +2343,7 @@ private Collection GetMissingMandatoryParameters setThatTakesPipelineInputByPropertyName = 0; break; } + setThatTakesPipelineInputByPropertyName = promptingSetData.ParameterSet; foundSetThatTakesPipelineInputByPropertyName = true; } @@ -2542,6 +2559,7 @@ private uint NewParameterSetPromptingData( { parameterSetFlag = uint.MaxValue; } + bool isDefaultSet = (defaultParameterSet != 0) && ((defaultParameterSet & parameterSetFlag) != 0); bool isMandatory = false; @@ -2670,6 +2688,7 @@ private int ValidateParameterSets(bool prePipelineInput, bool setDefault) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } + validParameterSetCount = resolvedParameterSetCount; } } @@ -2710,9 +2729,11 @@ private int ValidateParameterSets(bool prePipelineInput, bool setDefault) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } + validParameterSetCount = resolvedParameterSetCount; } } + Command.SetParameterSetName(CurrentParameterSetName); } @@ -2742,6 +2763,7 @@ Cmdlet command { allParameterSetFlags |= parameterSetMetadata.ParameterSetFlag; } + remainingParameterSetsWithNoMandatoryUnboundParameters &= allParameterSetFlags; Diagnostics.Assert( @@ -2766,8 +2788,10 @@ Cmdlet command string currentParameterSetName = bindableParameters.GetParameterSetName(_currentParameterSetFlag); command.SetParameterSetName(currentParameterSetName); } + return finalParameterSetCount; } + return -1; } @@ -2965,6 +2989,7 @@ internal bool HandleUnboundMandatoryParameters( result, "Any error in binding the parameter with type coercion should result in an exception"); } + result = true; } } @@ -3100,6 +3125,7 @@ private Collection CreatePromptDataStructures( { fDesc.HelpMessage = helpInfo; } + fDesc.SetParameterType(parameter.Parameter.Type); fDesc.Label = BuildLabel(parameter.Parameter.Name, usedHotKeys); @@ -3155,6 +3181,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys break; } } + if (!built) { // try Lower case @@ -3169,6 +3196,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys } } } + if (!built) { // try non-letters @@ -3183,11 +3211,13 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys } } } + if (!built) { // use first char label.Insert(0, hotKeyPrefix); } + return label.ToString(); } @@ -3284,6 +3314,7 @@ internal bool BindPipelineParameters(PSObject inputToOperateOn) // if it failed some post binding verification step. this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput); } + return result; } @@ -3337,6 +3368,7 @@ private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) ParameterBinderBase.bindingTracer.WriteLine("RESTORING pipeline parameter's original values"); } + bool result = false; // Reset the default values @@ -3541,6 +3573,7 @@ private bool BindUnboundParametersForBindingStateInParameterSet( } } } + return aParameterWasBound; } @@ -3576,6 +3609,7 @@ private bool BindValueFromPipeline( { invalidCast = e.InnerException as PSInvalidCastException; } + if (invalidCast == null) { parameterBindingException = e; @@ -3857,6 +3891,7 @@ private static int ValidParameterSetCount(uint parameterSetFlags) parameterSetFlags >>= 1; } } + return result; } @@ -3910,6 +3945,7 @@ internal object GetDefaultParameterValue(string name) { result = _dynamicParameterBinder.GetDefaultParameterValue(name); } + break; } } @@ -3991,6 +4027,7 @@ private HashSet BoundObsoleteParameterNames (_boundObsoleteParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase)); } } + private HashSet _boundObsoleteParameterNames; /// @@ -4019,9 +4056,11 @@ internal ReflectionParameterBinder ShouldProcessParametersBinder this.Command, this.CommandLineParameters); } + return _shouldProcessParameterBinder; } } + private ReflectionParameterBinder _shouldProcessParameterBinder; /// @@ -4044,9 +4083,11 @@ internal ReflectionParameterBinder PagingParametersBinder this.Command, this.CommandLineParameters); } + return _pagingParameterBinder; } } + private ReflectionParameterBinder _pagingParameterBinder; /// @@ -4069,9 +4110,11 @@ internal ReflectionParameterBinder TransactionParametersBinder this.Command, this.CommandLineParameters); } + return _transactionParameterBinder; } } + private ReflectionParameterBinder _transactionParameterBinder; /// @@ -4094,9 +4137,11 @@ internal ReflectionParameterBinder CommonParametersBinder this.Command, this.CommandLineParameters); } + return _commonParametersBinder; } } + private ReflectionParameterBinder _commonParametersBinder; private class DelayedScriptBlockArgument @@ -4518,6 +4563,7 @@ public override object this[object key] string keyAfterTrim = strKey.Trim(); return base[keyAfterTrim]; } + set { AddImpl(key, value, isSelfIndexing: true); @@ -4651,6 +4697,7 @@ private static int GetValueToken(int index, string key, ref string name, bool ge builder.Append(key[index]); continue; } + name = builder.ToString().Trim(); return name.Length == 0 ? -1 : index; } @@ -4666,6 +4713,7 @@ private static int GetValueToken(int index, string key, ref string name, bool ge Diagnostics.Assert(name.Length > 0, "name should not be empty at this point"); return index; } + return -1; } @@ -4686,6 +4734,7 @@ private static int SkipWhiteSpace(int index, string key) continue; return index; } + return -1; } diff --git a/src/System.Management.Automation/engine/CodeMethods.cs b/src/System.Management.Automation/engine/CodeMethods.cs index eccfe3fdb4b..bdbe2644267 100644 --- a/src/System.Management.Automation/engine/CodeMethods.cs +++ b/src/System.Management.Automation/engine/CodeMethods.cs @@ -37,6 +37,7 @@ public static string PropertyValueCollection(PSObject instance) { return String.Empty; } + return (PSObject.AsPSObject(values[0]).ToString()); } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 2bb168d6a68..0948f17fc7d 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -89,6 +89,7 @@ internal InvocationInfo MyInvocation internal PSObject CurrentPipelineObject { get { return currentObjectInPipeline; } + set { currentObjectInPipeline = value; @@ -102,6 +103,7 @@ internal PSHost PSHostInternal { get { return _CBhost; } } + private PSHost _CBhost; /// @@ -111,6 +113,7 @@ internal SessionState InternalState { get { return _state; } } + private SessionState _state; /// @@ -135,6 +138,7 @@ internal bool IsStopping internal CommandInfo CommandInfo { get { return _commandInfo; } + set { _commandInfo = value; } } @@ -151,12 +155,14 @@ internal CommandInfo CommandInfo internal ExecutionContext Context { get { return _context; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Context"); } + _context = value; Diagnostics.Assert(_context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost"); _CBhost = (InternalHost)_context.EngineHostInterface; @@ -166,6 +172,7 @@ internal ExecutionContext Context _state = new SessionState(_context.EngineSessionState); } } + private ExecutionContext _context; /// @@ -176,6 +183,7 @@ public CommandOrigin CommandOrigin { get { return CommandOriginInternal; } } + internal CommandOrigin CommandOriginInternal = CommandOrigin.Internal; #endregion public_properties diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 276a1e396f7..7bea072e751 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -81,6 +81,7 @@ public ScriptBlock CommandScriptBlock } } } + private ScriptBlock _scriptBlock; } @@ -318,6 +319,7 @@ private static Collection GetPSSnapinNames(IEnumerable req { requiresMissingPSSnapIns = new Collection(); } + requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); } else @@ -395,6 +399,7 @@ private static void VerifyRequiredSnapins(IEnumerable req { requiresMissingPSSnapIns = new Collection(); } + requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); } } @@ -609,6 +614,7 @@ internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, new CommandNotFoundException(reqSyntaxException.Message, reqSyntaxException); throw e; } + break; case CommandTypes.Filter: case CommandTypes.Function: @@ -920,6 +926,7 @@ internal static void AutoloadModulesWithJobSourceAdapters(System.Management.Auto AutoloadSpecifiedModule(module, context, cmdletInfo.Visibility, out unUsedException); } } + context.IsModuleWithJobSourceAdapterLoaded = true; } } @@ -981,6 +988,7 @@ private static CommandInfo InvokeCommandNotFoundHandler(string commandName, Exec } finally { context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveCommandNotFound", originalCommandName); } } + return result; } @@ -1045,6 +1053,7 @@ private static CommandInfo TryNormalSearch(string commandName, { lastError = metadataException; } + return result; } @@ -1624,6 +1633,7 @@ internal LookupPathCollection(IEnumerable collection) : base() base.Add(item); result = base.IndexOf(item); } + return result; } @@ -1666,6 +1676,7 @@ internal void AddRange(ICollection collection) break; } } + return result; } @@ -1688,6 +1699,7 @@ internal Collection IndexOfRelativePath() result.Add(index); } } + return result; } @@ -1721,27 +1733,40 @@ internal Collection IndexOfRelativePath() break; } } + return result; } } // Guid is {ea9e8155-5042-5537-0b73-8c0e6b53f398} + [EventSource(Name = "Microsoft-PowerShell-CommandDiscovery")] internal class CommandDiscoveryEventSource : EventSource { internal static CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); public void CommandLookupStart(string CommandName) { WriteEvent(1, CommandName); } + public void CommandLookupStop(string CommandName) { WriteEvent(2, CommandName); } + public void ModuleAutoLoadingStart(string CommandName) { WriteEvent(3, CommandName); } + public void ModuleAutoLoadingStop(string CommandName) { WriteEvent(4, CommandName); } + public void ModuleAutoDiscoveryStart(string CommandName) { WriteEvent(5, CommandName); } + public void ModuleAutoDiscoveryStop(string CommandName) { WriteEvent(6, CommandName); } + public void SearchingForModuleFilesStart() { WriteEvent(7); } + public void SearchingForModuleFilesStop() { WriteEvent(8); } + public void GetModuleExportedCommandsStart(string ModulePath) { WriteEvent(9, ModulePath); } + public void GetModuleExportedCommandsStop(string ModulePath) { WriteEvent(10, ModulePath); } + public void ModuleManifestAnalysisResult(string ModulePath, bool Success) { WriteEvent(11, ModulePath, Success); } + public void ModuleManifestAnalysisException(string ModulePath, string Exception) { WriteEvent(12, ModulePath, Exception); } } } diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 19803efa878..4959a5b98fb 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -235,6 +235,7 @@ public virtual Version Version internal ExecutionContext Context { get { return _context; } + set { _context = value; @@ -244,6 +245,7 @@ internal ExecutionContext Context } } } + private ExecutionContext _context; /// @@ -314,6 +316,7 @@ public virtual SessionStateEntryVisibility Visibility { return CopiedCommand == null ? _visibility : CopiedCommand.Visibility; } + set { if (CopiedCommand == null) @@ -331,6 +334,7 @@ public virtual SessionStateEntryVisibility Visibility } } } + private SessionStateEntryVisibility _visibility = SessionStateEntryVisibility.Public; /// @@ -581,8 +585,10 @@ public virtual Dictionary Parameters internal CommandMetadata ExternalCommandMetadata { get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); } + set { _externalCommandMetadata = value; } } + private CommandMetadata _externalCommandMetadata; /// @@ -614,9 +620,11 @@ public ReadOnlyCollection ParameterSets _parameterSets = new ReadOnlyCollection(parameterSetInfo); } + return _parameterSets; } } + internal ReadOnlyCollection _parameterSets; /// @@ -678,6 +686,7 @@ internal Collection GenerateCommandParameterSetInfo() { result = GetCacheableMetadata(CommandMetadata); } + return result; } @@ -856,6 +865,7 @@ public Type Type TypeResolver.TryResolveType(Name, out _type); } } + if (_type == null) { // We ignore the exception. @@ -874,12 +884,14 @@ public Type Type return _type; } } + private Type _type; /// /// When a type is defined by PowerShell, the ast for that type. /// public TypeDefinitionAst TypeDefinitionAst { get; private set; } + private bool _typeWasCalculated; /// diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index d496d51a02b..b6cfdfc548d 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -464,6 +464,7 @@ internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionC public string DefaultParameterSetName { get { return _defaultParameterSetName; } + set { if (string.IsNullOrEmpty(value)) @@ -474,6 +475,7 @@ public string DefaultParameterSetName _defaultParameterSetName = value; } } + private string _defaultParameterSetName = ParameterAttribute.AllParameterSets; /// @@ -524,8 +526,10 @@ public RemotingCapability RemotingCapability return _remotingCapability; } + set { _remotingCapability = value; } } + private RemotingCapability _remotingCapability = RemotingCapability.PowerShell; /// @@ -571,11 +575,13 @@ public Dictionary Parameters return _parameters; } + private set { _parameters = value; } } + private Dictionary _parameters; private bool _shouldGenerateCommonParameters; @@ -601,6 +607,7 @@ internal MergedCommandParameterMetadata StaticCommandParameterMetadata return _staticCommandParameterMetadata; } } + private readonly MergedCommandParameterMetadata _staticCommandParameterMetadata; /// @@ -611,6 +618,7 @@ internal bool ImplementsDynamicParameters { get { return _implementsDynamicParameters; } } + private bool _implementsDynamicParameters; /// @@ -619,8 +627,10 @@ internal bool ImplementsDynamicParameters internal uint DefaultParameterSetFlag { get { return _defaultParameterSetFlag; } + set { _defaultParameterSetFlag = value; } } + private uint _defaultParameterSetFlag; /// @@ -973,6 +983,7 @@ internal string GetParamBlock() return parameters.ToString(); } + return string.Empty; } @@ -1004,8 +1015,10 @@ internal string GetBeginBlock() {{ $PSBoundParameters['OutBuffer'] = 1 }} + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} + $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($PSCmdlet) }} catch {{ @@ -1024,6 +1037,7 @@ internal string GetBeginBlock() $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} + $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) }} catch {{ @@ -1069,6 +1083,7 @@ internal string GetDynamicParamBlock() $paramDictionary.Add($param.Name, $dynParam) }} }} + return $paramDictionary }} }} catch {{ @@ -1309,6 +1324,7 @@ public static Dictionary GetRestrictedCommands(SessionC { result.Add(restrictedCommand.Name, restrictedCommand); } + return result; } diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index 6b2fb317bf5..8f46b45549e 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -18,6 +18,7 @@ private class Parameter internal string parameterName; internal string parameterText; } + private class Argument { internal Ast ast; @@ -30,8 +31,11 @@ private class Argument private bool _spaceAfterParameter; internal bool SpaceAfterParameter { get { return _spaceAfterParameter; } } + internal bool ParameterNameSpecified { get { return _parameter != null; } } + internal bool ArgumentSpecified { get { return _argument != null; } } + internal bool ParameterAndArgumentSpecified { get { return ParameterNameSpecified && ArgumentSpecified; } } /// @@ -44,6 +48,7 @@ internal string ParameterName Diagnostics.Assert(ParameterNameSpecified, "Caller must verify parameter name was specified"); return _parameter.parameterName; } + set { Diagnostics.Assert(ParameterNameSpecified, "Caller must verify parameter name was specified"); @@ -120,6 +125,7 @@ internal void SetArgumentValue(Ast ast, object value) { _argument = new Argument(); } + _argument.value = value; _argument.ast = ast; } diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 63cedd6c735..39a918d03cb 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -63,6 +63,7 @@ internal CommandPathSearch( // called with the .ps1 extension, so that 'script.ps1' can be called by 'script'. commandPatterns = new[] { commandName, commandName + ".ps1" }; } + _postProcessEnumeratedFiles = CheckAgainstAcceptableCommandNames; _acceptableCommandNames = acceptableCommandNames; } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 1b435ccbd60..933ae90634c 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -129,9 +129,11 @@ internal CmdletParameterBinderController CmdletParameterBinderController { NewParameterBinderController(this.Command); } + return _cmdletParameterBinderController; } } + private CmdletParameterBinderController _cmdletParameterBinderController; /// @@ -141,6 +143,7 @@ internal override ObsoleteAttribute ObsoleteAttribute { get { return _obsoleteAttribute; } } + private ObsoleteAttribute _obsoleteAttribute; /// @@ -391,6 +394,7 @@ internal override void ProcessRecord() { throw; } + exceptionToThrow = rte; } catch (LoopFlowException) @@ -409,6 +413,7 @@ internal override void ProcessRecord() { _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; } + if (exceptionToThrow != null) { // This cmdlet threw an exception, so @@ -653,6 +658,7 @@ private bool ProcessInputPipelineObject(object inputObject) { inputToOperateOn = PSObject.AsPSObject(inputObject); } + Command.CurrentPipelineObject = inputToOperateOn; return this.CmdletParameterBinderController.BindPipelineParameters(inputToOperateOn); @@ -732,6 +738,7 @@ private void Init(CmdletInfo cmdletInformation) throw commandException; } + if (initError != null) { // Log a command health event diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index bc336cb74be..985df26c543 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -74,8 +74,10 @@ internal CommandProcessorBase(CommandInfo commandInfo) internal bool AddedToPipelineAlready { get { return _addedToPipelineAlready; } + set { _addedToPipelineAlready = value; } } + internal bool _addedToPipelineAlready; /// @@ -102,6 +104,7 @@ internal bool AddedToPipelineAlready /// kill current powershell session. /// public bool FromScriptFile { get { return _fromScriptFile; } } + protected bool _fromScriptFile = false; /// @@ -118,6 +121,7 @@ internal bool AddedToPipelineAlready internal InternalCommand Command { get { return _command; } + set { // The command runtime needs to be set up... @@ -132,6 +136,7 @@ internal InternalCommand Command if (value.Context == null && _context != null) value.Context = _context; } + _command = value; } } @@ -153,6 +158,7 @@ internal virtual ObsoleteAttribute ObsoleteAttribute internal MshCommandRuntime CommandRuntime { get { return commandRuntime; } + set { commandRuntime = value; } } @@ -164,8 +170,10 @@ internal MshCommandRuntime CommandRuntime internal bool UseLocalScope { get { return _useLocalScope; } + set { _useLocalScope = value; } } + protected bool _useLocalScope; /// @@ -224,6 +232,7 @@ protected static void ValidateCompatibleLanguageMode( internal ExecutionContext Context { get { return _context; } + set { _context = value; } } @@ -270,6 +279,7 @@ internal static CommandProcessorBase CreateGetHelpCommandProcessor( { throw PSTraceSource.NewArgumentNullException("context"); } + if (string.IsNullOrEmpty(helpTarget)) { throw PSTraceSource.NewArgumentNullException("helpTarget"); @@ -443,6 +453,7 @@ internal void DoPrepare(IDictionary psDefaultParameterValues) // so the scope we created needs to release any resources it hold.s CommandSessionState.RemoveScope(CommandScope); } + throw; } finally @@ -494,6 +505,7 @@ internal virtual void DoBegin() { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } + _context.CurrentCommandProcessor = this; using (commandRuntime.AllowThisCommandToWrite(true)) { @@ -616,6 +628,7 @@ internal void DoComplete() { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } + _context.CurrentCommandProcessor = this; SetCurrentScopeToExecutionScope(); diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 698b371571c..41a34d624dc 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -249,6 +249,7 @@ private CommandInfo SearchForAliases() { currentMatch = GetNextAlias(); } + return currentMatch; } @@ -368,6 +369,7 @@ private CommandInfo ProcessQualifiedFileSystemState() // The enumerator may throw if there are no more matches } } + return currentMatch; } @@ -603,6 +605,7 @@ private CommandInfo GetInfoFromPath(string path) result = new ExternalScriptInfo(scriptName, path, _context); break; } + break; } @@ -706,6 +709,7 @@ private CommandInfo GetNextAlias() result.Name, result.Definition); } + return result; } @@ -832,6 +836,7 @@ private AliasInfo GetAliasFromModules(string command) } } } + return result; } @@ -853,6 +858,7 @@ private CommandInfo GetFunctionFromModules(string command) } } } + return result; } @@ -871,6 +877,7 @@ private PSModuleInfo GetImportedModuleByName(string moduleName) break; } } + if (module == null) { module = modules[0]; @@ -919,6 +926,7 @@ private CommandInfo GetFunction(string function) { result = GetFunctionFromModules(function); } + return result; } @@ -996,6 +1004,7 @@ private CmdletInfo GetNextCmdlet() return traceResult(result); } + private IEnumerator _matchingCmdlet; private static CmdletInfo traceResult(CmdletInfo result) @@ -1007,6 +1016,7 @@ private static CmdletInfo traceResult(CmdletInfo result) result.Name, result.ImplementingType); } + return result; } @@ -1037,6 +1047,7 @@ private string DoPowerShellRelativePathLookup() } } } + return result; } @@ -1212,6 +1223,7 @@ internal Collection ConstructSearchPatternsFromName(string name, bool co { result.Add(name); } + return result; } @@ -1476,6 +1488,7 @@ public void Reset() { _pathSearcher.Reset(); } + _currentMatch = null; _currentState = SearchState.SearchingAliases; _matchingAlias = null; @@ -1485,8 +1498,10 @@ public void Reset() internal CommandOrigin CommandOrigin { get { return _commandOrigin; } + set { _commandOrigin = value; } } + private CommandOrigin _commandOrigin = CommandOrigin.Internal; /// diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 9610400b8e4..4477f837fd8 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -30,6 +30,7 @@ internal CommonParameters(MshCommandRuntime commandRuntime) { throw PSTraceSource.NewArgumentNullException("commandRuntime"); } + _commandRuntime = commandRuntime; } @@ -49,6 +50,7 @@ internal CommonParameters(MshCommandRuntime commandRuntime) public SwitchParameter Verbose { get { return _commandRuntime.Verbose; } + set { _commandRuntime.Verbose = value; } } @@ -65,6 +67,7 @@ public SwitchParameter Verbose public SwitchParameter Debug { get { return _commandRuntime.Debug; } + set { _commandRuntime.Debug = value; } } @@ -79,6 +82,7 @@ public SwitchParameter Debug public ActionPreference ErrorAction { get { return _commandRuntime.ErrorAction; } + set { _commandRuntime.ErrorAction = value; } } @@ -94,6 +98,7 @@ public ActionPreference ErrorAction public ActionPreference WarningAction { get { return _commandRuntime.WarningPreference; } + set { _commandRuntime.WarningPreference = value; } } @@ -108,6 +113,7 @@ public ActionPreference WarningAction public ActionPreference InformationAction { get { return _commandRuntime.InformationPreference; } + set { _commandRuntime.InformationPreference = value; } } @@ -128,6 +134,7 @@ public ActionPreference InformationAction public string ErrorVariable { get { return _commandRuntime.ErrorVariable; } + set { _commandRuntime.ErrorVariable = value; } } @@ -144,6 +151,7 @@ public string ErrorVariable public string WarningVariable { get { return _commandRuntime.WarningVariable; } + set { _commandRuntime.WarningVariable = value; } } @@ -160,6 +168,7 @@ public string WarningVariable public string InformationVariable { get { return _commandRuntime.InformationVariable; } + set { _commandRuntime.InformationVariable = value; } } @@ -178,6 +187,7 @@ public string InformationVariable public string OutVariable { get { return _commandRuntime.OutVariable; } + set { _commandRuntime.OutVariable = value; } } @@ -193,6 +203,7 @@ public string OutVariable public int OutBuffer { get { return _commandRuntime.OutBuffer; } + set { _commandRuntime.OutBuffer = value; } } @@ -211,6 +222,7 @@ public int OutBuffer public string PipelineVariable { get { return _commandRuntime.PipelineVariable; } + set { _commandRuntime.PipelineVariable = value; } } @@ -229,6 +241,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { varName = varName.Substring(1); } + VariablePath silp = new VariablePath(varName); if (!silp.IsVariable) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index ba7f739611e..9982e59a859 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -374,6 +374,7 @@ internal ParameterSetSpecificMetadata GetParameterSetData(uint parameterSetFlag) } } } + return result; } @@ -446,6 +447,7 @@ private void ProcessAttribute( { this.CannotBeNull = true; } + return; } @@ -464,6 +466,7 @@ private void ProcessAttribute( Array.Copy(prevAliasNames, aliases, prevAliasNames.Length); Array.Copy(newAliasNames, 0, aliases, prevAliasNames.Length, newAliasNames.Length); } + return; } @@ -547,6 +550,7 @@ private void ProcessParameterAttribute( { IsPipelineParameterInSomeParameterSet = true; } + if (parameter.Mandatory) { IsMandatoryInSomeParameterSet = true; diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 06b04f92387..6f07a1e3aca 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -334,6 +334,7 @@ private static Exception NewException(Exception e, string errorId, { newParameters[i + 1] = parameters[i]; } + Exception ex = e as TargetInvocationException; if (ex != null) { @@ -344,6 +345,7 @@ private static Exception NewException(Exception e, string errorId, resourceString, newParameters); } + newParameters[0] = e.Message; return new ExtendedTypeSystemException(errorId, e, @@ -739,6 +741,7 @@ internal static ConversionRank GetArgumentConversionRank(object argument, Type p { LanguagePrimitives.FigureCastConversion(fromType, parameterType, ref rank); } + return rank; } @@ -968,10 +971,12 @@ private static int CompareTypeSpecificity(Type type1, Type type2) { result -= 1; } + if (type2.IsGenericParameter) { result += 1; } + return result; } @@ -1257,6 +1262,7 @@ internal static MethodInformation FindBestMethod( } } } + return methodInfo; } @@ -1311,6 +1317,7 @@ private static MethodInformation FindBestMethodImpl( { argumentTypesForTypeInference[parameterIndex] = typeConstraintFromCallSite; } + parameterIndex++; } } @@ -1406,6 +1413,7 @@ private static MethodInformation FindBestMethodImpl( { candidate.conversionRanks[j] = arrayConv; } + if (candidate.conversionRanks[j] == ConversionRank.None) { candidate = null; @@ -1512,11 +1520,13 @@ internal static Type EffectiveArgumentType(object arg) break; } } + if (allSameType) { return firstType.MakeArrayType(); } } + return arg.GetType(); } else @@ -1542,17 +1552,20 @@ internal static void SetReferences(object[] arguments, MethodInformation methodI { continue; } + originalArgumentReference = originalArgumentObj.BaseObject as PSReference; if (originalArgumentReference == null) { continue; } } + ParameterInformation parameter = parameters[i]; if (!parameter.isByRef) { continue; } + object argument = arguments[i]; PSObject.memberResolution.WriteLine("Argument '{0}' was a reference so it will be set to \"{1}\".", i + 1, argument); originalArgumentReference.Value = argument; @@ -1595,6 +1608,7 @@ internal static MethodInformation GetBestMethodAndArguments( { throw new MethodException(errorId, null, errorMsg, methodName, arguments.Length); } + newArguments = GetMethodArgumentsBase(methodName, bestMethod.parameters, arguments, expandParamsOnBest); return bestMethod; } @@ -1612,12 +1626,14 @@ internal static object[] GetMethodArgumentsBase(string methodName, { return Utils.EmptyArray(); } + object[] retValue = new object[parametersLength]; for (int i = 0; i < parametersLength - 1; i++) { ParameterInformation parameter = parameters[i]; SetNewArgument(methodName, arguments, retValue, parameter, i); } + ParameterInformation lastParameter = parameters[parametersLength - 1]; if (!expandParamsOnBest) { @@ -1745,6 +1761,7 @@ internal static object MethodArgumentConvertTo(object valueToConvert, throw new MethodException("RefArgumentToNonRefParameterMsg", null, ExtendedTypeSystem.RefArgumentToNonRefParameter, parameterIndex + 1, typeof(PSReference).FullName, "[ref]"); } + return PropertySetAndMethodArgumentConvertTo(valueToConvert, resultType, formatProvider); } } @@ -1759,17 +1776,20 @@ internal static object UnReference(object obj, out bool isArgumentByRef) isArgumentByRef = true; return reference.Value; } + PSObject mshObj = obj as PSObject; if (mshObj != null) { reference = mshObj.BaseObject as PSReference; } + if (reference != null) { PSObject.memberResolution.WriteLine("Parameter was an PSObject containing a reference."); isArgumentByRef = true; return reference.Value; } + return obj; } @@ -1782,6 +1802,7 @@ internal static object PropertySetAndMethodArgumentConvertTo(object valueToConve { throw PSTraceSource.NewArgumentNullException("resultType"); } + PSObject mshObj = valueToConvert as PSObject; if (mshObj != null) { @@ -1863,11 +1884,13 @@ internal CacheTable() memberCollection = new Collection(); _indexes = new Dictionary(StringComparer.OrdinalIgnoreCase); } + internal void Add(string name, object member) { _indexes[name] = memberCollection.Count; memberCollection.Add(member); } + internal object this[string name] { get @@ -1877,6 +1900,7 @@ internal object this[string name] { return null; } + return this.memberCollection[indexObj]; } } @@ -1903,6 +1927,7 @@ internal string methodDefinition var methodDefn = DotNetAdapter.GetMethodInfoOverloadDefinition(name, method, method.GetParameters().Length - parameters.Length); Interlocked.CompareExchange(ref _cachedMethodDefinition, methodDefn, null); } + return _cachedMethodDefinition; } } @@ -2141,6 +2166,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) localCount += 1; mustStoreRetVal = true; } + locals = new LocalBuilder[localCount]; cLocal = 0; @@ -2166,6 +2192,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) { type = type.GetElementType(); } + locals[cLocal] = emitter.DeclareLocal(type); emitter.Emit(OpCodes.Ldarg_1); @@ -2179,6 +2206,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) { emitter.Emit(OpCodes.Castclass, type); } + emitter.Emit(OpCodes.Stloc, locals[cLocal]); cLocal += 1; @@ -2205,6 +2233,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) _useReflection = true; return null; } + emitter.Emit(OpCodes.Ldarg_0); emitter.Emit(OpCodes.Castclass, type); } @@ -2271,6 +2300,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) { continue; } + if (type.IsByRef) { type = type.GetElementType(); @@ -2493,13 +2523,16 @@ internal ParameterizedPropertyCacheEntry(List properties) { definition.Append(DotNetAdapter.GetMethodInfoOverloadDefinition(this.propertyName, propertySetter, 1)); } + setterList.Add(propertySetter); } + definition.Append(" {"); definition.Append(extraDefinition); definition.Append("}"); definitionArray.Add(definition.ToString()); } + propertyDefinition = definitionArray.ToArray(); this.writeOnly = getterList.Count == 0; @@ -2613,6 +2646,7 @@ private void InitGetter() instance = parameter.Cast(declaringType); } } + Expression getterExpr; if (declaringType.IsGenericTypeDefinition) @@ -2705,6 +2739,7 @@ private void InitSetter() { setterExpr = Expression.Assign(Expression.Field(instance, field), Expression.Convert(value, field.FieldType)); } + _setterDelegate = Expression.Lambda(setterExpr, parameter, value).Compile(); return; } @@ -2729,9 +2764,11 @@ internal GetterDelegate getterDelegate { InitGetter(); } + return _getterDelegate; } } + private GetterDelegate _getterDelegate; internal SetterDelegate setterDelegate @@ -2746,6 +2783,7 @@ internal SetterDelegate setterDelegate return _setterDelegate; } } + private SetterDelegate _setterDelegate; internal bool useReflection; @@ -2765,6 +2803,7 @@ internal AttributeCollection Attributes var objAttributes = this.member.GetCustomAttributes(true); _attributes = new AttributeCollection(objAttributes.Cast().ToArray()); } + return _attributes; } } @@ -2780,12 +2819,14 @@ private static bool SameSignature(MethodBase method1, MethodBase method2) { return false; } + ParameterInfo[] parameters1 = method1.GetParameters(); ParameterInfo[] parameters2 = method2.GetParameters(); if (parameters1.Length != parameters2.Length) { return false; } + for (int i = 0; i < parameters1.Length; ++i) { if (parameters1[i].ParameterType != parameters2[i].ParameterType @@ -2917,6 +2958,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth InterfaceMapping interfaceMapping = type.GetInterfaceMap(interfaceType); methods = interfaceMapping.InterfaceMethods; } + for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++) { MethodInfo interfaceMethodDefinition = methods[methodIndex]; @@ -3036,6 +3078,7 @@ private static bool PropertyAlreadyPresent(List previousProperties break; } } + if (parametersAreSame) { returnValue = true; @@ -3209,6 +3252,7 @@ internal static Type GetFirstPublicParentType(Type type) { return parent; } + parent = parent.BaseType; } @@ -3275,6 +3319,7 @@ private static Dictionary GetStaticEventReflectionTable { return typeTable; } + typeTable = new Dictionary(); PopulateEventReflectionTable(type, typeTable, staticBindingFlags); s_staticEventCacheTable[type] = typeTable; @@ -3297,6 +3342,7 @@ private static CacheTable GetInstancePropertyReflectionTable(Type type) { return typeTable; } + typeTable = new CacheTable(); PopulatePropertyReflectionTable(type, typeTable, instanceBindingFlags); s_instancePropertyCacheTable[type] = typeTable; @@ -3317,6 +3363,7 @@ private static CacheTable GetInstanceMethodReflectionTable(Type type) { return typeTable; } + typeTable = new CacheTable(); PopulateMethodReflectionTable(type, typeTable, instanceBindingFlags); s_instanceMethodCacheTable[type] = typeTable; @@ -3362,6 +3409,7 @@ private static Dictionary GetInstanceEventReflectionTab { return typeTable; } + typeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); PopulateEventReflectionTable(type, typeTable, instanceBindingFlags); s_instanceEventCacheTable[type] = typeTable; @@ -3420,6 +3468,7 @@ internal T GetDotNetProperty(object obj, string propertyName) where T : PSMem return new PSParameterizedProperty(parameterizedPropertyEntry.propertyName, this, obj, parameterizedPropertyEntry) as T; } + return null; } @@ -3439,6 +3488,7 @@ internal T GetDotNetMethod(object obj, string methodName) where T : PSMemberI { return null; } + var isCtor = methods[0].method is ConstructorInfo; bool isSpecial = !isCtor && methods[0].method.IsSpecialName; bool isHidden = false; @@ -3450,6 +3500,7 @@ internal T GetDotNetMethod(object obj, string methodName) where T : PSMemberI break; } } + return PSMethod.Create(methods[0].method.Name, this, obj, methods, isSpecial, isHidden) as T; } @@ -3526,6 +3577,7 @@ internal void AddAllMethods(object obj, PSMemberInfoInternalCollection mem break; } } + members.Add(PSMethod.Create(name, this, obj, method, isSpecial, isHidden) as T); } } @@ -3558,6 +3610,7 @@ internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection { return; } + if (!typeof(T).IsAssignableFrom(typeof(PSDynamicMember))) { return; @@ -3576,6 +3629,7 @@ private static bool PropertyIsStatic(PSProperty property) { return false; } + return entry.isStatic; } @@ -3685,10 +3739,12 @@ protected override string PropertyToString(PSProperty property) { returnValue.Append("get;"); } + if (PropertyIsSettable(property)) { returnValue.Append("set;"); } + returnValue.Append("}"); return returnValue.ToString(); } @@ -3781,6 +3837,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { setValue = PropertySetAndMethodArgumentConvertTo(setValue, propertyInfo.PropertyType, CultureInfo.InvariantCulture); } + if (adapterData.useReflection) { propertyInfo.SetValue(property.baseObject, setValue, null); @@ -3789,6 +3846,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { adapterData.setterDelegate(property.baseObject, setValue); } + return; } @@ -3797,6 +3855,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { setValue = PropertySetAndMethodArgumentConvertTo(setValue, field.FieldType, CultureInfo.InvariantCulture); } + if (adapterData.useReflection) { field.SetValue(property.baseObject, setValue); @@ -3878,6 +3937,7 @@ internal static object AuxiliaryConstructorInvoke(MethodInformation methodInform ExtendedTypeSystem.MethodInvocationException, ".ctor", arguments.Length, e.Message); } + SetReferences(arguments, methodInformation, originalArguments); return returnValue; #pragma warning restore 56500 @@ -3970,6 +4030,7 @@ internal static MethodInformation[] GetMethodInformationArray(MethodBase[] metho { returnValue[i] = new MethodInformation(methods[i], 0); } + return returnValue; } @@ -4028,6 +4089,7 @@ private static object InvokeResolvedConstructor(MethodInformation bestMethod, ob PSObject.memberResolution.WriteLine("Calling Constructor: {0}", DotNetAdapter.GetMethodInfoOverloadDefinition(null, bestMethod.method, 0)); } + return AuxiliaryConstructorInvoke(bestMethod, newArguments, arguments); } @@ -4072,6 +4134,7 @@ internal static void ParameterizedPropertyInvokeSet(string propertyName, object { finalArguments[i] = newArguments[i]; } + finalArguments[newArguments.Length] = lastArgument; AuxiliaryMethodInvoke(target, finalArguments, bestMethod, arguments); @@ -4084,6 +4147,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method { builder.Append("static "); } + MethodInfo method = methodEntry as MethodInfo; if (method != null) { @@ -4099,11 +4163,13 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method builder.Append(" "); } } + if (methodEntry.DeclaringType.IsInterface) { builder.Append(ToStringCodeMethods.Type(methodEntry.DeclaringType, dropNamespaces: true)); builder.Append("."); } + builder.Append(memberName ?? methodEntry.Name); if (methodEntry.IsGenericMethodDefinition) { @@ -4113,11 +4179,13 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method for (int i = 0; i < genericArgs.Length; i++) { if (i > 0) { builder.Append(", "); } + builder.Append(ToStringCodeMethods.Type(genericArgs[i])); } builder.Append("]"); } + builder.Append("("); System.Reflection.ParameterInfo[] parameters = methodEntry.GetParameters(); int parametersLength = parameters.Length - parametersToIgnore; @@ -4132,6 +4200,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method builder.Append("[ref] "); parameterType = parameterType.GetElementType(); } + if (parameterType.IsArray && (i == parametersLength - 1)) { // The extension method 'CustomAttributeExtensions.GetCustomAttributes(ParameterInfo, Type, Boolean)' has inconsistent @@ -4144,13 +4213,16 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method if (paramArrayAttrs != null && paramArrayAttrs.Any()) builder.Append("Params "); } + builder.Append(ToStringCodeMethods.Type(parameterType)); builder.Append(" "); builder.Append(parameter.Name); builder.Append(", "); } + builder.Remove(builder.Length - 2, 2); } + builder.Append(")"); return builder.ToString(); @@ -4277,6 +4349,7 @@ protected override Collection ParameterizedPropertyDefinitions(PSParamet { returnValue.Add(adapterData.propertyDefinition[i]); } + return returnValue; } @@ -4294,6 +4367,7 @@ protected override string ParameterizedPropertyToString(PSParameterizedProperty returnValue.Append(definitions[i]); returnValue.Append(", "); } + returnValue.Remove(returnValue.Length - 2, 2); return returnValue.ToString(); } @@ -4370,6 +4444,7 @@ protected override T GetMember(object obj, string memberName) return parameterizedProperty as T; } } + return null; } } @@ -4395,6 +4470,7 @@ protected override IEnumerable GetTypeNameHierarchy(object obj) { yield return ComAdapter.GetComTypeName(_comTypeInfo.Clsid); } + yield return type.FullName; } } @@ -4576,6 +4652,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) returnValue.Add(memberAsT); } } + return returnValue; } @@ -4633,6 +4710,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) returnValue.Add(memberAsT); } } + return returnValue; } @@ -4711,6 +4789,7 @@ protected override T GetMember(object obj, string memberName) return returnValue; } } + if (IsTypeParameterizedProperty(typeof(T))) { PSParameterizedProperty parameterizedProperty = base.GetDotNetProperty(obj, memberName); @@ -4721,6 +4800,7 @@ protected override T GetMember(object obj, string memberName) return parameterizedProperty as T; } } + return null; } @@ -4743,6 +4823,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) { DoAddAllProperties(obj, returnValue); } + base.AddAllMethods(obj, returnValue, true); if (IsTypeParameterizedProperty(typeof(T))) { @@ -4760,6 +4841,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) } } } + return returnValue; } } @@ -4800,6 +4882,7 @@ protected override IEnumerable GetTypeNameHierarchy(object obj) firstType.Append(node.LocalName); yield return firstType.ToString(); } + yield return baseType; } } @@ -4826,6 +4909,7 @@ protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCo nodeList = new List(); nodeArrays[attribute.LocalName] = nodeList; } + nodeList.Add(attribute); } } @@ -4846,6 +4930,7 @@ protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCo nodeList = new List(); nodeArrays[childNode.LocalName] = nodeList; } + nodeList.Add(childNode); } } @@ -4870,6 +4955,7 @@ protected override PSProperty DoGetProperty(object obj, string propertyName) { return null; } + return new PSProperty(nodes[0].LocalName, this, obj, nodes); } @@ -4886,20 +4972,24 @@ protected override bool PropertyIsSettable(PSProperty property) { return false; } + XmlNode node = nodes[0]; if (node is XmlText) { return true; } + if (node is XmlAttribute) { return true; } + XmlAttributeCollection nodeAttributes = node.Attributes; if ((nodeAttributes != null) && (nodeAttributes.Count != 0)) { return false; } + XmlNodeList nodeChildren = node.ChildNodes; if ((nodeChildren == null) || (nodeChildren.Count == 0)) { @@ -4910,6 +5000,7 @@ protected override bool PropertyIsSettable(PSProperty property) { return true; } + return false; } @@ -5063,6 +5154,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) catch (GetValueException) { } + var type = value == null ? typeof(object) : value.GetType(); return forDisplay ? ToStringCodeMethods.Type(type) : type.FullName; } @@ -5259,6 +5351,7 @@ protected override PSProperty DoGetProperty(object obj, string propertyName) { return null; } + string columnName = dataRowView.Row.Table.Columns[propertyName].ColumnName; return new PSProperty(columnName, this, obj, columnName); } @@ -5579,6 +5672,7 @@ private bool Unify(Type parameterType, Type argumentType) inferenceCandidates = new HashSet(); _typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition] = inferenceCandidates; } + inferenceCandidates.Add(argumentType); s_tracer.WriteLine("Inferred {0} => {1}", parameterType, argumentType); return true; @@ -5675,6 +5769,7 @@ private bool UnifyConstructedType(Type parameterType, Type argumentType) { return UnifyConstructedType(parameterType, baseType); } + baseType = baseType.BaseType; } diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 84e94a694be..0eb55d4eb30 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -97,11 +97,13 @@ public static GetSymmetricEncryptionKey GetSymmetricEncryptionKeyDelegate { return s_delegate; } + set { s_delegate = value; } } + private static GetSymmetricEncryptionKey s_delegate = null; /// diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 1aa19849c31..c1c58ea50a1 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -42,6 +42,7 @@ public string CurrentLocation { return _currentWorkingDirectory; } + set { _currentWorkingDirectory = value; @@ -97,6 +98,7 @@ public string Root { return _root; } + internal set { _root = value; @@ -697,6 +699,7 @@ public bool Equals(PSDriveInfo drive) { return drive1.Equals(drive2); } + return true; } else @@ -821,6 +824,7 @@ internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); } + return _noteProperty; } } diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 9b7d1b2afe5..14cc27c0fe7 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -68,6 +68,7 @@ internal string FullName this.ModuleName, this.Name); } + return result; } } @@ -89,6 +90,7 @@ internal string PSSnapInName { result = PSSnapIn.Name; } + return result; } } @@ -106,6 +108,7 @@ internal string ApplicationBase { psHome = null; } + return psHome; } } @@ -169,9 +172,11 @@ public Provider.ProviderCapabilities Capabilities // Assume no capabilities for now } } + return _capabilities; } } + private ProviderCapabilities _capabilities = ProviderCapabilities.None; private bool _capabilitiesRead; @@ -442,6 +447,7 @@ internal bool NameEquals(string providerName) // If only the provider name is specified, then only the name must match result = String.Equals(providerName, Name, StringComparison.OrdinalIgnoreCase); } + return result; } @@ -482,6 +488,7 @@ internal bool IsMatch(WildcardPattern namePattern, PSSnapinQualifiedName psSnapi result = true; } } + return result; } @@ -586,6 +593,7 @@ internal Provider.CmdletProvider CreateInstance() "ProviderNotFoundInAssembly", SessionStateStrings.ProviderNotFoundInAssembly); } + throw e; } @@ -613,12 +621,14 @@ internal void GetOutputTypes(string cmdletname, List listToAppend) { continue; } + List l; if (!_providerOutputType.TryGetValue(outputType.ProviderCmdlet, out l)) { l = new List(); _providerOutputType[outputType.ProviderCmdlet] = l; } + l.AddRange(outputType.Type); } } @@ -629,6 +639,7 @@ internal void GetOutputTypes(string cmdletname, List listToAppend) listToAppend.AddRange(cmdletOutputType); } } + private Dictionary> _providerOutputType; private PSNoteProperty _noteProperty; @@ -639,6 +650,7 @@ internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); } + return _noteProperty; } } diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index f97e8b57fde..bdbac44b248 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -243,6 +243,7 @@ public object OperandValue { return _operandValue; } + set { _operandValue = value; @@ -280,6 +281,7 @@ internal override bool Eval(object val) long operandValue = (long)LanguagePrimitives.ConvertTo(_operandValue, typeof(long), CultureInfo.InvariantCulture); satisfy = (operandValue == (valueToCheck & operandValue)); } + return satisfy; } @@ -301,6 +303,7 @@ internal override bool ExistEnum(object enumVal) long operandValue = (long)LanguagePrimitives.ConvertTo(_operandValue, typeof(long), CultureInfo.InvariantCulture); exist = valueToCheck == (valueToCheck & operandValue); } + return exist; } @@ -394,6 +397,7 @@ private List TokenizeInput(string input) tokenList.Add(GetNextToken(input, ref _offset)); } } + return tokenList; } @@ -452,6 +456,7 @@ private Token GetNextToken(string input, ref int _offset) { _offset--; } + break; } else @@ -489,6 +494,7 @@ private Token GetNextToken(string input, ref int _offset) null, "NoIdentifierGroupingAllowed", EnumExpressionEvaluatorStrings.NoIdentifierGroupingAllowed); } } + if (result.Equals(",")) { return (new Token(TokenKind.Or)); @@ -558,6 +564,7 @@ private void CheckSyntaxError(List tokenList) string text = token.Text; token.Text = EnumMinimumDisambiguation.EnumDisambiguate(text, typeof(T)); } + previous = token.Kind; } } @@ -612,6 +619,7 @@ private Node ConstructExpressionTree(List tokenList) andNode.Operand1 = andQueue.Dequeue(); andCurrent = andNode; } + orQueue.Enqueue(andCurrent); } } @@ -625,6 +633,7 @@ private Node ConstructExpressionTree(List tokenList) orNode.Operand1 = orQueue.Dequeue(); orCurrent = orNode; } + return orCurrent; } diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 48931e635e1..b2d308f610d 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -90,6 +90,7 @@ internal static string EnumDisambiguate(string text, Type enumType) matchListSB.Append(separator); matchListSB.Append(namesWithMatchingPrefix[i]); } + throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "MultipleEnumNameMatch", EnumExpressionEvaluatorStrings.MultipleEnumNameMatch, text, matchListSB.ToString()); @@ -113,8 +114,10 @@ internal static string EnumAllValues(Type enumType) returnValue.Append(names[i]); returnValue.Append(separator); } + returnValue.Remove(returnValue.Length - separator.Length, separator.Length); } + return returnValue.ToString(); } diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 5d551394dcb..d90fe000de9 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -233,8 +233,10 @@ public string Activity { return _errorRecord.InvocationInfo.MyCommand.Name; } + return string.Empty; } + set { _errorRecord._activityOverride = value; @@ -262,8 +264,10 @@ public string Reason _reasonIsExceptionType = true; return _errorRecord.Exception.GetType().Name; } + return string.Empty; } + set { _errorRecord._reasonOverride = value; @@ -302,8 +306,10 @@ public string TargetName return ErrorRecord.NotNull(targetInString); } + return string.Empty; } + set { _errorRecord._targetNameOverride = value; @@ -330,8 +336,10 @@ public string TargetType { return _errorRecord.TargetObject.GetType().Name; } + return string.Empty; } + set { _errorRecord._targetTypeOverride = value; @@ -401,6 +409,7 @@ public string GetMessage(CultureInfo uiCultureInfo) // this probably indicates an invalid ErrorCategory value errorCategoryString = ErrorCategory.NotSpecified.ToString(); } + string templateText = ErrorCategoryStrings.ResourceManager.GetString(errorCategoryString, uiCultureInfo); if (String.IsNullOrEmpty(templateText)) @@ -408,6 +417,7 @@ public string GetMessage(CultureInfo uiCultureInfo) // this probably indicates an invalid ErrorCategory value templateText = ErrorCategoryStrings.NotSpecified; } + Diagnostics.Assert(!String.IsNullOrEmpty(templateText), "ErrorCategoryStrings.resx resource failure"); @@ -734,6 +744,7 @@ public string Message { get { return ErrorRecord.NotNull(_message); } } + private string _message = string.Empty; /// @@ -749,11 +760,13 @@ public string Message public string RecommendedAction { get { return ErrorRecord.NotNull(_recommendedAction); } + set { _recommendedAction = value; } } + private string _recommendedAction = string.Empty; #endregion Public Properties @@ -761,8 +774,10 @@ public string RecommendedAction internal Exception TextLookupError { get { return _textLookupError; } + set { _textLookupError = value; } } + private Exception _textLookupError /* = null */; #endregion Internal Properties @@ -809,8 +824,10 @@ private string BuildMessage( _textLookupError = e; return string.Empty; // fallback to Exception.Message } + return BuildMessage(template, baseName, resourceId, args); } + private string BuildMessage( IResourceSupplier resourceSupplier, string baseName, @@ -842,8 +859,10 @@ private string BuildMessage( _textLookupError = e; return string.Empty; // fallback to Exception.Message } + return BuildMessage(template, baseName, resourceId, args); } + private string BuildMessage( System.Reflection.Assembly assembly, string baseName, @@ -875,8 +894,10 @@ private string BuildMessage( _textLookupError = e; return string.Empty; // fallback to Exception.Message } + return BuildMessage(template, baseName, resourceId, args); } + private string BuildMessage( string template, string baseName, @@ -1120,6 +1141,7 @@ private void PopulateProperties(Exception exception, { throw PSTraceSource.NewArgumentNullException("exception"); } + if (fullyQualifiedErrorId == null) { throw PSTraceSource.NewArgumentNullException("fullyQualifiedErrorId"); @@ -1144,6 +1166,7 @@ private void PopulateProperties(Exception exception, _errorDetails.RecommendedAction = errorDetails_RecommendedAction; } } + _scriptStackTrace = errorDetails_ScriptStackTrace; } @@ -1368,6 +1391,7 @@ public ErrorRecord(ErrorRecord errorRecord, { _error = errorRecord.Exception; } + _target = errorRecord.TargetObject; _errorId = errorRecord._errorId; _category = errorRecord._category; @@ -1416,6 +1440,7 @@ public Exception Exception return _error; } } + private Exception _error /* = null */; /// @@ -1426,6 +1451,7 @@ public object TargetObject { get { return _target; } } + private object _target /* = null */; internal void SetTargetObject(object target) { @@ -1442,6 +1468,7 @@ public ErrorCategoryInfo CategoryInfo { get { return _categoryInfo ?? (_categoryInfo = new ErrorCategoryInfo(this)); } } + private ErrorCategoryInfo _categoryInfo; /// @@ -1483,8 +1510,10 @@ public string FullyQualifiedErrorId public ErrorDetails ErrorDetails { get { return _errorDetails; } + set { _errorDetails = value; } } + private ErrorDetails _errorDetails; /// @@ -1496,6 +1525,7 @@ public InvocationInfo InvocationInfo { get { return _invocationInfo; } } + private InvocationInfo _invocationInfo /* = null */; internal void SetInvocationInfo(InvocationInfo invocationInfo) @@ -1543,8 +1573,10 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) internal bool PreserveInvocationInfoOnce { get { return _preserveInvocationInfoOnce; } + set { _preserveInvocationInfoOnce = value; } } + private bool _preserveInvocationInfoOnce /* = false */; /// @@ -1554,6 +1586,7 @@ public string ScriptStackTrace { get { return _scriptStackTrace; } } + private string _scriptStackTrace; internal void LockScriptStackTrace() @@ -1575,6 +1608,7 @@ internal void LockScriptStackTrace() { sb.Append(Environment.NewLine); } + first = false; sb.Append(frame.ToString()); } @@ -1593,6 +1627,7 @@ public ReadOnlyCollection PipelineIterationInfo return _pipelineIterationInfo; } } + private ReadOnlyCollection _pipelineIterationInfo = Utils.EmptyReadOnlyCollection(); /// @@ -1604,11 +1639,13 @@ internal bool SerializeExtendedInfo { return _serializeExtendedInfo; } + set { _serializeExtendedInfo = value; } } + private bool _serializeExtendedInfo = false; #endregion Public Properties @@ -1660,14 +1697,17 @@ public override string ToString() { return ErrorDetails.Message; } + if (Exception != null) { if (!String.IsNullOrEmpty(Exception.Message)) { return Exception.Message; } + return Exception.ToString(); } + return base.ToString(); } #endregion ToString diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 9a8706fd210..61a1f9091b2 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -780,6 +780,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, Object source, s subscribers = new List(); _engineEventSubscribers.Add(engineEventSourceIdentifier, subscribers); } + subscribers.Add(subscriber); // This subscriber is the only one in the idle event list, we enable the timer @@ -828,6 +829,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) // Already unsubscribed by another thread or the subscriber doesn't exist return; } + subscriber.IsBeingUnsubscribed = true; } @@ -944,6 +946,7 @@ protected internal override void ProcessNewEvent(PSEventArgs newEvent, { this.ProcessPendingActions(); } + waitHandle.Dispose(); } } @@ -986,6 +989,7 @@ private void ProcessNewEventImplementation(PSEventArgs newEvent, bool processSyn { actionsHandledInCurrentThread.Add(subscriber); } + capturedEvent = true; } else @@ -1030,6 +1034,7 @@ private void AddAction(EventAction action, bool processSynchronously) // This mutex will get set after the event is processed. action.Args.EventProcessed = new ManualResetEventSlim(); } + lock (((System.Collections.ICollection)_actionQueue).SyncRoot) { // If the engine isn't active, pulse the pipeline. @@ -1236,6 +1241,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) { _context.EngineSessionState = nextAction.Sender.Action.ScriptBlock.SessionStateInternal; } + Runspace oldDefault = Runspace.DefaultRunspace; try @@ -1275,6 +1281,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) { eventProcessed.Set(); } + Runspace.DefaultRunspace = oldDefault; _context.EngineSessionState = oldSessionState; _processingAction = null; @@ -2523,6 +2530,7 @@ public override bool HasMoreData return _moreData; } } + private bool _moreData = false; /// diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 5935feb36b4..82363052a8c 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -42,6 +42,7 @@ internal ScriptDebugger Debugger { get { return _debugger; } } + internal ScriptDebugger _debugger; internal int _debuggingMode; @@ -60,11 +61,13 @@ internal void ResetManagers() { Events.Dispose(); } + Events = new PSLocalEventManager(this); if (this.transactionManager != null) { this.transactionManager.Dispose(); } + this.transactionManager = new PSTransactionManager(); } /// @@ -78,8 +81,10 @@ internal int PSDebugTraceLevel // Pretend that tracing is off if ignoreScriptDebug is true return IgnoreScriptDebug ? 0 : _debugTraceLevel; } + set { _debugTraceLevel = value; } } + private int _debugTraceLevel; /// @@ -93,8 +98,10 @@ internal bool PSDebugTraceStep // Pretend that tracing is off if ignoreScriptDebug is true return !IgnoreScriptDebug && _debugTraceStep; } + set { _debugTraceStep = value; } } + private bool _debugTraceStep; // Helper for generated code to handle running w/ no execution context @@ -104,6 +111,7 @@ internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) { context = LocalPipeline.GetExecutionContextFromTLS(); } + return (context != null) ? context.IsStrictVersion(majorVersion) : false; @@ -131,6 +139,7 @@ internal bool IsStrictVersion(int majorVersion) { break; } + scope = scope.Parent; } @@ -214,6 +223,7 @@ internal void ReleaseResponsibilityForModuleAnalysisAppDomain() AppDomain.Unload(AppDomainForModuleAnalysis); AppDomainForModuleAnalysis = null; } + _responsibilityForModuleAnalysisAppDomainOwned = false; } @@ -242,9 +252,11 @@ internal ProviderNames ProviderNames { _providerNames = new SingleShellProviderNames(); } + return _providerNames; } } + private ProviderNames _providerNames; /// @@ -273,9 +285,11 @@ internal string ShellID _shellId = Utils.DefaultPowerShellShellID; } } + return _shellId; } } + private string _shellId; /// @@ -309,6 +323,7 @@ internal PSLanguageMode LanguageMode { return _languageMode; } + set { // If we're moving to ConstrainedLanguage, invalidate the binding @@ -356,6 +371,7 @@ internal PSLanguageMode LanguageMode _languageMode = value; } } + private PSLanguageMode _languageMode = PSLanguageMode.FullLanguage; /// @@ -395,6 +411,7 @@ internal static bool IsMarkedAsUntrusted(object value) object unused; result = UntrustedObjects.TryGetValue(baseValue, out unused); } + return result; } @@ -499,6 +516,7 @@ internal LocationGlobber LocationGlobber return _locationGlobber; } } + private LocationGlobber _locationGlobber; /// @@ -625,6 +643,7 @@ internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool def defaultUsed = true; return defaultPref; } + bool converted = defaultPref; defaultUsed = !LanguagePrimitives.TryConvertTo (val, out converted); @@ -642,6 +661,7 @@ internal HelpSystem HelpSystem { get { return _helpSystem ?? (_helpSystem = new HelpSystem(this)); } } + private HelpSystem _helpSystem; #endregion @@ -718,6 +738,7 @@ internal EngineIntrinsics EngineIntrinsics { get { return _engineIntrinsics ?? (_engineIntrinsics = new EngineIntrinsics(this)); } } + private EngineIntrinsics _engineIntrinsics; /// @@ -788,6 +809,7 @@ internal Pipe RedirectErrorPipe(Pipe newPipe) ShellFunctionErrorOutputPipe = newPipe; return oldPipe; } + internal void RestoreErrorPipe(Pipe pipe) { ShellFunctionErrorOutputPipe = pipe; @@ -882,6 +904,7 @@ internal void AppendDollarError(object obj) maxErrorCount - 1, numToErase); } + arraylist.Insert(0, obj); } #endregion @@ -919,6 +942,7 @@ internal static void CheckStackDepth() internal Runspace CurrentRunspace { get { return _currentRunspace; } + set { _currentRunspace = value; } } @@ -1009,6 +1033,7 @@ internal object DollarErrorVariable return resultItem; } + set { EngineSessionState.SetVariable( @@ -1026,6 +1051,7 @@ internal ActionPreference DebugPreferenceVariable InitialSessionState.defaultDebugPreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1046,6 +1072,7 @@ internal ActionPreference VerbosePreferenceVariable InitialSessionState.defaultVerbosePreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1066,6 +1093,7 @@ internal ActionPreference ErrorActionPreferenceVariable InitialSessionState.defaultErrorActionPreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1086,6 +1114,7 @@ internal ActionPreference WarningActionPreferenceVariable InitialSessionState.defaultWarningPreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1106,6 +1135,7 @@ internal ActionPreference InformationActionPreferenceVariable InitialSessionState.defaultInformationPreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1130,6 +1160,7 @@ internal object WhatIfPreferenceVariable return resultItem; } + set { this.EngineSessionState.SetVariable( @@ -1150,6 +1181,7 @@ internal ConfirmImpact ConfirmPreferenceVariable InitialSessionState.defaultConfirmPreference, out defaultUsed); } + set { this.EngineSessionState.SetVariable( @@ -1168,15 +1200,18 @@ internal void RunspaceClosingNotification() { _debugger.Dispose(); } + if (Events != null) { Events.Dispose(); } + Events = null; if (this.transactionManager != null) { this.transactionManager.Dispose(); } + this.transactionManager = null; } @@ -1192,8 +1227,10 @@ internal TypeTable TypeTable _typeTable = new TypeTable(); _typeTableWeakReference = new WeakReference(_typeTable); } + return _typeTable; } + set { _typeTable = value; @@ -1212,6 +1249,7 @@ internal WeakReference TypeTableWeakReference { var unused = TypeTable; } + return _typeTableWeakReference; } } @@ -1239,6 +1277,7 @@ internal TypeInfoDataBaseManager FormatDBManager _formatDBManager.DisableFormatTableUpdates = this.InitialSessionState.DisableFormatUpdates; } } + return _formatDBManager; } @@ -1247,6 +1286,7 @@ internal TypeInfoDataBaseManager FormatDBManager _formatDBManager = value; } } + private TypeInfoDataBaseManager _formatDBManager; /// @@ -1260,6 +1300,7 @@ internal PSTransactionManager TransactionManager return transactionManager; } } + internal PSTransactionManager transactionManager; internal Assembly AddAssembly(string name, string filename, out Exception error) @@ -1283,6 +1324,7 @@ internal Assembly AddAssembly(string name, string filename, out Exception error) // we should ignore this assembly. return loadedAssembly; } + AssemblyCache.Add(loadedAssembly.GetName().Name, loadedAssembly); return loadedAssembly; } @@ -1373,6 +1415,7 @@ internal static Assembly LoadAssembly(string name, string filename, out Exceptio { error = null; } + return loadedAssembly; } @@ -1612,6 +1655,7 @@ private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveE return assembly; } } + return null; } #endif diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index ae6c1e8f966..4e98d556c3d 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -599,9 +599,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidArgument, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "PSInvalidCastException"; } diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 13466039096..c8b79d690f0 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -138,6 +138,7 @@ public string Path { get { return _path; } } + private readonly string _path = String.Empty; /// @@ -190,6 +191,7 @@ public override SessionStateEntryVisibility Visibility return Context.EngineSessionState.CheckScriptVisibility(_path); } + set { throw PSTraceSource.NewNotImplementedException(); } } @@ -217,6 +219,7 @@ public ScriptBlock ScriptBlock return _scriptBlock; } + private set { _scriptBlock = value; @@ -226,6 +229,7 @@ private set } } } + private ScriptBlock _scriptBlock; private ScriptBlockAst _scriptBlockAst; @@ -261,10 +265,12 @@ internal ScriptBlockAst GetScriptBlockAst() { this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents); } + if (_scriptBlock != null) { return (ScriptBlockAst)_scriptBlock.Ast; } + if (_scriptBlockAst == null) { ParseError[] errors; @@ -298,6 +304,7 @@ internal ScriptBlockAst GetScriptBlockAst() ScriptBlock.CacheScriptBlock(_scriptBlock.Clone(), _path, scriptContents); } } + return _scriptBlockAst; } @@ -338,6 +345,7 @@ internal bool SignatureChecked { set { _signatureChecked = value; } } + private bool _signatureChecked; #region Internal @@ -354,6 +362,7 @@ internal override CommandMetadata CommandMetadata new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } + private CommandMetadata _commandMetadata; /// @@ -467,6 +476,7 @@ public string ScriptContents return _scriptContents; } } + private string _scriptContents; /// @@ -484,6 +494,7 @@ public Encoding OriginalEncoding return _originalEncoding; } } + private Encoding _originalEncoding; private void ReadScriptContents() diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index 9752a8b2a86..bbb894371a5 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -118,6 +118,7 @@ protected override T GetMember(object obj, string memberName) } } } + return null; } @@ -163,6 +164,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) members.Add(new PSProperty(property.PropertyName, this, obj, property) as T); } } + return members; } @@ -284,6 +286,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) catch (GetValueException) { } + var type = value == null ? typeof(object) : value.GetType(); return forDisplay ? ToStringCodeMethods.Type(type) : type.FullName; } @@ -371,6 +374,7 @@ protected override string MethodToString(PSMethod method) returnValue.Append(overload); returnValue.Append(", "); } + returnValue.Remove(returnValue.Length - 2, 2); return returnValue.ToString(); } diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index 12b55a3526e..cb3a4aa2993 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -170,6 +170,7 @@ public ScriptBlock ScriptBlock { get { return _scriptBlock; } } + private ScriptBlock _scriptBlock; /// @@ -367,6 +368,7 @@ public ScopedItemOptions Options } } } + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -391,6 +393,7 @@ public string Description } } } + private string _description = null; /// @@ -403,6 +406,7 @@ public string Verb return _verb; } } + private string _verb = String.Empty; /// @@ -415,6 +419,7 @@ public string Noun return _noun; } } + private string _noun = String.Empty; /// @@ -426,11 +431,13 @@ public string HelpFile { return _helpFile; } + internal set { _helpFile = value; } } + private string _helpFile = String.Empty; /// @@ -477,6 +484,7 @@ internal override CommandMetadata CommandMetadata new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } + private CommandMetadata _commandMetadata; /// diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 138cf459b3e..c7745f56c68 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -64,6 +64,7 @@ public string[] Name } } } + private string[] _names; private bool _nameContainsWildcard; @@ -84,10 +85,12 @@ public string[] Verb { value = Utils.EmptyArray(); } + _verbs = value; _verbPatterns = null; } } + private string[] _verbs = Utils.EmptyArray(); /// @@ -108,10 +111,12 @@ public string[] Noun { value = Utils.EmptyArray(); } + _nouns = value; _nounPatterns = null; } } + private string[] _nouns = Utils.EmptyArray(); /// @@ -133,12 +138,14 @@ public string[] Module { value = Utils.EmptyArray(); } + _modules = value; _modulePatterns = null; _isModuleSpecified = true; } } + private string[] _modules = Utils.EmptyArray(); private bool _isModuleSpecified = false; @@ -160,9 +167,11 @@ public ModuleSpecification[] FullyQualifiedModule { _moduleSpecifications = value; } + _isFullyQualifiedModuleSpecified = true; } } + private ModuleSpecification[] _moduleSpecifications = Utils.EmptyArray(); private bool _isFullyQualifiedModuleSpecified = false; @@ -184,6 +193,7 @@ public CommandTypes CommandType _isCommandTypeSpecified = true; } } + private CommandTypes _commandType = CommandTypes.All; private bool _isCommandTypeSpecified = false; @@ -212,6 +222,7 @@ public SwitchParameter Syntax _usage = value; } } + private bool _usage; /// @@ -239,8 +250,10 @@ public SwitchParameter Syntax public SwitchParameter All { get { return _all; } + set { _all = value; } } + private bool _all; /// @@ -260,6 +273,7 @@ public SwitchParameter ListImported _listImported = value; } } + private bool _listImported; /// @@ -271,6 +285,7 @@ public SwitchParameter ListImported public string[] ParameterName { get { return _parameterNames; } + set { if (value == null) @@ -284,6 +299,7 @@ public string[] ParameterName WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } + private Collection _parameterNameWildcards; private string[] _parameterNames; private HashSet _matchedParameterNames; @@ -300,6 +316,7 @@ public PSTypeName[] ParameterType { return _parameterTypes; } + set { if (value == null) @@ -317,15 +334,19 @@ public PSTypeName[] ParameterType { continue; } + if ((i != 0) && (ptn.Type != null) && (ptn.Type.Equals(typeof(object)))) { continue; } + filteredParameterTypes.Add(ptn); } + _parameterTypes = filteredParameterTypes.ToArray(); } } + private PSTypeName[] _parameterTypes; #endregion Definitions of cmdlet parameters @@ -428,6 +449,7 @@ protected override void EndProcessing() { continue; } + if (_matchedParameterNames.Contains(requestedParameterName)) { continue; @@ -651,6 +673,7 @@ private void AccumulateMatchingCommands() { commandNames.Add("*"); } + AccumulateMatchingCommands(commandNames); } @@ -813,6 +836,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { WriteError(new ErrorRecord(argumentException, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null)); } + continue; } catch (PathTooLongException pathTooLong) @@ -821,6 +845,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { WriteError(new ErrorRecord(pathTooLong, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null)); } + continue; } catch (FileLoadException fileLoadException) @@ -829,6 +854,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { WriteError(new ErrorRecord(fileLoadException, "GetCommandFileLoadError", ErrorCategory.ReadError, null)); } + continue; } catch (MetadataException metadataException) @@ -837,6 +863,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { WriteError(new ErrorRecord(metadataException, "GetCommandMetadataError", ErrorCategory.MetadataError, null)); } + continue; } catch (FormatException formatException) @@ -845,6 +872,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { WriteError(new ErrorRecord(formatException, "GetCommandBadFileFormat", ErrorCategory.InvalidData, null)); } + continue; } @@ -914,6 +942,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN { break; } + _accumulatedResults.Add(c); } // Make sure we don't exceed the TotalCount parameter @@ -1011,6 +1040,7 @@ private bool IsParameterMatch(CommandInfo commandInfo) // ignore all exceptions when getting parameter metadata (i.e. parse exceptions, dangling alias exceptions) // and proceed as if there was no parameter metadata } + if (commandParameters == null) { // do not match commands which have not been imported yet / for which we don't have parameter metadata yet @@ -1027,6 +1057,7 @@ private bool IsParameterMatch(CommandInfo commandInfo) // not breaking out of the loop early, to ensure that _matchedParameterNames gets populated for all command parameters } } + return foundMatchingParameter; } } @@ -1227,6 +1258,7 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) { isDuplicate = true; } + return isCommandMatch; } @@ -1336,6 +1368,7 @@ private bool IsCommandInResult(CommandInfo command) break; } } + return isPresent; } @@ -1436,6 +1469,7 @@ private static PSObject[] GetParameterInfo(ReadOnlyCollection Get() $strPaths += ($ctr.Path + "" :"" + ""`n"") $strPaths += ($ctr.CookedValue.ToString() + ""`n`n"") } + return $strPaths"), null)); yield return td7; #endif diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 0b70d22ae78..5867f4bfe53 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -83,8 +83,10 @@ internal InformationRecord(InformationRecord baseRecord) public List Tags { get { return _tags ?? (_tags = new List()); } + internal set { _tags = value; } } + private List _tags; /// @@ -104,10 +106,13 @@ public string User this._user = System.Security.Principal.WindowsIdentity.GetCurrent().Name; #endif } + return _user; } + set { _user = value; } } + private string _user; /// @@ -117,8 +122,10 @@ public string User public string Computer { get { return this._computerName ?? (this._computerName = PsUtils.GetHostName()); } + set { this._computerName = value; } } + private string _computerName; /// @@ -133,10 +140,13 @@ public uint ProcessId { this._processId = (uint) System.Diagnostics.Process.GetCurrentProcess().Id; } + return this._processId.Value; } + set { _processId = value; } } + private uint? _processId; /// diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8e680f50a1e..d916624e179 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -203,6 +203,7 @@ public SessionStateTypeEntry(TypeTable typeTable) { throw PSTraceSource.NewArgumentNullException("typeTable"); } + TypeTable = typeTable; } @@ -218,6 +219,7 @@ public SessionStateTypeEntry(TypeData typeData, bool isRemove) { throw PSTraceSource.NewArgumentNullException("typeData"); } + TypeData = typeData; IsRemove = isRemove; } @@ -308,6 +310,7 @@ public SessionStateFormatEntry(FormatTable formattable) { throw PSTraceSource.NewArgumentNullException("formattable"); } + Formattable = formattable; } @@ -322,6 +325,7 @@ public SessionStateFormatEntry(ExtendedTypeDefinition typeDefinition) { throw PSTraceSource.NewArgumentNullException("typeDefinition"); } + FormatData = typeDefinition; } @@ -951,6 +955,7 @@ public Collection Attributes { get { return _attributes ?? (_attributes = new Collection()); } } + private Collection _attributes; } @@ -1002,6 +1007,7 @@ public InitialSessionStateEntryCollection Clone() result.Add((T)item.Clone()); } } + return result; } @@ -1037,6 +1043,7 @@ public T this[int index] { result = _internalCollection[index]; } + return result; } } @@ -1063,6 +1070,7 @@ public Collection this[string name] } } } + return result; } } @@ -1675,6 +1683,7 @@ public InitialSessionState Clone() { ss.CoreModulesToImport.Add(mod); } + ss.DisableFormatUpdates = this.DisableFormatUpdates; foreach (var s in this.defaultSnapins) @@ -1786,12 +1795,14 @@ internal bool EnforceInputParameterValidation public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy { get { return _executionPolicy; } + set { _executionPolicy = value; _wasExecutionPolicySet = true; } } + private Microsoft.PowerShell.ExecutionPolicy _executionPolicy = Microsoft.PowerShell.ExecutionPolicy.Default; private bool _wasExecutionPolicySet = false; @@ -1939,6 +1950,7 @@ public virtual InitialSessionStateEntryCollection Ass return _assemblies; } } + private InitialSessionStateEntryCollection _assemblies; /// @@ -1953,6 +1965,7 @@ public virtual InitialSessionStateEntryCollection Types return _types; } } + private InitialSessionStateEntryCollection _types; /// @@ -1966,6 +1979,7 @@ public virtual InitialSessionStateEntryCollection Forma return _formats; } } + private InitialSessionStateEntryCollection _formats; /// @@ -1987,6 +2001,7 @@ public virtual InitialSessionStateEntryCollection Pro return _providers; } } + private InitialSessionStateEntryCollection _providers; /// @@ -2001,6 +2016,7 @@ public virtual InitialSessionStateEntryCollection Comm return _commands; } } + private InitialSessionStateEntryCollection _commands; internal SessionStateEntryVisibility DefaultCommandVisibility { get; set; } @@ -2014,6 +2030,7 @@ internal HashSet UnresolvedCommandsToExpose return _unresolvedCommandsToExpose; } } + private HashSet _unresolvedCommandsToExpose; internal Dictionary CommandModifications @@ -2025,6 +2042,7 @@ internal Dictionary CommandModifications return _commandModifications; } } + private Dictionary _commandModifications; internal List DynamicVariablesToDefine @@ -2036,6 +2054,7 @@ internal List DynamicVariablesToDefine return _dynamicVariablesToDefine; } } + private List _dynamicVariablesToDefine; /// @@ -2049,6 +2068,7 @@ public virtual InitialSessionStateEntryCollection Var return _variables; } } + private InitialSessionStateEntryCollection _variables; /// @@ -2062,6 +2082,7 @@ public virtual InitialSessionStateEntryCollection Env return _environmentVariables; } } + private InitialSessionStateEntryCollection _environmentVariables; /// @@ -2075,6 +2096,7 @@ public virtual HashSet StartupScripts return _startupScripts; } } + private HashSet _startupScripts = new HashSet(); private Object _syncObject = new Object(); @@ -2283,12 +2305,14 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, ss.AddSessionStateEntry(ssfe); continue; } + SessionStateAliasEntry ssae = cmd as SessionStateAliasEntry; if (ssae != null) { ss.AddSessionStateEntry(ssae, StringLiterals.Local); continue; } + SessionStateApplicationEntry ssappe = cmd as SessionStateApplicationEntry; if (ssappe != null) { @@ -2296,8 +2320,10 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, { ss.AddSessionStateEntry(ssappe); } + continue; } + SessionStateScriptEntry ssse = cmd as SessionStateScriptEntry; if (ssse != null) { @@ -2305,6 +2331,7 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, { ss.AddSessionStateEntry(ssse); } + continue; } @@ -2351,6 +2378,7 @@ private void Bind_LoadAssemblies(ExecutionContext context) context.ReportEngineStartupError(error.Message); } } + if (etwEnabled) RunspaceEventSource.Log.LoadAssemblyStop(ssae.Name, ssae.FileName); } @@ -2382,6 +2410,7 @@ HashSet GetPublicCommands() publicCommands.Add(sessionCommand); } } + return publicCommands; } @@ -2924,6 +2953,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( foreach (CommandInfo cmd in LookupCommands(commandToMakeVisible, moduleName, initializedRunspace.ExecutionContext)) { if (!found) { found = true; } + try { // Special case for wild card lookups. @@ -2994,6 +3024,7 @@ private IEnumerable LookupCommands( } if (!found) { found = true; } + yield return commandInfo; // Return first match unless a wild card pattern is submitted. @@ -3035,6 +3066,7 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun { name = Path.Combine(path, name); } + cmd.Parameters.Add("Name", name); } @@ -3305,6 +3337,7 @@ internal void Unbind(ExecutionContext context) context.TopLevelSessionState.RemoveCmdletEntry(ssce.Name, true); } } + continue; } } @@ -3341,6 +3374,7 @@ internal void Unbind(ExecutionContext context) } } } + List formatFilesToRemove = new List(); if (this.Formats != null) { @@ -3373,6 +3407,7 @@ internal static void RemoveTypesAndFormats(ExecutionContext context, IList GetPSSnapIn(string psSnapinName) { loadedSnapins = new List(); } + loadedSnapins.Add(defaultSnapin); } } @@ -3886,8 +3926,10 @@ internal List GetPSSnapIn(string psSnapinName) { loadedSnapins = new List(); } + loadedSnapins.Add(importedSnapin); } + return loadedSnapins; } @@ -3915,6 +3957,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) ArgumentNullException e = new ArgumentNullException("assembly"); throw e; } + Dictionary cmdlets = null; Dictionary> aliases = null; Dictionary providers = null; @@ -4186,6 +4229,7 @@ .FORWARDHELPCATEGORY Cmdlet begin { $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('New-Item', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters } + $steppablePipeline = $scriptCmd.GetSteppablePipeline() $steppablePipeline.Begin($PSCmdlet) } @@ -4218,6 +4262,7 @@ internal static string GetOSTFunctionText() $PSBoundParameters['Stream'] = $true $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-String',[System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } + $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } @@ -4837,11 +4882,13 @@ internal static void AnalyzePSSnapInAssembly( { entry.Item1.SetPSSnapIn(psSnapInInfo); } + var newEntry = (SessionStateCmdletEntry)entry.Item1.Clone(); if (newEntry.PSSnapIn != null && psSnapInInfo == null) { newEntry.SetPSSnapIn(null); } + cmdlets[key] = newEntry; if (entry.Item2 != null) @@ -4859,6 +4906,7 @@ internal static void AnalyzePSSnapInAssembly( { newAliasEntry.SetPSSnapIn(null); } + aliasList.Add(newAliasEntry); } @@ -4879,11 +4927,13 @@ internal static void AnalyzePSSnapInAssembly( { entry.SetPSSnapIn(psSnapInInfo); } + var newEntry = (SessionStateProviderEntry)entry.Clone(); if (newEntry.PSSnapIn != null && psSnapInInfo == null) { newEntry.SetPSSnapIn(null); } + providers[key] = newEntry; } } @@ -4940,6 +4990,7 @@ internal static void AnalyzePSSnapInAssembly( Diagnostics.Assert(false, "Missing provider: " + pair.Key); } } + Diagnostics.Assert(cmdletsCheck.Count == cmdlets.Count, "new Cmdlet added to System.Management.Automation.dll - update InitializeCoreCmdletsAndProviders"); foreach (var pair in cmdletsCheck) @@ -4991,6 +5042,7 @@ internal static void AnalyzePSSnapInAssembly( clone[entry.Key] = new Tuple>((SessionStateCmdletEntry)entry.Value.Clone(), aliasesCloneList); } + s_cmdletCache.Value[assembly] = clone; } @@ -5001,6 +5053,7 @@ internal static void AnalyzePSSnapInAssembly( { clone[entry.Key] = (SessionStateProviderEntry)entry.Value.Clone(); } + s_providerCache.Value[assembly] = clone; } } @@ -5042,6 +5095,7 @@ private static void AnalyzeModuleAssemblyWithReflection( SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmdletName, type, helpFile); if (psSnapInInfo != null) { cmdlet.SetPSSnapIn(psSnapInInfo); } + if (moduleInfo != null) { cmdlet.SetModule(moduleInfo); } cmdlets = cmdlets ?? new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -5059,9 +5113,12 @@ private static void AnalyzeModuleAssemblyWithReflection( // ('ScopedItemOptions.ReadOnly' and/or 'ScopedItemOptions.AllScopes'). var aliasEntry = new SessionStateAliasEntry(alias, cmdletName, description: string.Empty, ScopedItemOptions.None); if (psSnapInInfo != null) { aliasEntry.SetPSSnapIn(psSnapInInfo); } + if (moduleInfo != null) { aliasEntry.SetModule(moduleInfo); } + aliasList.Add(aliasEntry); } + aliases.Add(cmdletName, aliasList); } @@ -5087,6 +5144,7 @@ private static void AnalyzeModuleAssemblyWithReflection( SessionStateProviderEntry provider = new SessionStateProviderEntry(providerName, type, helpFile); if (psSnapInInfo != null) { provider.SetPSSnapIn(psSnapInInfo); } + if (moduleInfo != null) { provider.SetModule(moduleInfo); } providers = providers ?? new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -5273,37 +5331,62 @@ private static string GetHelpFile(string assemblyPath) } // Guid is {15d4c170-2f29-5689-a0e2-d95b0c7b4ea0} + [EventSource(Name = "Microsoft-PowerShell-Runspaces")] internal class RunspaceEventSource : EventSource { internal static RunspaceEventSource Log = new RunspaceEventSource(); public void OpenRunspaceStart() { WriteEvent(1); } + public void OpenRunspaceStop() { WriteEvent(2); } + public void LoadAssembliesStart() { WriteEvent(3); } + public void LoadAssembliesStop() { WriteEvent(4); } + public void UpdateFormatTableStart() { WriteEvent(5); } + public void UpdateFormatTableStop() { WriteEvent(6); } + public void UpdateTypeTableStart() { WriteEvent(7); } + public void UpdateTypeTableStop() { WriteEvent(8); } + public void LoadProvidersStart() { WriteEvent(9); } + public void LoadProvidersStop() { WriteEvent(10); } + public void LoadCommandsStart() { WriteEvent(11); } + public void LoadCommandsStop() { WriteEvent(12); } + public void LoadVariablesStart() { WriteEvent(13); } + public void LoadVariablesStop() { WriteEvent(14); } + public void LoadEnvironmentVariablesStart() { WriteEvent(15); } + public void LoadEnvironmentVariablesStop() { WriteEvent(16); } public void LoadAssemblyStart(string Name, string FileName) { WriteEvent(17, Name, FileName); } + public void LoadAssemblyStop(string Name, string FileName) { WriteEvent(18, Name, FileName); } + public void ProcessFormatFileStart(string FileName) { WriteEvent(19, FileName); } + public void ProcessFormatFileStop(string FileName) { WriteEvent(20, FileName); } + public void ProcessTypeFileStart(string FileName) { WriteEvent(21, FileName); } + public void ProcessTypeFileStop(string FileName) { WriteEvent(22, FileName); } + public void LoadProviderStart(string Name) { WriteEvent(23, Name); } + public void LoadProviderStop(string Name) { WriteEvent(24, Name); } + public void LoadCommandStart(string Name) { WriteEvent(25, Name); } + public void LoadCommandStop(string Name) { WriteEvent(26, Name); } } } diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 6a8ed896dc9..617f83318e8 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -69,8 +69,10 @@ public sealed class ForEachObjectCommand : PSCmdlet public PSObject InputObject { set { _inputObject = value; } + get { return _inputObject; } } + private PSObject _inputObject = AutomationNull.Value; #region ScriptBlockSet @@ -87,6 +89,7 @@ public ScriptBlock Begin { _scripts.Insert(0, value); } + get { return null; @@ -108,6 +111,7 @@ public ScriptBlock[] Process else _scripts.AddRange(value); } + get { return null; @@ -127,6 +131,7 @@ public ScriptBlock End _endScript = value; _setEndScript = true; } + get { return _endScript; @@ -149,6 +154,7 @@ public ScriptBlock[] RemainingScripts else _scripts.AddRange(value); } + get { return null; } } @@ -167,8 +173,10 @@ public ScriptBlock[] RemainingScripts public string MemberName { set { _propertyOrMethodName = value; } + get { return _propertyOrMethodName; } } + private string _propertyOrMethodName; private string _targetString; private DynamicPropertyGetter _propGetter; @@ -183,8 +191,10 @@ public string MemberName public object[] ArgumentList { set { _arguments = value; } + get { return _arguments; } } + private object[] _arguments; #endregion PropertyAndMethodSet @@ -301,6 +311,7 @@ protected override void ProcessRecord() args: Utils.EmptyArray()); } } + break; case "PropertyAndMethodSet": @@ -340,6 +351,7 @@ protected override void ProcessRecord() } } } + return; } @@ -378,6 +390,7 @@ protected override void ProcessRecord() _propertyOrMethodName, possibleMatches)); return; } + if (members.Count == 1) { member = members[0]; @@ -404,6 +417,7 @@ protected override void ProcessRecord() { WriteObject(member.Value); } + return; } @@ -601,6 +615,7 @@ private void MethodCallWithArguments() { possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); } + WriteError(GenerateNameParameterError("Name", InternalCommandStrings.AmbiguousMethodName, "AmbiguousMethodName", _inputObject, _propertyOrMethodName, possibleMatches)); @@ -622,6 +637,7 @@ private void MethodCallWithArguments() { arglist.AppendFormat(CultureInfo.InvariantCulture, ", {0}", GetStringRepresentation(_arguments[i])); } + string methodAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectMethodActionWithArguments, targetMethod.Name, arglist); @@ -697,6 +713,7 @@ private bool GetValueFromIDictionaryInput() object result = hash[_propertyOrMethodName]; WriteToPipelineWithUnrolling(result); } + return true; } } @@ -705,6 +722,7 @@ private bool GetValueFromIDictionaryInput() // Ignore invalid operation exception, it can happen if the dictionary // has keys that can't be compared to property. } + return false; } @@ -859,8 +877,10 @@ public sealed class WhereObjectCommand : PSCmdlet public PSObject InputObject { set { _inputObject = value; } + get { return _inputObject; } } + private PSObject _inputObject = AutomationNull.Value; private ScriptBlock _script; @@ -874,6 +894,7 @@ public ScriptBlock FilterScript { _script = value; } + get { return _script; @@ -919,6 +940,7 @@ public ScriptBlock FilterScript public string Property { set { _property = value; } + get { return _property; } } @@ -965,6 +987,7 @@ public object Value _value = value; _valueNotSpecified = false; } + get { return _value; } } @@ -989,6 +1012,7 @@ public SwitchParameter EQ _binaryOperator = TokenKind.Ieq; _forceBooleanEvaluation = false; } + get { return _binaryOperator == TokenKind.Ieq; } } @@ -1000,6 +1024,7 @@ public SwitchParameter EQ public SwitchParameter CEQ { set { _binaryOperator = TokenKind.Ceq; } + get { return _binaryOperator == TokenKind.Ceq; } } @@ -1011,6 +1036,7 @@ public SwitchParameter CEQ public SwitchParameter NE { set { _binaryOperator = TokenKind.Ine; } + get { return _binaryOperator == TokenKind.Ine; } } @@ -1022,6 +1048,7 @@ public SwitchParameter NE public SwitchParameter CNE { set { _binaryOperator = TokenKind.Cne; } + get { return _binaryOperator == TokenKind.Cne; } } @@ -1033,6 +1060,7 @@ public SwitchParameter CNE public SwitchParameter GT { set { _binaryOperator = TokenKind.Igt; } + get { return _binaryOperator == TokenKind.Igt; } } @@ -1044,6 +1072,7 @@ public SwitchParameter GT public SwitchParameter CGT { set { _binaryOperator = TokenKind.Cgt; } + get { return _binaryOperator == TokenKind.Cgt; } } @@ -1055,6 +1084,7 @@ public SwitchParameter CGT public SwitchParameter LT { set { _binaryOperator = _binaryOperator = TokenKind.Ilt; } + get { return _binaryOperator == TokenKind.Ilt; } } @@ -1066,6 +1096,7 @@ public SwitchParameter LT public SwitchParameter CLT { set { _binaryOperator = TokenKind.Clt; } + get { return _binaryOperator == TokenKind.Clt; } } @@ -1077,6 +1108,7 @@ public SwitchParameter CLT public SwitchParameter GE { set { _binaryOperator = TokenKind.Ige; } + get { return _binaryOperator == TokenKind.Ige; } } @@ -1088,6 +1120,7 @@ public SwitchParameter GE public SwitchParameter CGE { set { _binaryOperator = TokenKind.Cge; } + get { return _binaryOperator == TokenKind.Cge; } } @@ -1099,6 +1132,7 @@ public SwitchParameter CGE public SwitchParameter LE { set { _binaryOperator = TokenKind.Ile; } + get { return _binaryOperator == TokenKind.Ile; } } @@ -1110,6 +1144,7 @@ public SwitchParameter LE public SwitchParameter CLE { set { _binaryOperator = TokenKind.Cle; } + get { return _binaryOperator == TokenKind.Cle; } } @@ -1121,6 +1156,7 @@ public SwitchParameter CLE public SwitchParameter Like { set { _binaryOperator = TokenKind.Ilike; } + get { return _binaryOperator == TokenKind.Ilike; } } @@ -1131,6 +1167,7 @@ public SwitchParameter Like public SwitchParameter CLike { set { _binaryOperator = TokenKind.Clike; } + get { return _binaryOperator == TokenKind.Clike; } } @@ -1142,6 +1179,7 @@ public SwitchParameter CLike public SwitchParameter NotLike { set { _binaryOperator = TokenKind.Inotlike; } + get { return false; } } @@ -1152,6 +1190,7 @@ public SwitchParameter NotLike public SwitchParameter CNotLike { set { _binaryOperator = TokenKind.Cnotlike; } + get { return _binaryOperator == TokenKind.Cnotlike; } } @@ -1163,6 +1202,7 @@ public SwitchParameter CNotLike public SwitchParameter Match { set { _binaryOperator = TokenKind.Imatch; } + get { return _binaryOperator == TokenKind.Imatch; } } @@ -1173,6 +1213,7 @@ public SwitchParameter Match public SwitchParameter CMatch { set { _binaryOperator = TokenKind.Cmatch; } + get { return _binaryOperator == TokenKind.Cmatch; } } @@ -1184,6 +1225,7 @@ public SwitchParameter CMatch public SwitchParameter NotMatch { set { _binaryOperator = TokenKind.Inotmatch; } + get { return _binaryOperator == TokenKind.Inotmatch; } } @@ -1194,6 +1236,7 @@ public SwitchParameter NotMatch public SwitchParameter CNotMatch { set { _binaryOperator = TokenKind.Cnotmatch; } + get { return _binaryOperator == TokenKind.Cnotmatch; } } @@ -1205,6 +1248,7 @@ public SwitchParameter CNotMatch public SwitchParameter Contains { set { _binaryOperator = TokenKind.Icontains; } + get { return _binaryOperator == TokenKind.Icontains; } } @@ -1215,6 +1259,7 @@ public SwitchParameter Contains public SwitchParameter CContains { set { _binaryOperator = TokenKind.Ccontains; } + get { return _binaryOperator == TokenKind.Ccontains; } } @@ -1226,6 +1271,7 @@ public SwitchParameter CContains public SwitchParameter NotContains { set { _binaryOperator = TokenKind.Inotcontains; } + get { return _binaryOperator == TokenKind.Inotcontains; } } @@ -1236,6 +1282,7 @@ public SwitchParameter NotContains public SwitchParameter CNotContains { set { _binaryOperator = TokenKind.Cnotcontains; } + get { return _binaryOperator == TokenKind.Cnotcontains; } } @@ -1247,6 +1294,7 @@ public SwitchParameter CNotContains public SwitchParameter In { set { _binaryOperator = TokenKind.In; } + get { return _binaryOperator == TokenKind.In; } } @@ -1257,6 +1305,7 @@ public SwitchParameter In public SwitchParameter CIn { set { _binaryOperator = TokenKind.Cin; } + get { return _binaryOperator == TokenKind.Cin; } } @@ -1268,6 +1317,7 @@ public SwitchParameter CIn public SwitchParameter NotIn { set { _binaryOperator = TokenKind.Inotin; } + get { return _binaryOperator == TokenKind.Inotin; } } @@ -1278,6 +1328,7 @@ public SwitchParameter NotIn public SwitchParameter CNotIn { set { _binaryOperator = TokenKind.Cnotin; } + get { return _binaryOperator == TokenKind.Cnotin; } } @@ -1288,6 +1339,7 @@ public SwitchParameter CNotIn public SwitchParameter Is { set { _binaryOperator = TokenKind.Is; } + get { return _binaryOperator == TokenKind.Is; } } @@ -1298,6 +1350,7 @@ public SwitchParameter Is public SwitchParameter IsNot { set { _binaryOperator = TokenKind.IsNot; } + get { return _binaryOperator == TokenKind.IsNot; } } @@ -1308,6 +1361,7 @@ public SwitchParameter IsNot public SwitchParameter Not { set { _binaryOperator = TokenKind.Not; } + get { return _binaryOperator == TokenKind.Not; } } @@ -1385,6 +1439,7 @@ protected override void BeginProcessing() { _operationDelegate = GetCallSiteDelegateBoolean(ExpressionType.Equal, ignoreCase: true); } + break; case TokenKind.Ceq: _operationDelegate = GetCallSiteDelegate(ExpressionType.Equal, ignoreCase: false); @@ -1485,6 +1540,7 @@ protected override void BeginProcessing() (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); break; } + break; } case TokenKind.Ccontains: @@ -1512,6 +1568,7 @@ protected override void BeginProcessing() (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); break; } + break; } case TokenKind.Is: @@ -1548,6 +1605,7 @@ protected override void BeginProcessing() _convertedValue = LanguagePrimitives.ConvertTo(_convertedValue); } + break; } } @@ -1666,6 +1724,7 @@ private object GetValue(ref bool error) _property)); error = true; } + return null; } @@ -1811,6 +1870,7 @@ private ReadOnlyPSMemberInfoCollection GetMatchMembers() { results.Add(member); } + return new ReadOnlyPSMemberInfoCollection(results); } @@ -1834,8 +1894,10 @@ public sealed class SetPSDebugCommand : PSCmdlet public int Trace { set { _trace = value; } + get { return _trace; } } + private int _trace = -1; /// @@ -1845,8 +1907,10 @@ public int Trace public SwitchParameter Step { set { _step = value; } + get { return (SwitchParameter)_step; } } + private bool? _step; /// @@ -1856,8 +1920,10 @@ public SwitchParameter Step public SwitchParameter Strict { set { _strict = value; } + get { return (SwitchParameter)_strict; } } + private bool? _strict; /// @@ -1867,8 +1933,10 @@ public SwitchParameter Strict public SwitchParameter Off { get { return _off; } + set { _off = value; } } + private bool _off; /// @@ -1925,8 +1993,10 @@ public class SetStrictModeCommand : PSCmdlet public SwitchParameter Off { get { return _off; } + set { _off = value; } } + private SwitchParameter _off; /// @@ -1948,12 +2018,14 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input { return PSVersionInfo.PSVersion; } + if (versionStr.Contains(".")) { // If the string contains a '.', let the Version constructor handle the conversion. return inputData; } } + if (version is double) { // The conversion to int below is wrong, but the usual conversions will turn @@ -1996,8 +2068,10 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin public Version Version { get { return _version; } + set { _version = value; } } + private Version _version; /// @@ -2009,6 +2083,7 @@ protected override void EndProcessing() { _version = new Version(0, 0); } + Context.EngineSessionState.CurrentScope.StrictModeVersion = _version; } } diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 0459d7cba53..b6b4206911a 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -112,6 +112,7 @@ internal InvocationInfo(PSObject psObject) { scriptEndPosition = scriptPosition; } + _scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition); MyCommand = RemoteCommandInfo.FromPSObjectForRemoting(psObject); @@ -202,6 +203,7 @@ public Dictionary BoundParameters return _boundParameters ?? (_boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } + internal set { _boundParameters = value; } } @@ -211,6 +213,7 @@ public Dictionary BoundParameters public List UnboundArguments { get { return _unboundArguments ?? (_unboundArguments = new List()); } + internal set { _unboundArguments = value; } } @@ -309,6 +312,7 @@ public string PSCommandPath public string InvocationName { get { return _invocationName ?? string.Empty; } + internal set { _invocationName = value; } } @@ -376,6 +380,7 @@ internal IScriptExtent ScriptPosition return _scriptPosition; } } + set { _scriptPosition = value; } } @@ -478,6 +483,7 @@ internal static RemoteCommandInfo FromPSObjectForRemoting(PSObject psObject) commandInfo._definition = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Definition"); commandInfo.Visibility = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Visibility"); } + return commandInfo; } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 3ba8b33d64a..3002c04a2a8 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -181,6 +181,7 @@ public override bool CanConvertFrom(object sourceValue, Type destinationType) { return false; } + return true; } @@ -403,6 +404,7 @@ private static IEnumerable GetEnumerableFromIEnumerableT(object obj) return new EnumerableTWrapper(obj, i); } } + return null; } @@ -420,6 +422,7 @@ private static GetEnumerableDelegate GetOrCalculateEnumerable(Type type) s_getEnumerableCache.Add(type, getEnumerable); } } + return getEnumerable; } @@ -439,6 +442,7 @@ private static void InitializeGetEnumerableCache() internal static bool IsTypeEnumerable(Type type) { if (type == null) { return false; } + GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(type); return (getEnumerable != LanguagePrimitives.ReturnNullEnumerable); } @@ -466,6 +470,7 @@ public static IEnumerable GetEnumerable(object obj) { obj = PSObject.Base(obj); if (obj == null) { return null; } + GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(obj.GetType()); return getEnumerable(obj); } @@ -573,6 +578,7 @@ public static PSDataCollection GetPSDataCollection(object inputValue) result.Add(PSObject.AsPSObject(inputValue)); } } + result.Complete(); return result; } @@ -809,6 +815,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP first.ToString(), second.ToString(), e.Message); } } + return culture.CompareInfo.Compare(firstString, secondString, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } @@ -821,6 +828,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP { return LanguagePrimitives.NumericCompare(first, second, firstIndex, secondIndex); } + object secondConverted; try { @@ -1069,8 +1077,10 @@ internal static PSObject AsPSObjectOrNull(object obj) { return null; } + return PSObject.AsPSObject(obj); } + internal static int TypeTableIndex(Type type) { switch (LanguagePrimitives.GetTypeCode(type)) @@ -1446,6 +1456,7 @@ private static TypeConverter GetIntegerSystemConverter(Type type) { return new SByteConverter(); } + return null; } @@ -1462,6 +1473,7 @@ internal static object GetConverter(Type type, TypeTable backupTypeTable) s_tracer.WriteLine("ecFromTLS != null"); typesXmlConverter = ecFromTLS.TypeTable.GetTypeConverter(type.FullName); } + if ((typesXmlConverter == null) && (backupTypeTable != null)) { s_tracer.WriteLine("Using provided TypeTable to get the type converter"); @@ -1496,6 +1508,7 @@ private static object NewConverterInstance(string assemblyQualifiedTypeName) typeConversion.WriteLine("Type name \"{0}\" should be assembly qualified.", assemblyQualifiedTypeName); return null; } + string assemblyName = assemblyQualifiedTypeName.Substring(typeSeparator + 2); string typeName = assemblyQualifiedTypeName.Substring(0, typeSeparator); @@ -1513,6 +1526,7 @@ private static object NewConverterInstance(string assemblyQualifiedTypeName) typeConversion.WriteLine("Assembly \"{0}\" threw an exception when retrieving the type \"{1}\": \"{2}\".", assemblyName, typeName, e.Message); return null; } + try { return Activator.CreateInstance(converterType); @@ -1526,6 +1540,7 @@ private static object NewConverterInstance(string assemblyQualifiedTypeName) } } } + typeConversion.WriteLine("Could not create an instance of type \"{0}\".", assemblyQualifiedTypeName); return null; } @@ -1746,6 +1761,7 @@ public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultT ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(toConstructor, resultType); return noArgumentConstructorConverter.Convert(PSObject.Base(valueToConvert), resultType, recursion, (PSObject)valueToConvert, formatProvider, null, ignoreUnknownMembers); } + return null; } @@ -1761,6 +1777,7 @@ public static T ConvertTo(object valueToConvert) { return value; } + return (T)ConvertTo(valueToConvert, typeof(T), true, CultureInfo.InvariantCulture, null); } @@ -1780,6 +1797,7 @@ public static bool TryConvertTo(object valueToConvert, out T result) result = value; return true; } + return TryConvertTo(valueToConvert, CultureInfo.InvariantCulture, out result); } /// @@ -1917,6 +1935,7 @@ private static EnumHashEntry GetEnumHashEntry(Type enumType) { s_enumTable.Clear(); } + UInt64 allValues = 0; bool hasNegativeValue = false; Array values = Enum.GetValues(enumType); @@ -2087,6 +2106,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType ExtendedTypeSystem.InvalidCastException, sourceValue, ObjectToTypeNameString(sourceValue), destinationType); } + Diagnostics.Assert(destinationType.IsEnum, "EnumSingleTypeConverter is only applied to enumerations"); if (sourceValueString.Length == 0) { @@ -2094,6 +2114,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType ExtendedTypeSystem.InvalidCastException, sourceValue, ObjectToTypeNameString(sourceValue), destinationType); } + sourceValueString = sourceValueString.Trim(); if (sourceValueString.Length == 0) { @@ -2127,6 +2148,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType ExtendedTypeSystem.InvalidCastExceptionEnumerationNoFlagAndComma, sourceValue, destinationType); } + sourceValueEntries = new string[] { sourceValueString }; fromValuePatterns = new WildcardPattern[1]; if (WildcardPattern.ContainsWildcardCharacters(sourceValueString)) @@ -2188,6 +2210,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType if (String.Compare(sourceValueEntry, name, ignoreCaseOpt) != 0) continue; } + if (!multipleValues && foundOne) { object firstValue = Enum.ToObject(destinationType, returnUInt64); @@ -2196,9 +2219,11 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType ExtendedTypeSystem.InvalidCastExceptionEnumerationMoreThanOneValue, sourceValue, destinationType, firstValue, secondValue); } + foundOne = true; returnUInt64 |= Convert.ToUInt64(values.GetValue(j), CultureInfo.CurrentCulture); } + if (!foundOne) { throw new PSInvalidCastException("InvalidCastEnumStringNotFound", null, @@ -2244,14 +2269,17 @@ private static MethodInfo FindCastOperator(string methodName, Type targetType, T { continue; } + System.Reflection.ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 1 || !parameters[0].ParameterType.IsAssignableFrom(originalType)) { continue; } + typeConversion.WriteLine("Found \"{0}\" cast operator in type {1}.", methodName, targetType.FullName); return method; } + typeConversion.TraceScope("Cast operator for \"{0}\" not found.", methodName); return null; } @@ -2604,6 +2632,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, typeConversion.WriteLine("TypeConverter cannot convert to resultType."); } } + PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; if (valuePSTypeConverter != null) { @@ -2631,6 +2660,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } } } + s_tracer.WriteLine("No converter found in original type."); // now ConvertFrom for the destination type @@ -2662,6 +2692,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, typeConversion.WriteLine("Destination type's converter cannot convert from originalType."); } } + PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; if (valuePSTypeConverter != null) { @@ -2689,6 +2720,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } } } + result = null; return false; } @@ -2819,6 +2851,7 @@ private static Type ConvertStringToType(object valueToConvert, ExtendedTypeSystem.InvalidCastException, valueToConvert.ToString(), ObjectToTypeNameString(valueToConvert), resultType.ToString()); } + return namedType; } @@ -2884,6 +2917,7 @@ private static object ConvertStringToInteger(object valueToConvert, { e = e.InnerException; } + typeConversion.WriteLine("Exception converting to integer: \"{0}\".", e.Message); if (e is FormatException) { @@ -2897,6 +2931,7 @@ private static object ConvertStringToInteger(object valueToConvert, typeConversion.WriteLine("Exception converting to integer through double: \"{0}\".", ex.Message); } } + throw new PSInvalidCastException("InvalidCastFromStringToInteger", e, ExtendedTypeSystem.InvalidCastExceptionWithInnerException, strToConvert, resultType.ToString(), e.Message); @@ -2939,6 +2974,7 @@ private static object ConvertStringToDecimal(object valueToConvert, typeConversion.WriteLine("Exception converting to integer through double: \"{0}\".", ex.Message); } } + throw new PSInvalidCastException("InvalidCastFromStringToDecimal", e, ExtendedTypeSystem.InvalidCastExceptionWithInnerException, valueToConvert.ToString(), resultType.ToString(), e.Message); @@ -3378,6 +3414,7 @@ private static object ConvertEnumerableToArray(object valueToConvert, // false means no further recursions and therefore no cycles result.Add(ConvertTo(obj, resultElementType, false, formatProvider, backupTable)); } + return result.ToArray(resultElementType); } catch (Exception e) @@ -3551,6 +3588,7 @@ private static object ConvertEnumerableToEnum(object valueToConvert, e.Current, resultType, EnumSingleTypeConverter.EnumValues(resultType)); } } + sbResult.Append(current); } @@ -3872,6 +3910,7 @@ internal object Convert(object valueToConvert, IDictionary properties = valueToConvert as IDictionary; SetObjectProperties(result, properties, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: false); } + typeConversion.WriteLine("Constructor result: \"{0}\".", result); } else @@ -4215,6 +4254,7 @@ internal delegate T PSConverter(object valueToConvert, internal interface IConversionData { object Converter { get; } + ConversionRank Rank { get; } object Invoke(object valueToConvert, @@ -4268,6 +4308,7 @@ private static IConversionData CacheConversion(Type fromType, Type toType, PS "Existing conversion isn't the same as new conversion"); } } + return data; } @@ -4378,6 +4419,7 @@ internal static void RebuildConversionCache() LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); } } + foreach (Type integerType in s_integerTypes) { CacheConversion(typeofString, integerType, LanguagePrimitives.ConvertStringToInteger, ConversionRank.NumericString); @@ -4526,6 +4568,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T if (TypeResolver.TryResolveType(property.TypeNameOfValue, out propType)) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } + try { PSObject propertyValue = prop.Value as PSObject; @@ -4548,6 +4591,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T } } } + property.Value = propValue; } else @@ -4581,6 +4625,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T } } } + return pso; } @@ -4597,6 +4642,7 @@ private static string GetAvailableProperties(PSObject pso) { availableProperties.Append(" , "); } + availableProperties.Append("[" + p.Name + " <" + p.TypeNameOfValue + ">]"); if (first == true) { @@ -4805,6 +4851,7 @@ private static IConversionData FigureLanguageConversion(Type fromType, Type toTy { converter = LanguagePrimitives.ConvertClassToBool; } + return CacheConversion(fromType, toType, converter, ConversionRank.Language); } @@ -5011,6 +5058,7 @@ internal bool ProjectedSignatureMatchesTarget(Type[] argumentTypes, out bool sig { return false; } + allTypesMatchExactly &= typesMatchExactly; } @@ -5041,6 +5089,7 @@ private static bool ProjectedTypeMatchesTargetType(Type sourceType, Type targetT return true; } } + return false; } @@ -5107,6 +5156,7 @@ private static PSConverter FigureParseConversion(Type fromType, Type toT { typeConversion.WriteLine("Exception finding Parse method with CultureInfo: \"{0}\".", e.Message); } + if (parse != null) { ConvertViaParseMethod converter = new ConvertViaParseMethod(); @@ -5174,6 +5224,7 @@ internal static Tuple, ConversionRank> FigureIEnumerableCons "toType has more than one generic arguments. Here we only care about the toType which contains only one generic argument and whose constructor takes IEnumerable, ICollection or IList."); return null; } + elementType = argTypes[0]; if (typeof(Array) == fromType || typeof(object[]) == fromType || @@ -5441,6 +5492,7 @@ internal class InternalPSCustomObject } internal class InternalPSObject : PSObject { } + internal static IConversionData FigureConversion(Type fromType, Type toType) { IConversionData data = GetConversionData(fromType, toType); @@ -5648,6 +5700,7 @@ private static IConversionData FigureConversionFromNull(Type toType) { return CacheConversion(typeof(Null), toType, LanguagePrimitives.ConvertNullToRef, ConversionRank.NullToRef); } + return CacheConversion(typeof(Null), toType, ConvertNoConversion, ConversionRank.None); } @@ -5664,6 +5717,7 @@ internal static string ObjectToTypeNameString(object o) { return typeNames[0]; } + return Microsoft.PowerShell.ToStringCodeMethods.Type(o.GetType()); } @@ -5679,6 +5733,7 @@ private static Assembly AssemblyResolveHelper(object sender, ResolveEventArgs ar return assem; } } + return null; } #endif diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 6cb7bfe7582..c1f52ee2002 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -87,6 +87,7 @@ private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObj type.Append(managementObj.SystemProperties["__NAMESPACE"].Value); type.Append("\\"); } + type.Append(managementObj.SystemProperties["__CLASS"].Value); yield return type.ToString(); @@ -115,6 +116,7 @@ private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObj type.Append(managementObj.SystemProperties["__NAMESPACE"].Value); type.Append("\\"); } + type.Append(t); yield return type.ToString(); } @@ -152,6 +154,7 @@ protected override IEnumerable GetTypeNameHierarchy(object obj) yield return typeFromDerivation; } } + yield return baseType; } } @@ -359,6 +362,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c property.Name, property.baseObject.GetType().FullName, typeof(ManagementBaseObject).FullName); } + if (!PropertyIsSettable(property)) { throw new SetValueException("ReadOnlyWMIProperty", @@ -366,6 +370,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c ExtendedTypeSystem.ReadOnlyProperty, property.Name); } + PropertyData pd = property.adapterData as PropertyData; if ((convertIfPossible) && (setValue != null)) @@ -392,6 +397,7 @@ protected override string PropertyToString(PSProperty property) // { // returnValue.Append("static "); // } + returnValue.Append(PropertyType(property, forDisplay: true)); returnValue.Append(" "); returnValue.Append(property.Name); @@ -400,10 +406,12 @@ protected override string PropertyToString(PSProperty property) { returnValue.Append("get;"); } + if (PropertyIsSettable(property)) { returnValue.Append("set;"); } + returnValue.Append("}"); return returnValue.ToString(); } diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index f25d80ea7da..fc410f1bc24 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -151,6 +151,7 @@ internal Collection AddMetadataForBinder( _aliasedParameters.Add(aliasName, mergedParameter); } } + return result; } @@ -248,6 +249,7 @@ private int AddParameterSetToMap(string parameterSetName) _nextAvailableParameterSetIndex++; } } + return index; } @@ -326,6 +328,7 @@ internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSet // Set the bit field in the parameter parameter.Parameter.ParameterSetFlags = parameterSetBitField; } + return defaultParameterSetFlag; } @@ -378,6 +381,7 @@ internal string GetParameterSetName(uint parameterSet) result = String.Empty; } } + return result; } @@ -402,6 +406,7 @@ private static string RetrieveParameterNameForAlias( return compiledParam.Name; } } + return String.Empty; } @@ -560,6 +565,7 @@ internal MergedCompiledCommandParameter GetMatchingParameter( { result = matchingParameters[0]; } + return result; } @@ -585,6 +591,7 @@ internal Collection GetParametersInParameterSet( result.Add(parameter); } } + return result; } @@ -594,6 +601,7 @@ internal Collection GetParametersInParameterSet( /// the values are the compiled parameter metadata. /// internal IDictionary BindableParameters { get { return _bindableParameters; } } + private IDictionary _bindableParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -602,6 +610,7 @@ internal Collection GetParametersInParameterSet( /// the alias name and the value is the MergedCompiledCommandParameter metadata. /// internal IDictionary AliasedParameters { get { return _aliasedParameters; } } + private IDictionary _aliasedParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); diff --git a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs index 0b2280ae366..dc69c4cd432 100644 --- a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs +++ b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs @@ -318,6 +318,7 @@ private string { return XmlFormatValue; } + if (TextFormatValue.StartsWith(fpValue, StringComparison.OrdinalIgnoreCase)) { return TextFormatValue; @@ -370,6 +371,7 @@ private static ArrayList ConvertArgsValueToArrayList(object value) results.Add(list.Current); } } + return results; } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 6cc28f240db..353f085b58b 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -260,6 +260,7 @@ public bool HasErrors { return _commandRuntime.PipelineProcessor.ExecutionFailed; } + set { _commandRuntime.PipelineProcessor.ExecutionFailed = value; @@ -442,6 +443,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) { throw e; } + if (cmdletType == null) { return null; @@ -454,6 +456,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) if (ca != null) break; } + if (ca == null) { throw PSTraceSource.NewNotSupportedException(); @@ -705,6 +708,7 @@ public Collection InvokeScript( { throw PSTraceSource.NewArgumentNullException("scriptBlock"); } + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException("sessionState"); @@ -972,10 +976,12 @@ public PagingParameters PagingParameters _pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); } } + return _pagingParameters; } } } + private PagingParameters _pagingParameters; #region InvokeCommand diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 5e85e54323b..5feafaef0e8 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -68,6 +68,7 @@ internal bool IsPipelineInputExpected { return false; } + return true; } } @@ -86,6 +87,7 @@ internal bool IsPipelineInputExpected internal string OutVariable { get; set; } internal IList OutVarList { get { return _outVarList; } set { _outVarList = value; } } + private IList _outVarList = null; internal PipelineProcessor PipelineProcessor { get; set; } @@ -978,6 +980,7 @@ internal void SetupPipelineVariable() internal int OutBuffer { get { return OutputPipe.OutBufferCount; } + set { OutputPipe.OutBufferCount = value; } } @@ -1404,6 +1407,7 @@ private bool CanShouldProcessAutoConfirm() Dbg.Assert(false, "Expected CommandMetadata"); return true; } + ConfirmImpact cmdletConfirmImpact = commandMetadata.ConfirmImpact; // compare to ConfirmPreference @@ -2028,6 +2032,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { throw PSTraceSource.NewArgumentNullException("errorRecord"); } + errorRecord.SetInvocationInfo(MyInvocation); if (errorRecord.ErrorDetails != null @@ -2169,6 +2174,7 @@ internal void SetMergeFromRuntime(MshCommandRuntime fromRuntime) internal Pipe InputPipe { get { return _inputPipe ?? (_inputPipe = new Pipe()); } + set { _inputPipe = value; } } @@ -2178,6 +2184,7 @@ internal Pipe InputPipe internal Pipe OutputPipe { get { return _outputPipe ?? (_outputPipe = new Pipe()); } + set { _outputPipe = value; } } @@ -2200,6 +2207,7 @@ internal object[] GetResultsAsArray() internal Pipe ErrorOutputPipe { get { return _errorOutputPipe ?? (_errorOutputPipe = new Pipe()); } + set { _errorOutputPipe = value; } } @@ -2537,6 +2545,7 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, { this.OutputPipe.AddVariableList(streamKind, varList); } + _state.PSVariable.Set(variableName, varList); } @@ -2895,6 +2904,7 @@ internal ConfirmImpact ConfirmPreference return ConfirmImpact.None; return ConfirmImpact.Low; } + if (IsConfirmFlagSet) // -Confirm:$false return ConfirmImpact.None; @@ -2904,6 +2914,7 @@ internal ConfirmImpact ConfirmPreference _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out defaultUsed); _isConfirmPreferenceCached = true; } + return _confirmPreference; } } @@ -2949,6 +2960,7 @@ internal ActionPreference DebugPreference return _debugPreference; } + set { _debugPreference = value; @@ -3035,6 +3047,7 @@ internal ActionPreference WarningPreference return _warningPreference; } + set { if (value == ActionPreference.Suspend) @@ -3061,6 +3074,7 @@ internal ActionPreference WarningPreference internal bool Verbose { get { return _verboseFlag; } + set { _verboseFlag = value; @@ -3084,6 +3098,7 @@ internal SwitchParameter Confirm { return _confirmFlag; } + set { _confirmFlag = value; @@ -3107,6 +3122,7 @@ internal SwitchParameter UseTransaction { return _useTransactionFlag; } + set { _useTransactionFlag = value; @@ -3131,6 +3147,7 @@ internal SwitchParameter UseTransaction internal bool Debug { get { return _debugFlag; } + set { _debugFlag = value; @@ -3162,6 +3179,7 @@ internal SwitchParameter WhatIf return _whatIfFlag; } + set { _whatIfFlag = value; @@ -3196,8 +3214,10 @@ internal ActionPreference ErrorAction _errorAction = Context.GetEnumPreference(SpecialVariables.ErrorActionPreferenceVarPath, _errorAction, out defaultUsed); _isErrorActionPreferenceCached = true; } + return _errorAction; } + set { if (value == ActionPreference.Suspend) @@ -3229,14 +3249,17 @@ internal ActionPreference ProgressPreference _progressPreference = Context.GetEnumPreference(SpecialVariables.ProgressPreferenceVarPath, _progressPreference, out defaultUsed); _isProgressPreferenceCached = true; } + return _progressPreference; } + set { _progressPreference = value; _isProgressPreferenceSet = true; } } + private ActionPreference _progressPreference = InitialSessionState.defaultProgressPreference; private bool _isProgressPreferenceSet = false; private bool _isProgressPreferenceCached = false; @@ -3258,8 +3281,10 @@ internal ActionPreference InformationPreference _informationPreference = Context.GetEnumPreference(SpecialVariables.InformationPreferenceVarPath, _informationPreference, out defaultUsed); _isInformationPreferenceCached = true; } + return _informationPreference; } + set { if (value == ActionPreference.Suspend) @@ -3271,6 +3296,7 @@ internal ActionPreference InformationPreference IsInformationActionSet = true; } } + private ActionPreference _informationPreference = InitialSessionState.defaultInformationPreference; internal bool IsInformationActionSet { get; private set; } = false; @@ -3547,8 +3573,10 @@ bool hasSecurityImpact { textChoices.Append(" "); } + textChoices.Append(choice.Label); } + CBhost.InternalUI.TranscribeResult(textChoices.ToString()); int defaultOption = 0; diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 3625a0a7667..729383a1419 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -591,6 +591,7 @@ public override object Value return returnValue; } + set => this.ReferencedMember.Value = value; } @@ -915,6 +916,7 @@ public override object Value e.Message); } } + set { if (SetterCodeReference == null) @@ -1797,6 +1799,7 @@ public override object Value return InvokeGetter(this.instance); } + set { if (this.SetterScript == null) diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 13d9ce73cd7..792a08294a6 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -87,6 +87,7 @@ private static T TypeTableGetMemberDelegate(PSObject msjObj, TypeTable typeTa PSObject.memberResolution.WriteLine("\"{0}\" present in type table.", name); return memberAsT; } + PSObject.memberResolution.WriteLine("\"{0}\" from types table ignored because it has type {1} instead of {2}.", name, member.GetType(), typeof(T)); return null; @@ -104,6 +105,7 @@ internal static PSMemberInfoInternalCollection TypeTableGetMembersDelegate { return new PSMemberInfoInternalCollection(); } + PSMemberInfoInternalCollection members = typeTableToUse.GetMembers(msjObj.InternalTypeNames); PSObject.memberResolution.WriteLine("Type table members: {0}.", members.Count); return members; @@ -117,10 +119,12 @@ private static T AdapterGetMemberDelegate(PSObject msjObj, string name) where { return null; } + T adaptedMember = msjObj.adaptedMembers[name] as T; PSObject.memberResolution.WriteLine("Serialized adapted member: {0}.", adaptedMember == null ? "not found" : adaptedMember.Name); return adaptedMember; } + T retValue = msjObj.InternalAdapter.BaseGetMember(msjObj._immediateBaseObject, name); PSObject.memberResolution.WriteLine("Adapted member: {0}.", retValue == null ? "not found" : retValue.Name); return retValue; @@ -142,6 +146,7 @@ internal static PSMemberInfoInternalCollection TransformMemberInfoCollection< returnValue.Add(tAsU); } } + return returnValue; } @@ -153,9 +158,11 @@ private static PSMemberInfoInternalCollection AdapterGetMembersDelegate(PS { return new PSMemberInfoInternalCollection(); } + PSObject.memberResolution.WriteLine("Serialized adapted members: {0}.", msjObj.adaptedMembers.Count); return TransformMemberInfoCollection(msjObj.adaptedMembers); } + PSMemberInfoInternalCollection retValue = msjObj.InternalAdapter.BaseGetMembers(msjObj._immediateBaseObject); PSObject.memberResolution.WriteLine("Adapted members: {0}.", retValue.VisibleCount); return retValue; @@ -237,6 +244,7 @@ internal static Collection> GetMemberCollection( true, true, "type table members")); } } + if ((viewType & PSMemberViewTypes.Adapted) == PSMemberViewTypes.Adapted) { returnValue.Add(new CollectionEntry( @@ -246,6 +254,7 @@ internal static Collection> GetMemberCollection( shouldCloneWhenReturning: false, collectionNameForTracing: "adapted members")); } + if ((viewType & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) { returnValue.Add(new CollectionEntry( @@ -255,6 +264,7 @@ internal static Collection> GetMemberCollection( shouldCloneWhenReturning: false, collectionNameForTracing: "clr members")); } + return returnValue; } @@ -331,6 +341,7 @@ internal static Collection> GetPropertyCollectio true, true, "type table members")); } } + if ((viewType & PSMemberViewTypes.Adapted) == PSMemberViewTypes.Adapted) { returnValue.Add(new CollectionEntry( @@ -338,6 +349,7 @@ internal static Collection> GetPropertyCollectio PSObject.AdapterGetMemberDelegate, false, false, "adapted members")); } + if ((viewType & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) { returnValue.Add(new CollectionEntry( @@ -345,6 +357,7 @@ internal static Collection> GetPropertyCollectio PSObject.DotNetGetMemberDelegate, false, false, "clr members")); } + return returnValue; } @@ -392,16 +405,23 @@ private void CommonInitialization(object obj) private static AdapterSet MappedInternalAdapterSet(object obj) { if (obj is PSMemberSet) { return PSObject.s_mshMemberSetAdapter; } + if (obj is PSObject) { return PSObject.s_mshObjectAdapter; } + if (obj is CimInstance) { return PSObject.s_cimInstanceAdapter; } #if !UNIX if (obj is ManagementClass) { return PSObject.s_managementClassAdapter; } + if (obj is ManagementBaseObject) { return PSObject.s_managementObjectAdapter; } + if (obj is DirectoryEntry) { return PSObject.s_directoryEntryAdapter; } #endif if (obj is DataRowView) { return PSObject.s_dataRowViewAdapter; } + if (obj is DataRow) { return PSObject.s_dataRowAdapter; } + if (obj is XmlNode) { return PSObject.s_xmlNodeAdapter; } + return null; } @@ -524,6 +544,7 @@ public PSObject(object obj) { throw PSTraceSource.NewArgumentNullException("obj"); } + CommonInitialization(obj); } @@ -622,6 +643,7 @@ private AdapterSet InternalAdapterSet return _adapterSet; } } + private AdapterSet _adapterSet; internal bool hasGeneratedReservedMembers; @@ -646,8 +668,10 @@ internal PSMemberInfoInternalCollection InstanceMembers return _instanceMembers; } + set => _instanceMembers = value; } + private PSMemberInfoInternalCollection _instanceMembers; internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalCollection instanceMembers) @@ -662,6 +686,7 @@ internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalColl out psobj._instanceMembers); } } + instanceMembers = psobj._instanceMembers; } else if (obj != null) @@ -731,6 +756,7 @@ public PSMemberInfoCollection Members return _members; } } + private PSMemberInfoIntegratingCollection _members; /// @@ -754,6 +780,7 @@ public PSMemberInfoCollection Properties return _properties; } } + private PSMemberInfoIntegratingCollection _properties; /// @@ -777,6 +804,7 @@ public PSMemberInfoCollection Methods return _methods; } } + private PSMemberInfoIntegratingCollection _methods; /// @@ -829,6 +857,7 @@ public Collection TypeNames object baseObj = BaseObject; // In most cases, the TypeNames will be modified after it's returned if (baseObj != null) { PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(baseObj.GetType()); } + return _typeNames; } } @@ -864,6 +893,7 @@ internal ConsolidatedString InternalTypeNames return _typeNames; } + set => _typeNames = value; } @@ -878,6 +908,7 @@ internal static ConsolidatedString GetTypeNames(object obj) { return result; } + return PSObject.GetMappedAdapter(obj, null).OriginalAdapter.BaseGetTypeNameHierarchy(obj); } @@ -946,12 +977,14 @@ internal static object Base(object obj) { return obj; } + if (mshObj == AutomationNull.Value) return null; if (mshObj.immediateBaseObjectIsEmpty) { return obj; } + object returnValue; do { @@ -969,6 +1002,7 @@ internal static PSMemberInfo GetStaticCLRMember(object obj, string methodName) { return null; } + var objType = obj as Type ?? obj.GetType(); return dotNetStaticAdapter.BaseGetMember(objType, methodName); } @@ -1062,6 +1096,7 @@ private static string GetSeparator(ExecutionContext context, string separator) { return obj.ToString(); } + return " "; } @@ -1075,10 +1110,12 @@ internal static string ToStringEnumerator(ExecutionContext context, IEnumerator returnValue.Append(PSObject.ToString(context, obj, separator, format, formatProvider, false, false)); returnValue.Append(separatorToUse); } + if (returnValue.Length == 0) { return string.Empty; } + int separatorLength = separatorToUse.Length; returnValue.Remove(returnValue.Length - separatorLength, separatorLength); return returnValue.ToString(); @@ -1095,12 +1132,15 @@ internal static string ToStringEnumerable(ExecutionContext context, IEnumerable PSObject mshObj = PSObject.AsPSObject(obj); returnValue.Append(PSObject.ToString(context, mshObj, separator, format, formatProvider, false, false)); } + returnValue.Append(separatorToUse); } + if (returnValue.Length == 0) { return string.Empty; } + int separatorLength = separatorToUse.Length; returnValue.Remove(returnValue.Length - separatorLength, separatorLength); return returnValue.ToString(); @@ -1116,6 +1156,7 @@ private static string ToStringEmptyBaseObject(ExecutionContext context, PSObject { returnValue.Append("; "); } + isFirst = false; returnValue.Append(property.Name); returnValue.Append("="); @@ -1125,10 +1166,12 @@ private static string ToStringEmptyBaseObject(ExecutionContext context, PSObject returnValue.Append(PSObject.ToString(context, propertyValue, separator, format, formatProvider, false, false)); } + if (isFirst) { return string.Empty; } + returnValue.Append("}"); return returnValue.ToString(); } @@ -1267,6 +1310,7 @@ internal static string ToString(ExecutionContext context, object obj, string sep // We do want to ignore exceptions here to try the regular ToString below. } } + if (unravelEnumeratorOnRecurse) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(obj); @@ -1297,8 +1341,10 @@ internal static string ToString(ExecutionContext context, object obj, string sep { return Microsoft.PowerShell.ToStringCodeMethods.Type(type); } + return obj.ToString(); } + return objFormattable.ToString(format, formatProvider); } catch (Exception e) @@ -1390,6 +1436,7 @@ internal static string ToString(ExecutionContext context, object obj, string sep // We do want to ignore exceptions here to try the regular ToString below. } } + if (unravelEnumeratorOnRecurse) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(mshObj); @@ -1452,6 +1499,7 @@ public override string ToString() { return _toStringFromDeserialization; } + return PSObject.ToString(null, this, null, null, null, true, false); } @@ -1472,6 +1520,7 @@ public string ToString(string format, IFormatProvider formatProvider) { return _toStringFromDeserialization; } + return PSObject.ToString(null, this, null, format, formatProvider, true, false); } @@ -1486,6 +1535,7 @@ private string PrivateToString() { result = this.BaseObject.GetType().FullName; } + return result; } @@ -1596,6 +1646,7 @@ public int CompareTo(object obj) { return 0; } + try { // PSObject.Base instead of BaseObject could cause an infinite @@ -1776,16 +1827,19 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName { settings.ReplicateInstance(ownerObject); } + PSNoteProperty note = settings.Members[noteName] as PSNoteProperty; if (note == null) { return defaultValue; } + object noteValue = note.Value; if (noteValue == null || noteValue.GetType() != expectedType) { return defaultValue; } + return note.Value; } @@ -1924,6 +1978,7 @@ internal bool ShouldSerializeAdapter() { return this.adaptedMembers != null; } + return !this.immediateBaseObjectIsEmpty; } @@ -1938,6 +1993,7 @@ private PSMemberInfoInternalCollection GetProperties(PSMemberInf { return serializedMembers; } + PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); foreach (PSPropertyInfo member in particularAdapter.BaseGetMembers(_immediateBaseObject)) @@ -2002,6 +2058,7 @@ internal bool PreserveToString { return preserveToString; } + preserveToStringSet = true; if (InternalTypeNames.Count == 0) { @@ -2127,6 +2184,7 @@ public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder bind { return DeferForIDMOP(binder, arg); } + return binder.FallbackBinaryOperation(GetUnwrappedObject(), arg); } @@ -2251,6 +2309,7 @@ internal bool IsHelpObject get => _isHelpObject; set => _isHelpObject = value; } + private bool _isHelpObject = false; #endregion @@ -2306,8 +2365,10 @@ private static void AddGenericArguments(StringBuilder sb, Type[] genericArgument for (int i = 0; i < genericArguments.Length; i++) { if (i > 0) { sb.Append(','); } + sb.Append(Type(genericArguments[i], dropNamespaces)); } + sb.Append(']'); } @@ -2340,6 +2401,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = { sb.Append(","); } + sb.Append("]"); result = sb.ToString(); } @@ -2352,6 +2414,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = { return type.Name; } + if (dropNamespaces) { if (type.IsNested) @@ -2388,6 +2451,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = result = type.AssemblyQualifiedName; } } + return result; } @@ -2438,6 +2502,7 @@ public static string XmlNodeList(PSObject instance) { return string.Empty; } + return PSObject.AsPSObject(nodes[0]).ToString(); } diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 7274d876551..33bada71c26 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -191,8 +191,10 @@ public override object GetValue(object component) { throw e; } + return returnValue; } + return property.Value; } catch (ExtendedTypeSystemException e) @@ -204,6 +206,7 @@ public override object GetValue(object component) { throw; } + return returnValue; } } @@ -223,8 +226,10 @@ private static PSObject GetComponentPSObject(object component) typeof(PSObject).Name, typeof(PSObjectTypeDescriptor).Name); } + mshObj = descriptor.Instance; } + return mshObj; } @@ -238,6 +243,7 @@ private object DealWithGetValueException(ExtendedTypeSystemException e, out bool "GettingValueException event has been triggered resulting in ValueReplacement:\"{0}\".", eventArgs.ValueReplacement); } + shouldThrow = eventArgs.ShouldThrow; return eventArgs.ValueReplacement; } @@ -283,8 +289,10 @@ public override void SetValue(object component, object value) { throw e; } + return; } + property.Value = value; } catch (ExtendedTypeSystemException e) @@ -297,6 +305,7 @@ public override void SetValue(object component, object value) throw; } } + OnValueChanged(component, EventArgs.Empty); } @@ -310,6 +319,7 @@ private void DealWithSetValueException(ExtendedTypeSystemException e, out bool s "SettingValueException event has been triggered resulting in ShouldThrow:\"{0}\".", eventArgs.ShouldThrow); } + shouldThrow = eventArgs.ShouldThrow; return; } @@ -365,6 +375,7 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", propertyInfo.Name); return; } + AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if (attributes != null && attributes.Length != 0) @@ -444,6 +455,7 @@ public override PropertyDescriptorCollection GetProperties(Attribute[] attribute { CheckAndAddProperty(property, attributes, ref returnValue); } + return returnValue; } } @@ -460,10 +472,12 @@ public override bool Equals(object obj) { return false; } + if (this.Instance == null || other.Instance == null) { return ReferenceEquals(this, other); } + return other.Instance.Equals(this.Instance); } @@ -477,6 +491,7 @@ public override int GetHashCode() { return base.GetHashCode(); } + return this.Instance.GetHashCode(); } @@ -490,6 +505,7 @@ public override PropertyDescriptor GetDefaultProperty() { return null; } + string defaultProperty = null; PSMemberSet standardMembers = this.Instance.PSStandardMembers; if (standardMembers != null) @@ -513,6 +529,7 @@ public override PropertyDescriptor GetDefaultProperty() } } } + PropertyDescriptorCollection properties = this.GetProperties(); if (defaultProperty != null) @@ -543,6 +560,7 @@ public override TypeConverter GetConverter() // GetConverter returned an illegal value return new TypeConverter(); } + object baseObject = this.Instance.BaseObject; TypeConverter retValue = LanguagePrimitives.GetConverter(baseObject.GetType(), null) as TypeConverter ?? TypeDescriptor.GetConverter(baseObject); @@ -584,6 +602,7 @@ public override EventDescriptor GetDefaultEvent() { return null; } + return TypeDescriptor.GetDefaultEvent(this.Instance.BaseObject); } @@ -597,6 +616,7 @@ public override EventDescriptorCollection GetEvents() { return new EventDescriptorCollection(null); } + return TypeDescriptor.GetEvents(this.Instance.BaseObject); } @@ -611,6 +631,7 @@ public override EventDescriptorCollection GetEvents(Attribute[] attributes) { return null; } + return TypeDescriptor.GetEvents(this.Instance.BaseObject, attributes); } @@ -624,6 +645,7 @@ public override AttributeCollection GetAttributes() { return new AttributeCollection(); } + return TypeDescriptor.GetAttributes(this.Instance.BaseObject); } @@ -637,6 +659,7 @@ public override string GetClassName() { return null; } + return TypeDescriptor.GetClassName(this.Instance.BaseObject); } @@ -650,6 +673,7 @@ public override string GetComponentName() { return null; } + return TypeDescriptor.GetComponentName(this.Instance.BaseObject); } @@ -664,6 +688,7 @@ public override object GetEditor(Type editorBaseType) { return null; } + return TypeDescriptor.GetEditor(this.Instance.BaseObject, editorBaseType); } #endregion Forwarded To BaseObject diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index f1e564c28b9..eeeca79e178 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -56,6 +56,7 @@ public object Value return _value; } + set { PSVariable variable = _value as PSVariable; diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index 0a290f6cea0..baae51712b0 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -101,9 +101,11 @@ public override ErrorRecord ErrorRecord ErrorCategory.SecurityError, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; /// @@ -115,6 +117,7 @@ public override string Message { get { return _message; } } + private string _message; } } diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index f52630c0df6..d52323e5f71 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -90,6 +90,7 @@ internal string FullName return _fullName; } } + private string _fullName; /// @@ -102,6 +103,7 @@ internal string PSSnapInName return _psSnapinName; } } + private string _psSnapinName; /// @@ -114,6 +116,7 @@ internal string ShortName return _shortName; } } + private string _shortName; /// diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index 883bc6e1f9a..15a57f86de8 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -14,6 +14,7 @@ internal sealed class NativeCommand : InternalCommand internal NativeCommandProcessor MyCommandProcessor { get { return _myCommandProcessor; } + set { _myCommandProcessor = value; } } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 40cfcb23358..63c476c270a 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -75,6 +75,7 @@ internal void BindParameters(Collection parameters) { _arguments.Append(' '); } + first = false; if (parameter.ParameterNameSpecified) @@ -139,6 +140,7 @@ internal string Arguments return _arguments.ToString(); } } + private readonly StringBuilder _arguments = new StringBuilder(); #endregion internal members @@ -178,6 +180,7 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array { break; } + arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); currentElement += 1; @@ -221,6 +224,7 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array { _arguments.Append('\\'); } + _arguments.Append('"'); } else @@ -293,6 +297,7 @@ private void PossiblyGlobArg(string arg, bool usedQuotes) { _arguments.Append(expandedPath); } + argExpanded = true; } } @@ -342,8 +347,10 @@ internal static bool NeedQuotes(string stringToCheck) { needQuotes = true; } + followingBackslash = stringToCheck[i] == '\\'; } + return needQuotes; } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 62a582639d8..01d0516a81b 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -274,6 +274,7 @@ internal NativeCommandParameterBinderController NativeParameterBinderController { NewParameterBinderController(this.Command); } + return _nativeParameterBinderController; } } @@ -532,6 +533,7 @@ private void InitNativeProcess() { inputFormat = ((MinishellParameterBinderController)NativeParameterBinderController).InputFormat; } + lock (_sync) { if (!_stopped) @@ -812,6 +814,7 @@ public int ParentId { ConstructParentId(); } + return _parentId; } } @@ -829,6 +832,7 @@ public static ProcessWithParentId[] Construct(Process[] originalProcCollection) { result[index] = new ProcessWithParentId(originalProcCollection[index]); } + return result; } @@ -1052,12 +1056,14 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) { sourceId = (long)info.Value; } + info = temp.Properties["Record"]; ProgressRecord rec = null; if (info != null) { rec = info.Value as ProgressRecord; } + if (rec != null) { this.Command.PSHostInternal.UI.WriteProgress(sourceId, rec); @@ -1092,10 +1098,12 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE { startInfo.RedirectStandardInput = true; } + if (redirectOutput) { startInfo.RedirectStandardOutput = true; } + if (redirectError) { startInfo.RedirectStandardError = true; @@ -1129,6 +1137,7 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE mpc.BindParameters(arguments, redirectOutput, this.Command.Context.EngineHostInterface.Name); startInfo.CreateNoWindow = mpc.NonInteractive; } + startInfo.Arguments = NativeParameterBinderController.Arguments; ExecutionContext context = this.Command.Context; @@ -1422,6 +1431,7 @@ private bool IsMiniShell() } } } + return false; } @@ -1452,6 +1462,7 @@ public ProcessOutputHandler(Process process, BlockingCollection DeserializeCliXmlObject(string xml, bool isOut { stream = StringToMinishellStreamConverter.ToMinishellStream(streamName); } + if (stream == MinishellStream.Unknown) { stream = isOutput ? MinishellStream.Output : MinishellStream.Error; @@ -1602,6 +1614,7 @@ private List DeserializeCliXmlObject(string xml, bool isOut { continue; } + obj = new ErrorRecord(new RemoteException(errorMessage), "NativeCommandError", ErrorCategory.NotSpecified, errorMessage); } @@ -1641,6 +1654,7 @@ private List DeserializeCliXmlObject(string xml, bool isOut continue; } } + result.Add(new ProcessOutputObject(obj, stream)); } } @@ -1843,6 +1857,7 @@ internal void Dispose() // lead to "Broken pipe" exception. // we are ignoring it here } + _streamWriter = null; } } diff --git a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs index a0e087421ae..920b14e53a8 100644 --- a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs +++ b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs @@ -23,11 +23,13 @@ public string SourceIdentifier { return _sourceIdentifier; } + set { _sourceIdentifier = value; } } + private string _sourceIdentifier = Guid.NewGuid().ToString(); /// @@ -40,11 +42,13 @@ public ScriptBlock Action { return _action; } + set { _action = value; } } + private ScriptBlock _action = null; /// @@ -57,11 +61,13 @@ public PSObject MessageData { return _messageData; } + set { _messageData = value; } } + private PSObject _messageData = null; /// @@ -75,11 +81,13 @@ public SwitchParameter SupportEvent { return _supportEvent; } + set { _supportEvent = value; } } + private SwitchParameter _supportEvent = new SwitchParameter(); /// @@ -93,11 +101,13 @@ public SwitchParameter Forward { return _forward; } + set { _forward = value; } } + private SwitchParameter _forward = new SwitchParameter(); /// @@ -111,11 +121,13 @@ public int MaxTriggerCount { return _maxTriggerCount; } + set { _maxTriggerCount = value <= 0 ? 0 : value; } } + private int _maxTriggerCount = 0; #endregion parameters @@ -137,6 +149,7 @@ protected PSEventSubscriber NewSubscriber { get { return _newSubscriber; } } + private PSEventSubscriber _newSubscriber; /// diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 5487028d9a3..2abdce0f034 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -90,6 +90,7 @@ internal void SetSystemConfigFilePath(string value) { throw new FileNotFoundException(value); } + FileInfo info = new FileInfo(value); systemWideConfigFile = info.FullName; systemWideConfigDirectory = info.Directory.FullName; @@ -109,6 +110,7 @@ internal string GetModulePath(ConfigScope scope) { modulePath = Environment.ExpandEnvironmentVariables(modulePath); } + return modulePath; } @@ -137,6 +139,7 @@ internal string GetExecutionPolicy(ConfigScope scope, string shellId) { execPolicy = rawExecPolicy; } + return execPolicy; } @@ -257,6 +260,7 @@ internal string GetSysLogIdentity() { identity = "powershell"; } + return identity; } @@ -277,6 +281,7 @@ internal PSLevel GetLogLevel() { level = PSLevel.Informational; } + return level; } diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 9342b46a01c..e1841db3355 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -274,10 +274,12 @@ internal static bool IsValidPSVersion(Version version) { return version.Minor == s_psV6Version.Minor; } + if (version.Major == s_psV5Version.Major) { return (version.Minor == s_psV5Version.Minor || version.Minor == s_psV51Version.Minor); } + if (version.Major == s_psV4Version.Major) { return (version.Minor == s_psV4Version.Minor); @@ -550,6 +552,7 @@ public SemanticVersion(Version version) { PreReleaseLabel = preLabelNote.Value as string; } + var buildLabelNote = psobj.Properties[BuildLabelPropertyName]; if (buildLabelNote != null) { @@ -941,6 +944,7 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) // A larger set of pre-release fields has a higher precedence than a smaller set, // if all of the preceding identifiers are equal. if (String.IsNullOrEmpty(preLabel1)) { return String.IsNullOrEmpty(preLabel2) ? 0 : 1; } + if (String.IsNullOrEmpty(preLabel2)) { return -1; } var units1 = preLabel1.Split('.'); @@ -963,6 +967,7 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) else { if (isNumber1) { return -1; } + if (isNumber2) { return 1; } int result = String.CompareOrdinal(ac, bc); @@ -1031,8 +1036,10 @@ internal Exception GetVersionParseException() { return e; } + break; } + return PSTraceSource.NewArgumentException("version"); } } diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 60da10d7068..d4e7b63136b 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -173,8 +173,10 @@ internal CommandLineParameters CommandLineParameters { // Setter is needed to pass into RuntimeParameterBinder instances set { _commandLineParameters = value; } + get { return _commandLineParameters ?? (_commandLineParameters = new CommandLineParameters()); } } + private CommandLineParameters _commandLineParameters; /// @@ -525,6 +527,7 @@ internal virtual bool BindParameter( e.Message); throw bindingException; } + s_tracer.WriteLine("Validation attribute on {0} returned {1}.", parameterMetadata.Name, result); } } @@ -641,6 +644,7 @@ internal virtual bool BindParameter( break; } } + stringToPrint = sb.ToString(); } else if (parameterValue != null) @@ -651,6 +655,7 @@ internal virtual bool BindParameter( catch (Exception) // Catch-all OK, 3rd party callout { } + if (stringToPrint != null) { cmdRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, stringToPrint); @@ -706,6 +711,7 @@ private void ValidateNullOrEmptyArgument( "ParameterArgumentValidationErrorNullNotAllowed"); throw bindingException; } + return; } @@ -734,6 +740,7 @@ private void ValidateNullOrEmptyArgument( "ParameterArgumentValidationErrorEmptyStringNotAllowed"); throw bindingException; } + return; } @@ -881,6 +888,7 @@ private bool ShouldContinueUncoercedBind( // type for the parameter. return false; } + parameterValue = encodedValue; return true; } @@ -1159,6 +1167,7 @@ private object CoerceTypeAsNeeded( throw pbe; } + break; } @@ -1327,6 +1336,7 @@ private static bool IsNullParameterValue(object currentValue) { result = true; } + return result; } @@ -1574,6 +1584,7 @@ private object EncodeCollection( "ArgumentException matching Add(T) for type {0}: {1}", toType.FullName, e.Message); getMethodError = e; } + if (addMethod == null) { ParameterBindingException bindingException = @@ -1970,6 +1981,7 @@ internal PSBoundParametersDictionary() private static readonly IDictionary s_emptyUsingParameters = new ReadOnlyDictionary(new Dictionary()); public List BoundPositionally { get; private set; } + internal IDictionary ImplicitUsingParameters { get; set; } } diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index e5f26a9d002..1c81d839d03 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -71,6 +71,7 @@ internal MergedCommandParameterMetadata BindableParameters { get { return _bindableParameters; } } + protected MergedCommandParameterMetadata _bindableParameters = new MergedCommandParameterMetadata(); /// @@ -220,6 +221,7 @@ internal void ReparseUnboundArguments() throw exception; } + ++index; argument.ParameterName = matchingParameter.Parameter.Name; argument.SetArgumentValue(nextArgument.ArgumentAst, nextArgument.ParameterText); @@ -364,6 +366,7 @@ internal static void AddArgumentsToCommandProcessor(CommandProcessorBase command { param = CommandParameterInternal.CreateArgument(arguments[argIndex]); } + commandProcessor.AddParameter(param); } } @@ -507,6 +510,7 @@ internal virtual bool BindParameter( UnboundParameters.Remove(parameter); BoundParameters.Add(parameter.Parameter.Name, parameter); } + return result; } @@ -716,6 +720,7 @@ out ParameterBindingException outgoingBindingException result = unboundArguments; } } + return result; } @@ -855,6 +860,7 @@ out ParameterBindingException bindingException } } } + return result; } @@ -916,6 +922,7 @@ private static CommandParameterInternal GetNextPositionalArgument( result = argument; break; } + nonPositionalArguments.Add(argument); // Now check to see if the next argument needs to be consumed as well. @@ -987,6 +994,7 @@ internal static SortedDictionary Type parameterType = Nullable.GetUnderlyingType(type) ?? type; parameterTypeString = ToStringCodeMethods.Type(parameterType, true); } + return parameterTypeString; } diff --git a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs index 7b9aeed2359..df1c71fc946 100644 --- a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs +++ b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs @@ -205,6 +205,7 @@ internal string GetHelpMessage(Cmdlet cmdlet) { helpInfo = HelpMessage; } + return helpInfo; } diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index 4613dd81ca2..c036dfa5953 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -41,12 +41,14 @@ internal class Pipe internal CommandProcessorBase DownstreamCmdlet { get { return _downstreamCmdlet; } + set { Diagnostics.Assert(_resultList == null, "Tried to set downstream cmdlet when _resultList not null"); _downstreamCmdlet = value; } } + private CommandProcessorBase _downstreamCmdlet; /// @@ -75,12 +77,14 @@ internal CommandProcessorBase DownstreamCmdlet internal PipelineWriter ExternalWriter { get { return _externalWriter; } + set { Diagnostics.Assert(_resultList == null, "Tried to set Pipe ExternalWriter when resultList not null"); _externalWriter = value; } } + private PipelineWriter _externalWriter; /// @@ -105,12 +109,14 @@ public override string ToString() internal bool NullPipe { get { return _nullPipe; } + set { _isRedirected = true; _nullPipe = value; } } + private bool _nullPipe; /// @@ -147,6 +153,7 @@ internal bool IsRedirected { get { return _downstreamCmdlet != null || _isRedirected; } } + private bool _isRedirected; /// @@ -214,6 +221,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) { _errorVariableList = new List(); } + _errorVariableList.Add(list); break; case VariableStreamKind.Warning: @@ -221,6 +229,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) { _warningVariableList = new List(); } + _warningVariableList.Add(list); break; case VariableStreamKind.Output: @@ -228,6 +237,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) { _outVariableList = new List(); } + _outVariableList.Add(list); break; case VariableStreamKind.Information: @@ -235,6 +245,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) { _informationVariableList = new List(); } + _informationVariableList.Add(list); break; } @@ -322,6 +333,7 @@ internal Pipe(List resultList) _isRedirected = true; _resultList = resultList; } + private readonly List _resultList; /// @@ -336,6 +348,7 @@ internal Pipe(System.Collections.ObjectModel.Collection resultCollecti _isRedirected = true; _resultCollection = resultCollection; } + private System.Collections.ObjectModel.Collection _resultCollection; /// @@ -366,6 +379,7 @@ internal Pipe(IEnumerator enumeratorToProcess) // assume that there is some stuff to read _enumeratorToProcessIsEmpty = false; } + private IEnumerator _enumeratorToProcess; private bool _enumeratorToProcessIsEmpty; @@ -553,6 +567,7 @@ internal object Retrieve() // again if it already reported completion. ExternalReader = null; } + return o; } catch (PipelineClosedException) diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 8f9c76794fc..a3f75f9673d 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -22,6 +22,7 @@ internal static Process GetParent(this Process process) { return null; } + var candidate = Process.GetProcessById(pid); // if the candidate was started later than process, the pid has been recycled diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index a4995e2ad60..0268397b924 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -44,10 +44,12 @@ class ProgressRecord throw PSTraceSource.NewArgumentOutOfRangeException("activityId", activityId, ProgressRecordStrings.ArgMayNotBeNegative, "activityId"); } + if (String.IsNullOrEmpty(activity)) { throw PSTraceSource.NewArgumentException("activity", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "activity"); } + if (String.IsNullOrEmpty(statusDescription)) { throw PSTraceSource.NewArgumentException("activity", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "statusDescription"); @@ -113,12 +115,14 @@ internal ProgressRecord(ProgressRecord other) { return parentId; } + set { if (value == ActivityId) { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ParentActivityIdCantBeActivityId); } + parentId = value; } } @@ -139,12 +143,14 @@ internal ProgressRecord(ProgressRecord other) { return activity; } + set { if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "value"); } + activity = value; } } @@ -161,12 +167,14 @@ internal ProgressRecord(ProgressRecord other) { return status; } + set { if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "value"); } + status = value; } } @@ -185,6 +193,7 @@ internal ProgressRecord(ProgressRecord other) { return currentOperation; } + set { // null or empty string is allowed @@ -206,6 +215,7 @@ internal ProgressRecord(ProgressRecord other) { return percent; } + set { // negative values are allowed @@ -239,6 +249,7 @@ internal ProgressRecord(ProgressRecord other) { return secondsRemaining; } + set { // negative values are allowed @@ -259,6 +270,7 @@ internal ProgressRecord(ProgressRecord other) { return type; } + set { if (value != ProgressRecordType.Completed && value != ProgressRecordType.Processing) @@ -331,6 +343,7 @@ public override { return null; } + TimeSpan remainingTime = totalTime - elapsedTime; return (int)(remainingTime.TotalSeconds); @@ -361,6 +374,7 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD { throw new ArgumentOutOfRangeException("startTime"); } + if (expectedDuration <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("expectedDuration"); diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 60ef0e9eaba..2f404f2005c 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -171,6 +171,7 @@ public static string GetBegin(CommandMetadata commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } + return commandMetadata.GetBeginBlock(); } @@ -194,6 +195,7 @@ public static string GetProcess(CommandMetadata commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } + return commandMetadata.GetProcessBlock(); } @@ -217,6 +219,7 @@ public static string GetDynamicParam(CommandMetadata commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } + return commandMetadata.GetDynamicParamBlock(); } @@ -240,6 +243,7 @@ public static string GetEnd(CommandMetadata commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } + return commandMetadata.GetEndBlock(); } @@ -250,6 +254,7 @@ private static T GetProperty(PSObject obj, string property) where T : class { result = obj.Properties[property].Value as T; } + return result; } @@ -262,6 +267,7 @@ private static string GetObjText(object obj) { text = GetProperty(psobj, "Text"); } + return text ?? obj.ToString(); } @@ -298,10 +304,12 @@ private static void AppendContent(StringBuilder sb, string section, PSObject[] a sb.Append(section); sb.Append("\n\n"); } + sb.Append(text); sb.Append("\n"); } } + if (!first) { sb.Append("\n"); @@ -412,11 +420,13 @@ public static string GetHelpComments(PSObject help) } } } + PSObject code = GetProperty(ex, "code"); if (code != null) { exsb.Append(code.ToString()); } + PSObject[] remarks = GetProperty(ex, "remarks"); if (remarks != null) { diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index cf9f9f7a2e5..6b1cf19d7cd 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -54,6 +54,7 @@ internal RuntimeDefinedParameterBinder( throw bindingException; } } + this.CommandLineParameters = commandLineParameters; } @@ -97,6 +98,7 @@ internal override object GetDefaultParameterValue(string name) { result = parameter.Value; } + return result; } diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index 616a7c44671..2c363998ce1 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -82,15 +82,18 @@ public string Name { return _name; } + set { if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("name"); } + _name = value; } } + private string _name = String.Empty; /// @@ -115,9 +118,11 @@ public Type ParameterType { throw PSTraceSource.NewArgumentNullException("value"); } + _parameterType = value; } } + private Type _parameterType; /// @@ -140,6 +145,7 @@ public object Value _value = value; } } + private object _value; /// @@ -169,12 +175,14 @@ internal bool IsDisabled() if (!hasSeenExpAttribute && attr is ExperimentalAttribute expAttribute) { if (expAttribute.ToHide) { return true; } + hasSeenExpAttribute = true; } else if (attr is ParameterAttribute paramAttribute) { hasParameterAttribute = true; if (paramAttribute.ToHide) { continue; } + hasEnabledParamAttribute = true; } } @@ -217,8 +225,10 @@ public RuntimeDefinedParameterDictionary() public string HelpFile { get { return _helpFile; } + set { _helpFile = String.IsNullOrEmpty(value) ? String.Empty : value; } } + private string _helpFile = String.Empty; /// diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index 2ef51fc52e0..25bf450c265 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -96,6 +96,7 @@ public bool MoveNext() result = true; break; } + result = false; if (_isSingleScopeLookup) @@ -181,6 +182,7 @@ internal SessionStateScope InitialScope { get { return _initialScope; } } + private SessionStateScope _initialScope; #region private members @@ -425,6 +427,7 @@ protected override bool GetScopeItem( { result = false; } + return result; } @@ -432,6 +435,7 @@ internal string Name { get { return _name; } } + private string _name = String.Empty; } @@ -477,6 +481,7 @@ protected override bool GetScopeItem( { result = false; } + return result; } } diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index dae14fe3d4a..d2747f2d5ae 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -78,6 +78,7 @@ internal ScriptParameterBinderController ScriptParameterBinderController _scriptParameterBinderController.CommandLineParameters.UpdateInvocationInfo(this.Command.MyInvocation); this.Command.MyInvocation.UnboundArguments = _scriptParameterBinderController.DollarArgs; } + return _scriptParameterBinderController; } } @@ -280,6 +281,7 @@ internal override ObsoleteAttribute ObsoleteAttribute { get { return _obsoleteAttribute; } } + private ObsoleteAttribute _obsoleteAttribute; internal override void Prepare(IDictionary psDefaultParameterValues) diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index fc052572506..17952b92508 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -121,6 +121,7 @@ internal override CommandMetadata CommandMetadata new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } + private CommandMetadata _commandMetadata; } } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 39140c2d556..880749d42f8 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -57,6 +57,7 @@ internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, Ex { throw PSTraceSource.NewArgumentNullException("context"); } + ExecutionContext = context; // Create the working directory stack. This @@ -144,6 +145,7 @@ internal LocationGlobber Globber { get { return _globberPrivate ?? (_globberPrivate = ExecutionContext.LocationGlobber); } } + private LocationGlobber _globberPrivate; /// @@ -157,8 +159,10 @@ internal LocationGlobber Globber internal SessionState PublicSessionState { get { return _publicSessionState ?? (_publicSessionState = new SessionState(this)); } + set { _publicSessionState = value; } } + private SessionState _publicSessionState; /// @@ -168,6 +172,7 @@ internal ProviderIntrinsics InvokeProvider { get { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } } + private ProviderIntrinsics _invokeProvider; /// @@ -193,6 +198,7 @@ internal PSLanguageMode LanguageMode { return ExecutionContext.LanguageMode; } + set { ExecutionContext.LanguageMode = value; @@ -403,6 +409,7 @@ private SessionStateEntryVisibility checkPathVisibility(List list, strin } } } + return SessionStateEntryVisibility.Private; } diff --git a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs index ac11d3e5aed..776c5fef201 100644 --- a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs @@ -155,6 +155,7 @@ internal IDictionary> GetCmdletTable() toBeAdded.Add(cmdletInfo); } } + result.Add(entry.Key, toBeAdded); } } @@ -199,6 +200,7 @@ internal IDictionary> GetCmdletTableAtScope(string scop toBeAdded.Add(cmdletInfo); } } + result.Add(entry.Key, toBeAdded); } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 3b61d0c07f0..cdc84f6b49f 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -137,6 +137,7 @@ internal bool ItemExists( { result = false; } + return result; } @@ -209,6 +210,7 @@ internal bool ItemExists( path, e); } + return result; } @@ -276,6 +278,7 @@ internal object ItemExistsDynamicParameters(string path, CmdletProviderContext c return ItemExistsDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -351,6 +354,7 @@ private object ItemExistsDynamicParameters( path, e); } + return result; } @@ -520,6 +524,7 @@ private bool IsValidPath( path, e); } + return result; } @@ -1102,6 +1107,7 @@ internal object RemoveItemDynamicParameters( return RemoveItemDynamicParameters(providerInstance, providerPaths[0], recurse, newContext); } + return null; } @@ -1181,6 +1187,7 @@ private object RemoveItemDynamicParameters( path, e); } + return result; } @@ -1639,6 +1646,7 @@ private bool IsPathContainer( throw; } } + return itemContainer; } @@ -2152,6 +2160,7 @@ private object GetChildItemsDynamicParameters( path, e); } + return result; } @@ -2849,6 +2858,7 @@ internal object GetChildNamesDynamicParameters( } } } + return result; } @@ -2925,6 +2935,7 @@ private object GetChildNamesDynamicParameters( path, e); } + return result; } @@ -3204,6 +3215,7 @@ internal object RenameItemDynamicParameters( return RenameItemDynamicParameters(providerInstance, providerPaths[0], newName, newContext); } + return null; } @@ -3284,6 +3296,7 @@ private object RenameItemDynamicParameters( path, e); } + return result; } @@ -3674,6 +3687,7 @@ internal object NewItemDynamicParameters( return NewItemDynamicParameters(providerInstance, providerPaths[0], type, newItemValue, newContext); } + return null; } @@ -3757,6 +3771,7 @@ private object NewItemDynamicParameters( path, e); } + return result; } @@ -4168,6 +4183,7 @@ internal void CopyItem( sourceIsRemote = true; session = dynamicParams.FromSession; } + if (dynamicParams.ToSession != null) { destinationIsRemote = true; @@ -4760,6 +4776,7 @@ private object CopyItemDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateContent.cs b/src/System.Management.Automation/engine/SessionStateContent.cs index 6f3f3ed0008..89b082981c8 100644 --- a/src/System.Management.Automation/engine/SessionStateContent.cs +++ b/src/System.Management.Automation/engine/SessionStateContent.cs @@ -215,6 +215,7 @@ private IContentReader GetContentReaderPrivate( path, e); } + return result; } @@ -351,6 +352,7 @@ private object GetContentReaderDynamicParameters( path, e); } + return result; } @@ -551,6 +553,7 @@ private IContentWriter GetContentWriterPrivate( path, e); } + return result; } @@ -617,6 +620,7 @@ internal object GetContentWriterDynamicParameters( return GetContentWriterDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -693,6 +697,7 @@ private object GetContentWriterDynamicParameters( path, e); } + return result; } @@ -940,6 +945,7 @@ internal object ClearContentDynamicParameters( return ClearContentDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -1015,6 +1021,7 @@ private object ClearContentDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 3c926afab0c..16d5224d39d 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -249,6 +249,7 @@ private static bool IsValidDriveName(string name) return result; } + private static char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; /// @@ -398,6 +399,7 @@ internal object NewDriveDynamicParameters(string providerId, CmdletProviderConte null, e); } + return result; } @@ -631,6 +633,7 @@ private PSDriveInfo AutomountFileSystemDrive(string name) // DriveNotFoundException which will be thrown by the caller } } + return result; } @@ -733,6 +736,7 @@ private PSDriveInfo AutomountFileSystemDrive(System.IO.DriveInfo systemDriveInfo e, Severity.Warning); } + return result; } @@ -1174,6 +1178,7 @@ internal void RemoveDrive( { ProvidersCurrentWorkingDrive[drive.Provider] = null; } + break; } } @@ -1415,6 +1420,7 @@ internal Collection Drives(string scope) { results.Add(drive); } + return results; } diff --git a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs index 49ec921b495..4f3b43fbaca 100644 --- a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs @@ -334,6 +334,7 @@ internal object NewPropertyDynamicParameters( return NewPropertyDynamicParameters(providerInstance, providerPaths[0], propertyName, type, value, newContext); } + return null; } @@ -422,6 +423,7 @@ private object NewPropertyDynamicParameters( path, e); } + return result; } @@ -698,6 +700,7 @@ internal object RemovePropertyDynamicParameters( return RemovePropertyDynamicParameters(providerInstance, providerPaths[0], propertyName, newContext); } + return null; } @@ -778,6 +781,7 @@ private object RemovePropertyDynamicParameters( path, e); } + return result; } @@ -1167,6 +1171,7 @@ internal object CopyPropertyDynamicParameters( destinationProperty, newContext); } + return null; } @@ -1260,6 +1265,7 @@ private object CopyPropertyDynamicParameters( path, e); } + return result; } @@ -1651,6 +1657,7 @@ internal object MovePropertyDynamicParameters( destinationProperty, newContext); } + return null; } @@ -1745,6 +1752,7 @@ private object MovePropertyDynamicParameters( path, e); } + return result; } @@ -2065,6 +2073,7 @@ internal object RenamePropertyDynamicParameters( destinationProperty, newContext); } + return null; } @@ -2153,6 +2162,7 @@ private object RenamePropertyDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 0d16ede8064..511e37d896f 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -116,6 +116,7 @@ internal IDictionary GetFunctionTableAtScope(string scopeI internal bool FunctionsExportedWithWildcard { get { return _functionsExportedWithWildcard; } + set { Dbg.Assert((value == true), "This property should never be set/reset to false"); @@ -125,6 +126,7 @@ internal bool FunctionsExportedWithWildcard } } } + private bool _functionsExportedWithWildcard; /// @@ -650,6 +652,7 @@ internal FunctionInfo SetFunction( result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } + return result; } @@ -726,6 +729,7 @@ internal void RemoveFunction(string name, bool force, CommandOrigin origin) { scope = searcher.CurrentLookupScope; } + scope.RemoveFunction(name, force); } diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index 3ad73b0aef9..65de4586e2c 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -271,6 +271,7 @@ internal object GetItemDynamicParameters(string path, CmdletProviderContext cont return GetItemDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -346,6 +347,7 @@ private object GetItemDynamicParameters( path, e); } + return result; } @@ -616,6 +618,7 @@ internal object SetItemDynamicParameters(string path, object value, CmdletProvid return SetItemDynamicParameters(providerInstance, providerPaths[0], value, newContext); } + return null; } @@ -695,6 +698,7 @@ private object SetItemDynamicParameters( path, e); } + return result; } @@ -956,6 +960,7 @@ internal object ClearItemDynamicParameters(string path, CmdletProviderContext co return ClearItemDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -1031,6 +1036,7 @@ private object ClearItemDynamicParameters( path, e); } + return result; } @@ -1281,6 +1287,7 @@ internal object InvokeDefaultActionDynamicParameters(string path, CmdletProvider return InvokeDefaultActionDynamicParameters(providerInstance, providerPaths[0], newContext); } + return null; } @@ -1356,6 +1363,7 @@ private object InvokeDefaultActionDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index ebfdfa5f33a..b58484f7d86 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -122,6 +122,7 @@ internal PathInfo GetNamespaceCurrentLocation(string namespaceID) { path = LocationGlobber.GetDriveQualifiedPath(drive.CurrentLocation, drive); } + return new PathInfo(drive, drive.Provider, path, new SessionState(this)); } @@ -916,6 +917,7 @@ internal PathInfo PopLocation(string stackName) SessionStateStrings.StackNameResolvedToMultiple, stackName); } + haveMatch = true; stackName = key; } @@ -937,6 +939,7 @@ internal PathInfo PopLocation(string stackName) SessionStateStrings.StackNotFound, stackName); } + return null; } @@ -1063,6 +1066,7 @@ internal PathInfoStack SetDefaultLocationStack(string stackName) { return new PathInfoStack(_defaultStackName, locationStack); } + return null; } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 676fe80340c..cbc22b87329 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -430,6 +430,7 @@ internal string GetParentPath( path, e); } + return result; } @@ -830,6 +831,7 @@ internal string MakePath( { provider = CurrentDrive.Provider; } + if (context.Drive == null) { bool isProviderQualified = LocationGlobber.IsProviderQualifiedPath(parent); @@ -845,12 +847,14 @@ internal string MakePath( { drive = provider.HiddenDrive; } + context.Drive = drive; } else { context.Drive = CurrentDrive; } + result = MakePath(provider, parent, child, context); if (isAbsolute) @@ -867,6 +871,7 @@ internal string MakePath( provider = context.Drive.Provider; result = MakePath(provider, parent, child, context); } + return result; } @@ -1279,6 +1284,7 @@ bool acceptNonContainerProviders path, e); } + return result; } @@ -1646,6 +1652,7 @@ internal object MoveItemDynamicParameters( return MoveItemDynamicParameters(providerInstance, providerPaths[0], destination, newContext); } + return null; } @@ -1730,6 +1737,7 @@ private object MoveItemDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index abbb493271c..806619f984b 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -288,6 +288,7 @@ internal object GetPropertyDynamicParameters( return GetPropertyDynamicParameters(providerInstance, providerPaths[0], providerSpecificPickList, newContext); } + return null; } @@ -368,6 +369,7 @@ private object GetPropertyDynamicParameters( path, e); } + return result; } @@ -658,6 +660,7 @@ internal object SetPropertyDynamicParameters( return SetPropertyDynamicParameters(providerInstance, providerPaths[0], propertyValue, newContext); } + return null; } @@ -738,6 +741,7 @@ private object SetPropertyDynamicParameters( path, e); } + return result; } @@ -1018,6 +1022,7 @@ internal object ClearPropertyDynamicParameters( return ClearPropertyDynamicParameters(providerInstance, providerPaths[0], propertyToClear, newContext); } + return null; } @@ -1099,6 +1104,7 @@ private object ClearPropertyDynamicParameters( path, e); } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index 2bc6d2cc61e..5c5bd0b586a 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -31,6 +31,7 @@ internal Dictionary> Providers return ExecutionContext.TopLevelSessionState.Providers; } } + private Dictionary> _providers = new Dictionary>( SessionStateConstants.DefaultDictionaryCapacity, StringComparer.OrdinalIgnoreCase); @@ -49,6 +50,7 @@ internal Dictionary ProvidersCurrentWorkingDrive return ExecutionContext.TopLevelSessionState.ProvidersCurrentWorkingDrive; } } + private Dictionary _providersCurrentWorkingDrive = new Dictionary(); /// @@ -118,6 +120,7 @@ private ProviderInfo AddProvider(Type implementingType, string name, string help // NTRAID#Windows OS Bugs-1009281-2004/02/11-JeffJon this.ExecutionContext.ReportEngineStartupError(e); } + return provider; } @@ -226,6 +229,7 @@ private PSDriveInfo ValidateDriveWithProvider( { drive.DriveBeingCreated = false; } + return result; } @@ -791,6 +795,7 @@ internal Collection GetProvider(string name) throw e; } + return GetProvider(providerName); } @@ -834,6 +839,7 @@ internal ProviderInfo GetSingleProvider(string name) throw NewAmbiguousProviderName(name, matchingProviders); } } + return matchingProviders[0]; } @@ -901,6 +907,7 @@ internal Collection GetProvider(PSSnapinQualifiedName providerName result.Add(provider); } } + return result; } @@ -920,6 +927,7 @@ internal IEnumerable ProviderList result.Add(provider); } } + return result; } } @@ -1285,6 +1293,7 @@ private ProviderInfo ProviderExists(ProviderInfo provider) } } } + return null; } @@ -1569,6 +1578,7 @@ internal int ProviderCount { count += matchingProviders.Count; } + return count; } } diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index f6fd38b7998..5b6be707eab 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -120,6 +120,7 @@ public PSVariableIntrinsics PSVariable public PSLanguageMode LanguageMode { get { return _sessionState.LanguageMode; } + set { _sessionState.LanguageMode = value; } } @@ -198,6 +199,7 @@ public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) throw exception; } + CommandInfo cinfo = valueToCheck as CommandInfo; if (cinfo != null) { @@ -255,6 +257,7 @@ public static bool IsVisible(CommandOrigin origin, object valueToCheck) { return (obj.Visibility == SessionStateEntryVisibility.Public); } + return true; } /// @@ -271,6 +274,7 @@ public static bool IsVisible(CommandOrigin origin, PSVariable variable) { throw PSTraceSource.NewArgumentNullException("variable"); } + return (variable.Visibility == SessionStateEntryVisibility.Public); } /// @@ -287,6 +291,7 @@ public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo) { throw PSTraceSource.NewArgumentNullException("commandInfo"); } + return (commandInfo.Visibility == SessionStateEntryVisibility.Public); } diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 7c4d863c28d..d6ba0d6c719 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -65,12 +65,14 @@ internal SessionStateScope(SessionStateScope parentScope) internal SessionStateScope ScriptScope { get { return _scriptScope; } + set { Diagnostics.Assert(value != null, "Caller to verify scope is not null"); _scriptScope = value; } } + private SessionStateScope _scriptScope; /// @@ -94,6 +96,7 @@ internal SessionStateScope ScriptScope /// other variables use the variable apis to find the variable and get/set it. /// internal Stack DottedScopes { get { return _dottedScopes; } } + private readonly Stack _dottedScopes = new Stack(); #region Drives @@ -231,6 +234,7 @@ internal PSDriveInfo GetDrive(string name) // manually removed drives. GetAutomountedDrives().TryGetValue(name, out result); } + return result; } @@ -257,6 +261,7 @@ internal IEnumerable Drives result.Add(drive); } } + return result; } } @@ -327,6 +332,7 @@ internal bool TryGetVariable(string name, CommandOrigin origin, bool fromNewOrSe SessionState.ThrowIfNotVisible(origin, variable); return true; } + return false; } @@ -403,6 +409,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo { throw new NotImplementedException("fastPath"); } + variable = new PSVariable(name, variableToSet.Value, variableToSet.Options, variableToSet.Attributes) { Description = variableToSet.Description }; GetPrivateVariables()[name] = variable; return variable; @@ -966,6 +973,7 @@ internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin RemoveAliasFromCache(aliasInfo.Name, aliasInfo.Definition); } + aliasInfos[aliasToSet.Name] = aliasToSet; AddAliasToCache(aliasToSet.Name, aliasToSet.Definition); @@ -1366,6 +1374,7 @@ internal void RemoveFunction(string name, bool force) GetAllScopeFunctions().Remove(name); } } + functionInfos.Remove(name); } diff --git a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs index 79e666e5008..ebb7b455540 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs @@ -195,6 +195,7 @@ internal SessionStateScope CurrentScope inGlobalScopeLineage = true; break; } + scope = scope.Parent; } @@ -237,6 +238,7 @@ internal SessionStateScope NewScope(bool isScriptScope) { newScope.ScriptScope = newScope; } + return newScope; } @@ -315,6 +317,7 @@ internal void RemoveScope(SessionStateScope scope) { _currentScope = _currentScope.Parent; } + scope.Parent = null; } } diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 14cd8b53d61..801670e5ba4 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -124,6 +124,7 @@ internal static Collection ConvertArrayToCollection(T[] array) result.Add(element); } } + return result; } @@ -175,6 +176,7 @@ internal static bool CollectionContainsValue(IEnumerable collection, object valu } } } + return result; } diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index c0519ac1698..310c264e02b 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -556,6 +556,7 @@ internal PSVariable GetVariableItem( result = ((IEnumerator)searcher).Current; scope = searcher.CurrentLookupScope; } + return result; } @@ -1138,6 +1139,7 @@ internal object SetVariable( { throw PSTraceSource.NewArgumentNullException("variablePath"); } + CmdletProviderContext context = null; SessionStateScope scope = null; @@ -1178,6 +1180,7 @@ internal object SetVariable( { varResult.Options = varResult.Options | ScopedItemOptions.Private; } + result = varResult; } else @@ -1359,6 +1362,7 @@ internal object SetVariable( } #endif } + return result; } diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index b53f53a7c1e..cc51d5adc63 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -213,11 +213,13 @@ public virtual string Description { return _description; } + set { _description = value; } } + private string _description = String.Empty; internal void DebuggerCheckVariableRead() @@ -265,6 +267,7 @@ public virtual object Value SetValue(value); } } + private object _value; /// @@ -372,6 +375,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) _options = newOptions; } + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -385,6 +389,7 @@ public Collection Attributes { get { return _attributes ?? (_attributes = new PSVariableAttributeCollection(this)); } } + private PSVariableAttributeCollection _attributes; /// @@ -417,6 +422,7 @@ internal static bool IsValidValue(IEnumerable attributes, object valu } } } + return true; } @@ -458,6 +464,7 @@ internal static bool IsValidValue(object value, Attribute attribute) result = false; } } + return result; } @@ -502,6 +509,7 @@ internal static object TransformValue(IEnumerable attributes, object result = transformationAttribute.TransformInternal(engine, result); } } + return result; } @@ -581,6 +589,7 @@ internal bool WasRemoved { return _wasRemoved; } + set { _wasRemoved = value; @@ -594,6 +603,7 @@ internal bool WasRemoved } } } + private bool _wasRemoved; internal SessionStateInternal SessionState { get; set; } @@ -667,6 +677,7 @@ private void SetValueRawImpl(object newValue, bool preserveValueTypeSemantics) { newValue = CopyMutableValues(newValue); } + _value = newValue; } @@ -748,6 +759,7 @@ public LocalVariable(string name, MutableTuple tuple, int tupleSlot) public override ScopedItemOptions Options { get { return base.Options; } + set { // Throw, but only if someone is actually changing the options. @@ -772,6 +784,7 @@ public override object Value DebuggerCheckVariableRead(); return _tuple.GetValue(_tupleSlot); } + set { _tuple.SetValue(_tupleSlot, value); @@ -785,6 +798,7 @@ internal override void SetValueRaw(object newValue, bool preserveValueTypeSemant { newValue = CopyMutableValues(newValue); } + this.Value = newValue; } } @@ -826,8 +840,10 @@ public override object Value public override string Description { get { return _description ?? (_description = SessionStateStrings.DollarNullDescription); } + set { /* Do nothing */ } } + private string _description; /// @@ -836,6 +852,7 @@ public override string Description public override ScopedItemOptions Options { get { return ScopedItemOptions.None; } + set { /* Do nothing */ } } } diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index 7d401f33758..487648377cc 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -91,6 +91,7 @@ internal static class SpecialVariables internal static readonly VariablePath LastTokenVarPath = new VariablePath("global:" + LastToken); internal static bool IsUnderbar(string name) { return name.Length == 1 && name[0] == '_'; } + internal const string PSItem = "PSItem"; // simple alias for $_ internal const string Underbar = "_"; internal static readonly VariablePath UnderbarVarPath = new VariablePath(Underbar); diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index 5b13bc9be22..a50e6d4fc7f 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -63,6 +63,7 @@ void IEnlistmentNotification.InDoubt(Enlistment enlistment) { enlistment.Done(); } + void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) { preparingEnlistment.Prepared(); diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs index 72f87048d32..de1d16b5e09 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -77,8 +77,10 @@ public int SubscriberCount return _subscriberCount; } + set { _subscriberCount = value; } } + private int _subscriberCount; /// @@ -148,11 +150,13 @@ internal bool IsRolledBack return _isRolledBack; } + set { _isRolledBack = value; } } + private bool _isRolledBack = false; /// @@ -210,6 +214,7 @@ internal PSTransactionContext(PSTransactionManager transactionManager) _transactionManager = transactionManager; transactionManager.SetActive(); } + private PSTransactionManager _transactionManager; /// @@ -310,6 +315,7 @@ internal static void EnableEngineProtection() { s_engineProtectionEnabled = true; } + private static bool s_engineProtectionEnabled = false; /// @@ -578,6 +584,7 @@ internal void SetActive() _previousActiveTransaction = Transaction.Current; currentTransaction.Activate(); } + private Transaction _previousActiveTransaction; /// diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 80b02788b03..8ff2a6017e8 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -94,6 +94,7 @@ public int Position { return _position; } + set { _position = value; @@ -109,6 +110,7 @@ public bool ValueFromPipeline { return _valueFromPipeline; } + set { _valueFromPipeline = value; @@ -125,6 +127,7 @@ public bool ValueFromPipelineByPropertyName { return _valueFromPipelineByPropertyName; } + set { _valueFromPipelineByPropertyName = value; @@ -142,6 +145,7 @@ public bool ValueFromRemainingArguments { return _valueFromRemainingArguments; } + set { _valueFromRemainingArguments = value; @@ -157,6 +161,7 @@ public string HelpMessage { return _helpMessage; } + set { _helpMessage = value; @@ -172,6 +177,7 @@ public string HelpMessageBaseName { return _helpMessageBaseName; } + set { _helpMessageBaseName = value; @@ -187,6 +193,7 @@ public string HelpMessageResourceId { return _helpMessageResourceId; } + set { _helpMessageResourceId = value; @@ -257,11 +264,16 @@ internal ParameterFlags Flags { ParameterFlags flags = 0; if (IsMandatory) { flags = flags | ParameterFlags.Mandatory; } + if (ValueFromPipeline) { flags = flags | ParameterFlags.ValueFromPipeline; } + if (ValueFromPipelineByPropertyName) { flags = flags | ParameterFlags.ValueFromPipelineByPropertyName; } + if (ValueFromRemainingArguments) { flags = flags | ParameterFlags.ValueFromRemainingArguments; } + return flags; } + set { this.IsMandatory = (ParameterFlags.Mandatory == (value & ParameterFlags.Mandatory)); @@ -553,6 +565,7 @@ public Dictionary ParameterSets public bool IsDynamic { get { return _isDynamic; } + set { _isDynamic = value; } } /// @@ -691,6 +704,7 @@ internal bool IsMatchingType(PSTypeName psTypeName) { return parameterAcceptsObjects; } + if (parameterAcceptsObjects) { return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); @@ -716,10 +730,12 @@ internal bool IsMatchingType(PSTypeName psTypeName) { return true; } + if (this.ParameterType.IsArray && wildcardPattern.IsMatch((this.ParameterType.GetElementType().FullName))) { return true; } + if (this.Attributes != null) { PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType().FirstOrDefault(); @@ -728,6 +744,7 @@ internal bool IsMatchingType(PSTypeName psTypeName) return true; } } + return false; } @@ -792,11 +809,13 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); separator = ", "; } + if (!string.IsNullOrEmpty(paramSetData)) { result.Append(separator); result.Append(paramSetData); } + result.Append(")]"); } } @@ -900,6 +919,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) { format = ValidateRangeFormat; } + result = string.Format(CultureInfo.InvariantCulture, format, prefix, validRangeAttrib.MinRange, validRangeAttrib.MaxRange); @@ -1138,6 +1158,7 @@ internal static InternalParameterMetadata Get(Type type, ExecutionContext contex s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } } + return result; } @@ -1169,6 +1190,7 @@ internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefi { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameters"); } + ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames); } @@ -1216,6 +1238,7 @@ internal InternalParameterMetadata(Type type, bool processingDynamicParameters) /// the values are the compiled parameter metadata. /// internal Dictionary BindableParameters { get; } + = new Dictionary(StringComparer.OrdinalIgnoreCase); /// @@ -1223,6 +1246,7 @@ internal InternalParameterMetadata(Type type, bool processingDynamicParameters) /// the alias name and the value is the CompiledCommandParameter metadata. /// internal Dictionary AliasedParameters { get; } + = new Dictionary(StringComparer.OrdinalIgnoreCase); /// @@ -1423,6 +1447,7 @@ private void AddParameter(CompiledCommandParameter parameter, bool checkNames) DiscoveryExceptions.AliasDeclaredMultipleTimes, alias); } + AliasedParameters.Add(alias, parameter); } } @@ -1468,6 +1493,7 @@ private static bool IsMemberAParameter(MemberInfo member) break; } } + return hasAnyVisibleParamAttributes; } catch (MetadataException metadataException) diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index b91b9b3cdb7..84ac917b15f 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -50,6 +50,7 @@ private string ReadElementString(string nodeName) _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NodeShouldHaveInnerText, nodeName); return null; } + if (!_reader.IsEmptyElement) { _reader.Read(); @@ -61,11 +62,13 @@ private string ReadElementString(string nodeName) break; } } + if (_reader.NodeType != XmlNodeType.EndElement) { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NodeShouldHaveInnerText, nodeName); return null; } + result = result.Trim(); _reader.Read(); } @@ -73,11 +76,13 @@ private string ReadElementString(string nodeName) { _reader.Read(); } + if (string.IsNullOrWhiteSpace(result)) { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NodeShouldHaveInnerText, nodeName); return null; } + return result; } @@ -195,6 +200,7 @@ private Type ResolveType(string typeName, int line) { _context.AddError(line, ParserStrings.TypeNotFound, typeName); } + return type; } @@ -244,6 +250,7 @@ private void CheckStandardNote(TypeMemberData member, TypeData typeData, Acti { value = (T)note.Value; } + setter(typeData, value); } else @@ -318,8 +325,10 @@ private IEnumerable Read_Types() { UnknownNode(_idTypes, "Type"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -377,8 +386,10 @@ private TypeData Read_Type() { UnknownNode(_idType, "Name,Members,TypeConverter,TypeAdapter"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -404,6 +415,7 @@ private TypeData Read_Type() typeData.Members.Add(m.Name, m); } } + typeData.TypeAdapter = typeAdapter; typeData.TypeConverter = typeConverter; @@ -470,6 +482,7 @@ private TypeData Read_Type() } } } + return typeData; } @@ -510,8 +523,10 @@ private Type Read_TypeX(string elementName) { UnknownNode(elementName, "TypeName"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -608,8 +623,10 @@ private Collection Read_Members(out MemberSetData standardMember { UnknownNode(_idMembers, "NoteProperty,AliasProperty,ScriptProperty,CodeProperty,ScriptMethod,CodeMethod,PropertySet,MemberSet"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -670,8 +687,10 @@ private MemberSetData Read_MemberSet() { UnknownNode(_idMemberSet, "Name,InheritMembers,Members"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -692,6 +711,7 @@ private MemberSetData Read_MemberSet() { result.InheritMembers = inheritMembers.Value; } + return result; } @@ -750,8 +770,10 @@ private PropertySetData Read_PropertySet() { UnknownNode(_idPropertySet, "Name"); } + _reader.MoveToContent(); } + ReadEndElement(); } } @@ -764,8 +786,10 @@ private PropertySetData Read_PropertySet() { UnknownNode(_idPropertySet, "Name,ReferencedProperties"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -829,8 +853,10 @@ private CodeMethodData Read_CodeMethod() { UnknownNode(_idCodeMethod, "Name,CodeReference"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -892,8 +918,10 @@ private MethodInfo Read_CodeReference() { UnknownNode(_idCodeReference, "TypeName,MethodName"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -965,8 +993,10 @@ private ScriptMethodData Read_ScriptMethod() { UnknownNode(_idScriptMethod, "Name,Script"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -974,6 +1004,7 @@ private ScriptMethodData Read_ScriptMethod() { NodeNotFound(lineNumber, _idName, _idScriptMethod); } + if (string.IsNullOrWhiteSpace(script)) { NodeNotFound(lineNumber, _idScript, _idScriptMethod); @@ -1042,8 +1073,10 @@ private CodePropertyData Read_CodeProperty() { UnknownNode(_idCodeProperty, "Name,GetCodeReference,SetCodeReference"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -1116,8 +1149,10 @@ private ScriptPropertyData Read_ScriptProperty() { UnknownNode(_idScriptProperty, "Name,GetScriptBlock,SetScriptBlock"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -1125,6 +1160,7 @@ private ScriptPropertyData Read_ScriptProperty() { NodeNotFound(lineNumber, _idName, _idScriptProperty); } + if (string.IsNullOrWhiteSpace(getScriptBlock) && string.IsNullOrWhiteSpace(setScriptBlock)) { _context.AddError(lineNumber, TypesXmlStrings.ScriptPropertyShouldHaveGetterOrSetter); @@ -1191,6 +1227,7 @@ private AliasPropertyData Read_AliasProperty() { UnknownNode(_idAliasProperty, "Name,ReferencedMemberName,TypeName"); } + _reader.MoveToContent(); } @@ -1201,10 +1238,12 @@ private AliasPropertyData Read_AliasProperty() { NodeNotFound(lineNumber, _idName, _idAliasProperty); } + if (string.IsNullOrWhiteSpace(referencedMemberName)) { NodeNotFound(lineNumber, _idReferencedMemberName, _idAliasProperty); } + Type convertToType = (typeName != null) ? ResolveType(typeName, typeLineNumber) : null; if (_context.errors.Count != errorCount) return null; @@ -1264,8 +1303,10 @@ private NotePropertyData Read_NoteProperty() { UnknownNode(_idNoteProperty, "Name,Value,TypeName"); } + _reader.MoveToContent(); } + ReadEndElement(); } @@ -1273,6 +1314,7 @@ private NotePropertyData Read_NoteProperty() { NodeNotFound(lineNumber, _idName, _idNoteProperty); } + if (string.IsNullOrWhiteSpace(valueAsString)) { NodeNotFound(lineNumber, _idValue, _idNoteProperty); @@ -1375,6 +1417,7 @@ protected override void SetItem(int index, string item) { throw PSTraceSource.NewArgumentException("item"); } + base.SetItem(index, item); UpdateKey(); } @@ -1391,6 +1434,7 @@ protected override void InsertItem(int index, string item) { throw PSTraceSource.NewArgumentException("item"); } + base.InsertItem(index, item); UpdateKey(); } @@ -1402,6 +1446,7 @@ protected override void RemoveItem(int index) } internal string Key { get; private set; } + internal bool IsReadOnly { get { return ((ICollection)this).IsReadOnly; } } private void UpdateKey() @@ -1439,6 +1484,7 @@ public ConsolidatedString(IEnumerable strings) throw PSTraceSource.NewArgumentException("strings"); } } + UpdateKey(); } @@ -1480,6 +1526,7 @@ internal LoadContext(string PSSnapinName, string fileName, ConcurrentBag internal bool IsFullyTrusted { get { return isFullyTrusted; } + set { isFullyTrusted = value; } } @@ -1735,6 +1782,7 @@ public TypeData(Type type) : this() public string SerializationMethod { get { return _serializationMethod; } + set { _serializationMethod = value; @@ -1763,6 +1811,7 @@ public string SerializationMethod public Type TargetTypeForDeserialization { get { return _targetTypeForDeserialization; } + set { _targetTypeForDeserialization = value; @@ -1791,6 +1840,7 @@ public Type TargetTypeForDeserialization public uint SerializationDepth { get { return _serializationDepth; } + set { _serializationDepth = value; @@ -1814,6 +1864,7 @@ public uint SerializationDepth public string DefaultDisplayProperty { get { return _defaultDisplayProperty; } + set { _defaultDisplayProperty = value; @@ -1842,6 +1893,7 @@ public string DefaultDisplayProperty public bool InheritPropertySerializationSet { get { return _inheritPropertySerializationSet; } + set { _inheritPropertySerializationSet = value; @@ -1864,6 +1916,7 @@ public bool InheritPropertySerializationSet public string StringSerializationSource { get { return _stringSerializationSource; } + set { if (value == null) @@ -1875,6 +1928,7 @@ public string StringSerializationSource { StandardMembers.Remove(TypeTable.StringSerializationSource); } + _stringSerializationSource = null; return; } @@ -1907,6 +1961,7 @@ public string StringSerializationSource public TypeMemberData StringSerializationSourceProperty { get { return _stringSerializationSourceProperty; } + set { if (value == null) @@ -1918,6 +1973,7 @@ public TypeMemberData StringSerializationSourceProperty { StandardMembers.Remove(TypeTable.StringSerializationSource); } + _stringSerializationSourceProperty = null; return; } @@ -1943,6 +1999,7 @@ public TypeMemberData StringSerializationSourceProperty public PropertySetData DefaultDisplayPropertySet { get { return _defaultDisplayPropertySet; } + set { _defaultDisplayPropertySet = value; @@ -1959,6 +2016,7 @@ public PropertySetData DefaultDisplayPropertySet public PropertySetData DefaultKeyPropertySet { get { return _defaultKeyPropertySet; } + set { _defaultKeyPropertySet = value; @@ -1975,6 +2033,7 @@ public PropertySetData DefaultKeyPropertySet public PropertySetData PropertySerializationSet { get { return _propertySerializationSet; } + set { _propertySerializationSet = value; @@ -2049,6 +2108,7 @@ public TypeData Copy() break; } } + newTypeData.DefaultDisplayPropertySet = this.DefaultDisplayPropertySet == null ? null : (PropertySetData)this.DefaultDisplayPropertySet.Copy(); @@ -2633,11 +2693,13 @@ private static void AddMember(ConcurrentBag errors, string typeName, PSM AddError(errors, typeName, TypesXmlStrings.ReservedNameMember, member.name); return; } + if (membersCollection[member.name] != null && !isOverride) { AddError(errors, typeName, TypesXmlStrings.DuplicateMember, member.name); return; } + member.IsInstance = false; if (membersCollection[member.name] == null) @@ -2690,9 +2752,11 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, { note.noteValue = String.Compare(sourceValueAsString, "false", StringComparison.OrdinalIgnoreCase) != 0; } + return true; } } + try { note.noteValue = LanguagePrimitives.ConvertTo(sourceValue, noteType, CultureInfo.InvariantCulture); @@ -2702,6 +2766,7 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, AddError(errors, typeName, TypesXmlStrings.ErrorConvertingNote, note.Name, e.Message); return false; } + return true; } @@ -2716,6 +2781,7 @@ private static bool EnsureNotPresent(ConcurrentBag errors, string typeNa return false; } } + return true; } @@ -2777,6 +2843,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty break; } } + if (!found) { membersToBeIgnored.Add(memberName); @@ -2801,6 +2868,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty { serializationMethod = (SerializationMethod)serializationMethodNote.Value; } + if (serializationMethod == SerializationMethod.String) { serializationSettingsOk = EnsureNotPresent(errors, typeName, members, InheritPropertySerializationSet); @@ -2830,6 +2898,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty serializationSettingsOk = false; break; } + PSNoteProperty noteProperty; serializationSettingsOk = GetCheckNote(errors, typeName, members, SerializationDepth, typeof(int), out noteProperty); if (!serializationSettingsOk) break; @@ -2866,17 +2935,20 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty { members.Remove(DefaultDisplayPropertySet); } + if (!GetCheckMemberType(errors, typeName, members, DefaultKeyPropertySet, typeof(PSPropertySet), out otherMember)) { members.Remove(DefaultKeyPropertySet); } + PSNoteProperty defaultDisplayProperty; if (!GetCheckNote(errors, typeName, members, DefaultDisplayProperty, typeof(string), out defaultDisplayProperty)) { members.Remove(DefaultDisplayProperty); } + PSNoteProperty targetTypeForDeserialization; if (!GetCheckNote(errors, typeName, members, TargetTypeForDeserialization, typeof(Type), out targetTypeForDeserialization)) @@ -3049,6 +3121,7 @@ internal static void ProcessCodeMethodData(ConcurrentBag errors, string AddError(errors, typeName, TypesXmlStrings.Exception, exception.Message); return; } + AddMember(errors, typeName, codeMethod, membersCollection, isOverride); } @@ -3069,6 +3142,7 @@ internal static void ProcessPropertySetData(ConcurrentBag errors, string AddError(errors, typeName, TypesXmlStrings.TypeDataShouldNotBeNullOrEmpty, "PropertySetData", "ReferencedProperties"); continue; } + referencedProperties.Add(name); } @@ -3091,6 +3165,7 @@ internal static void ProcessMemberSetData(ConcurrentBag errors, string t { m.Process(errors, typeName, memberSetMembers, isOverride); } + var memberSet = new PSMemberSet(memberSetData.Name, memberSetMembers) { IsHidden = memberSetData.IsHidden, @@ -3164,6 +3239,7 @@ private static void ProcessStandardMembers(ConcurrentBag errors, string oldMembersCopy.Add(member); } } + PSMemberSet standardMemberSet = new PSMemberSet(PSStandardMembers, oldMembersCopy) { inheritMembers = true, @@ -3184,10 +3260,12 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat { propertySets.Add(typeData.DefaultDisplayPropertySet); } + if (typeData.DefaultKeyPropertySet != null) { propertySets.Add(typeData.DefaultKeyPropertySet); } + if (typeData.PropertySerializationSet != null) { propertySets.Add(typeData.PropertySerializationSet); @@ -3219,6 +3297,7 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat { typeMembers = _extendedMembers.GetOrAdd(typeName, k => new PSMemberInfoInternalCollection()); } + ProcessStandardMembers(errors, typeName, typeData.StandardMembers.Values, propertySets, typeMembers, typeData.IsOverride); } @@ -3382,6 +3461,7 @@ static TypeTable() { PSGetMemberBinder.TypeTableMemberAdded(sm); } + PSGetMemberBinder.TypeTableMemberAdded(PSStandardMembers); } @@ -3506,6 +3586,7 @@ internal Collection GetSpecificProperties(ConsolidatedString types) { return new Collection(); } + Collection result = _consolidatedSpecificProperties.GetOrAdd(types.Key, key => { var retValueTable = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -3521,6 +3602,7 @@ internal Collection GetSpecificProperties(ConsolidatedString types) { retValueTable.Add(reference); } + bool inherit = (bool)PSObject.GetNoteSettingValue(settings, InheritPropertySerializationSet, defaultInheritPropertySerializationSet, typeof(bool), false, null); if (!inherit) @@ -3528,11 +3610,13 @@ internal Collection GetSpecificProperties(ConsolidatedString types) break; } } + var retValue = new Collection(); foreach (var value in retValueTable) { retValue.Add(value); } + return retValue; }); return result; @@ -3728,6 +3812,7 @@ private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) { membersData.Add(GetTypeMemberDataFromPSMemberInfo(m)); } + return new MemberSetData(memberSet.Name, membersData); } @@ -3913,6 +3998,7 @@ private bool RetrieveMembersToTypeData(TypeData typeData) PSMemberInfo newMember = member.Copy(); LoadMembersToTypeData(newMember, typeData); } + return true; } @@ -4007,6 +4093,7 @@ internal void Clear() { LanguagePrimitives.UpdateTypeConvertFromTypeTable(conv); } + _typeConverters.Clear(); foreach (var ml in _extendedMembers.Values) @@ -4016,6 +4103,7 @@ internal void Clear() PSGetMemberBinder.TypeTableMemberPossiblyUpdated(m.Name); } } + _extendedMembers.Clear(); StandardMembersUpdated(); @@ -4038,6 +4126,7 @@ private static void StandardMembersUpdated() { PSGetMemberBinder.TypeTableMemberPossiblyUpdated(sm); } + PSGetMemberBinder.TypeTableMemberPossiblyUpdated(PSStandardMembers); } @@ -4369,6 +4458,7 @@ internal void Update( UpdateWithModuleContents(fileContents, moduleName, filePath, isFullyTrusted, isProductCode, errors); } } + if (etwEnabled) RunspaceEventSource.Log.ProcessTypeFileStop(filePath); } diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index c22ec203072..8b71076ad82 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -873,6 +873,7 @@ public static IEnumerable Get() new ScriptPropertyData(@"AccessToString", GetScriptBlock(@"$toString = """"; $first = $true; if ( ! $this.Access ) { return """" } + foreach($ace in $this.Access) { if($first) @@ -883,6 +884,7 @@ public static IEnumerable Get() { $tostring += ""`n""; } + $toString += $ace.IdentityReference.ToString(); $toString += "" ""; $toString += $ace.AccessControlType.ToString(); @@ -896,11 +898,13 @@ public static IEnumerable Get() $toString += $ace.RegistryRights.ToString(); } } + return $toString;"), null)); td102.Members.Add("AuditToString", new ScriptPropertyData(@"AuditToString", GetScriptBlock(@"$toString = """"; $first = $true; if ( ! (& { Set-StrictMode -Version 1; $this.audit }) ) { return """" } + foreach($ace in (& { Set-StrictMode -Version 1; $this.audit })) { if($first) @@ -911,6 +915,7 @@ public static IEnumerable Get() { $tostring += ""`n""; } + $toString += $ace.IdentityReference.ToString(); $toString += "" ""; $toString += $ace.AuditFlags.ToString(); @@ -924,6 +929,7 @@ public static IEnumerable Get() $toString += $ace.RegistryRights.ToString(); } } + return $toString;"), null)); yield return td102; @@ -1277,9 +1283,12 @@ public static IEnumerable Get() var td165 = new TypeData(@"System.Management.Automation.CallStackFrame", true); td165.Members.Add("Command", new ScriptPropertyData(@"Command", GetScriptBlock(@"if ($null -eq $this.InvocationInfo) { return $this.FunctionName } + $commandInfo = $this.InvocationInfo.MyCommand if ($null -eq $commandInfo) { return $this.InvocationInfo.InvocationName } + if ($commandInfo.Name -ne """") { return $commandInfo.Name } + return $this.FunctionName"), null)); td165.Members.Add("Location", new ScriptPropertyData(@"Location", GetScriptBlock(@"$this.GetScriptLocation()"), null)); @@ -1309,6 +1318,7 @@ public static IEnumerable Get() { $argumentsBuilder.Append(string.Empty, string.Empty) } + if ($arg) { $argumentsBuilder.Append([string]$arg) @@ -1328,16 +1338,19 @@ public static IEnumerable Get() var td166 = new TypeData(@"Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration", true); td166.Members.Add("Permission", new ScriptPropertyData(@"Permission", GetScriptBlock(@"trap { continue; } + $private:sd = $null $private:sd = new-object System.Security.AccessControl.CommonSecurityDescriptor $false,$false,$this.SecurityDescriptorSddl if ($private:sd) { # reset trap trap { } + $private:dacls = """"; $private:first = $true $private:sd.DiscretionaryAcl | ForEach-Object { trap { } + if ($private:first) { $private:first = $false; @@ -1346,6 +1359,7 @@ public static IEnumerable Get() { $private:dacls += "", "" } + $private:dacls += $_.SecurityIdentifier.Translate([System.Security.Principal.NTAccount]).ToString() + "" "" + $_.AceType } # end of foreach @@ -1971,6 +1985,7 @@ public static IEnumerable Get() { $suffix = ""-""+$this.PSSemVerPreReleaseLabel } + if (![String]::IsNullOrEmpty($this.PSSemVerBuildLabel)) { $suffix += ""+""+$this.PSSemVerBuildLabel diff --git a/src/System.Management.Automation/engine/UserFeedbackParameters.cs b/src/System.Management.Automation/engine/UserFeedbackParameters.cs index 1dbf3ae5d7c..3c2bce27cd9 100644 --- a/src/System.Management.Automation/engine/UserFeedbackParameters.cs +++ b/src/System.Management.Automation/engine/UserFeedbackParameters.cs @@ -20,6 +20,7 @@ internal PagingParameters(MshCommandRuntime commandRuntime) { throw PSTraceSource.NewArgumentNullException("commandRuntime"); } + commandRuntime.PagingParameters = this; } @@ -117,6 +118,7 @@ internal ShouldProcessParameters(MshCommandRuntime commandRuntime) { throw PSTraceSource.NewArgumentNullException("commandRuntime"); } + _commandRuntime = commandRuntime; } #endregion ctor @@ -134,6 +136,7 @@ public SwitchParameter WhatIf { return _commandRuntime.WhatIf; } + set { _commandRuntime.WhatIf = value; @@ -151,6 +154,7 @@ public SwitchParameter Confirm { return _commandRuntime.Confirm; } + set { _commandRuntime.Confirm = value; @@ -195,6 +199,7 @@ public SwitchParameter UseTransaction { return _commandRuntime.UseTransaction; } + set { _commandRuntime.UseTransaction = value; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index eb179ea53f9..d70682a9df1 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -394,6 +394,7 @@ internal static Version StringToVersion(string versionString) { return result; } + return null; } @@ -546,6 +547,7 @@ internal static bool IsValidPSEditionValue(string editionValue) case nameof(ConsoleSessionConfiguration): result = policies.ConsoleSessionConfiguration; break; default: Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); break; } + if (result != null) { return (T) result; } } } @@ -628,12 +630,14 @@ internal static bool IsValidPSEditionValue(string editionValue) if (rawIntValue == 1) { propertyValue = true; } else if (rawIntValue == 0) { propertyValue = false; } } + break; case var _ when propertyType == typeof(string): if (rawRegistryValue is string rawStringValue) { propertyValue = rawStringValue; } + break; case var _ when propertyType == typeof(string[]): if (rawRegistryValue is string[] rawStringArrayValue) @@ -644,6 +648,7 @@ internal static bool IsValidPSEditionValue(string editionValue) { propertyValue = new string[] { stringValue }; } + break; default: Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when properties of new types are added to PowerShell policy types."); @@ -923,6 +928,7 @@ internal static bool IsAdministrator() var principal = new WindowsPrincipal(currentIdentity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } + return false; #endif } @@ -1109,6 +1115,7 @@ internal static Mutex SafeWaitMutex(Mutex mutex, MutexInitializer initializer) return mutex; } + internal delegate Mutex MutexInitializer(); internal static bool Succeeded(int hresult) @@ -1243,6 +1250,7 @@ private static void WorkItemCallback(object callBackArgs) () => callback(state)); return; } + callback(state); } #endif @@ -1600,6 +1608,7 @@ private static bool TryGetCommandInfoList(PowerShell ps, HashSet command { return false; } + cmdInfoList.Add(cmdInfo); } @@ -1936,6 +1945,7 @@ internal T Pop() { throw new InvalidOperationException(SessionStateStrings.BoundedStackIsEmpty); } + return item; } } diff --git a/src/System.Management.Automation/engine/VariablePath.cs b/src/System.Management.Automation/engine/VariablePath.cs index 0cdbd665025..54dbeb78ac9 100644 --- a/src/System.Management.Automation/engine/VariablePath.cs +++ b/src/System.Management.Automation/engine/VariablePath.cs @@ -133,6 +133,7 @@ internal VariablePath(string path, VariablePathFlags knownFlags) candidateScopeUpper = "ARIABLE"; candidateFlags = VariablePathFlags.Variable; } + break; } @@ -156,6 +157,7 @@ internal VariablePath(string path, VariablePathFlags knownFlags) { _flags = VariablePathFlags.Variable; } + _flags |= candidateFlags; lastScannedColon = currentCharIndex; currentCharIndex += 1; diff --git a/src/System.Management.Automation/engine/WorkflowInfo.cs b/src/System.Management.Automation/engine/WorkflowInfo.cs index 8038de65883..555e82b54a9 100644 --- a/src/System.Management.Automation/engine/WorkflowInfo.cs +++ b/src/System.Management.Automation/engine/WorkflowInfo.cs @@ -248,6 +248,7 @@ public override string Definition { get { return _definition; } } + private string _definition = string.Empty; /// @@ -268,6 +269,7 @@ public ReadOnlyCollection WorkflowsCalled { get { return _workflowsCalled ?? Utils.EmptyReadOnlyCollection(); } } + private ReadOnlyCollection _workflowsCalled; internal override HelpCategory HelpCategory diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 91204294901..94059e1717c 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -45,6 +45,7 @@ public static HashSet CommonParameters return s_commonParameters.Value; } } + private static Lazy> s_commonParameters = new Lazy>( () => { @@ -66,6 +67,7 @@ public static HashSet OptionalCommonParameters return s_optionalCommonParameters.Value; } } + private static Lazy> s_optionalCommonParameters = new Lazy>( () => { @@ -117,6 +119,7 @@ internal void SetParameterSetName(string parameterSetName) { _parameterSetName = parameterSetName; } + private string _parameterSetName = string.Empty; #region Override Internal @@ -265,6 +268,7 @@ public virtual string GetResourceString(string baseName, string resourceId) { throw PSTraceSource.NewArgumentException("baseName", GetErrorText.ResourceBaseNameFailure, baseName); } + if (retValue == null) { throw PSTraceSource.NewArgumentException("resourceId", GetErrorText.ResourceIdFailure, resourceId); @@ -291,6 +295,7 @@ public ICommandRuntime CommandRuntime return commandRuntime; } } + set { using (PSTransactionManager.GetEngineProtectionScope()) diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index faa8bc42ab8..29c84db0bb1 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -114,6 +114,7 @@ internal bool ExecutionFailed { return _executionFailed; } + set { _executionFailed = value; @@ -316,25 +317,30 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma { throw PSTraceSource.NewArgumentNullException("commandProcessor"); } + if (_commands == null) { // "_commands == null" throw PSTraceSource.NewInvalidOperationException(); } + if (_disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } + if (_executionStarted) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); } + if (commandProcessor.AddedToPipelineAlready) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.CommandProcessorAlreadyUsed); } + if (0 == _commands.Count) { if (0 != readFromCommand) @@ -363,6 +369,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma // "PipelineProcessor.AddCommand(): previous request object == null" throw PSTraceSource.NewInvalidOperationException(); } + Pipe UpstreamPipe = (readErrorQueue) ? prevcommandProcessor.CommandRuntime.ErrorOutputPipe : prevcommandProcessor.CommandRuntime.OutputPipe; if (UpstreamPipe == null) @@ -370,6 +377,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma // "PipelineProcessor.AddCommand(): UpstreamPipe == null" throw PSTraceSource.NewInvalidOperationException(); } + if (UpstreamPipe.DownstreamCmdlet != null) { throw PSTraceSource.NewInvalidOperationException( @@ -406,6 +414,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma } } } + _commands.Add(commandProcessor); // We give the Command a pointer back to the @@ -495,6 +504,7 @@ internal Array SynchronousExecuteEnumerate(object input) firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader = ExternalInput; } + Inject(input, enumerate: true); } catch (PipelineStoppedException) @@ -595,6 +605,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman commandRequestingUpstreamCommandsToStop = null; continue; // do not call DoComplete/EndProcessing on the command that initiated stopping } + if (commandRequestingUpstreamCommandsToStop != null) { continue; // do not call DoComplete/EndProcessing on commands that were stopped upstream @@ -636,6 +647,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman commandProcessor.CommandRuntime.PipelineProcessor.LogExecutionComplete( commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name); } + lastCommandRuntime = commandProcessor.CommandRuntime; } } @@ -759,6 +771,7 @@ internal void StartStepping(bool expectInput) { _firstTerminatingError.Throw(); } + throw; } } @@ -873,6 +886,7 @@ internal Array Step(object input) { _firstTerminatingError.Throw(); } + throw; } catch (Exception) @@ -919,6 +933,7 @@ private void Start(bool incomingStream) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } + if (Stopping) { throw new PipelineStoppedException(); @@ -955,6 +970,7 @@ private void Start(bool incomingStream) // "PipelineProcessor.Start(): LastCommandProcessor == null" throw PSTraceSource.NewInvalidOperationException(); } + if (ExternalSuccessOutput != null) { LastCommandProcessor.CommandRuntime.OutputPipe.ExternalWriter @@ -1357,6 +1373,7 @@ private void DisposeCommands() #pragma warning restore 56500 } } + _redirectionPipes = null; } @@ -1391,6 +1408,7 @@ internal bool RecordFailure(Exception e, InternalCommand command) { ex = ex.InnerException; } + if (!(ex is PipelineStoppedException)) { string message = StringUtil.Format(PipelineStrings.SecondFailure, @@ -1407,9 +1425,11 @@ InvalidOperationException ioe Severity.Warning); } } + wasStopping = _stopping; _stopping = true; } + return !wasStopping; } @@ -1449,6 +1469,7 @@ internal void ForgetFailure() internal PipelineReader ExternalInput { get { return _externalInputPipe; } + set { if (_executionStarted) @@ -1456,6 +1477,7 @@ internal PipelineReader ExternalInput throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); } + _externalInputPipe = value; } } @@ -1473,6 +1495,7 @@ internal PipelineReader ExternalInput internal PipelineWriter ExternalSuccessOutput { get { return _externalSuccessOutput; } + set { if (_executionStarted) @@ -1480,6 +1503,7 @@ internal PipelineWriter ExternalSuccessOutput throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); } + _externalSuccessOutput = value; } } @@ -1498,6 +1522,7 @@ internal PipelineWriter ExternalSuccessOutput internal PipelineWriter ExternalErrorOutput { get { return _externalErrorOutput; } + set { if (_executionStarted) @@ -1531,6 +1556,7 @@ internal bool Stopping internal LocalPipeline LocalPipeline { get { return _localPipeline; } + set { _localPipeline = value; } } @@ -1542,6 +1568,7 @@ internal LocalPipeline LocalPipeline internal SessionStateScope ExecutionScope { get { return _executionScope; } + set { // This needs to be settable so that a steppable pipeline diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 45fbc23789b..cd4196f5763 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -275,6 +275,7 @@ public static bool ContainsWildcardCharacters(string pattern) ++index; } } + return result; } @@ -317,6 +318,7 @@ public static string Unescape(string pattern) { prevCharWasEscapeChar = true; } + continue; } @@ -408,8 +410,10 @@ internal WildcardPatternException(ErrorRecord errorRecord) { throw new ArgumentNullException("errorRecord"); } + _errorRecord = errorRecord; } + [NonSerialized] private ErrorRecord _errorRecord; @@ -728,10 +732,12 @@ internal static RegexOptions TranslateWildcardOptionsIntoRegexOptions(WildcardOp { regexOptions |= RegexOptions.Compiled; } + if ((options & WildcardOptions.IgnoreCase) != 0) { regexOptions |= RegexOptions.IgnoreCase; } + if ((options & WildcardOptions.CultureInvariant) == WildcardOptions.CultureInvariant) { regexOptions |= RegexOptions.CultureInvariant; @@ -754,6 +760,7 @@ internal static void AppendLiteralCharacter(StringBuilder regexPattern, char c) { regexPattern.Append('\\'); } + regexPattern.Append(c); } @@ -790,6 +797,7 @@ protected override void EndWildcardPattern() { _regexPattern.Remove(0, 3); } + if (regexPatternString.EndsWith(".*$", StringComparison.Ordinal)) { _regexPattern.Remove(_regexPattern.Length - 3, 3); @@ -821,6 +829,7 @@ internal static void AppendLiteralCharacterToBracketExpression(StringBuilder reg AppendLiteralCharacter(regexPattern, c); } } + protected override void AppendLiteralCharacterToBracketExpression(char c) { AppendLiteralCharacterToBracketExpression(_regexPattern, c); diff --git a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs index a0d8e9b3bfd..980b8ec009e 100644 --- a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs +++ b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs @@ -186,6 +186,7 @@ internal override Collection BindParameters(Collection throw bindingException; } + BindParameter(uint.MaxValue, argument, parameter, ParameterBindingFlags.ShouldCoerceType); } else if (argument.ParameterName.Equals(Language.Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal)) @@ -200,6 +201,7 @@ internal override Collection BindParameters(Collection result.Add(argument); } } + return result; } @@ -261,6 +263,7 @@ private void HandleRemainingArguments(Collection argum { args.Add(argValue); } + continue; } @@ -279,6 +282,7 @@ private void HandleRemainingArguments(Collection argum { IsHidden = true }; parameterText.Properties.Add(noteProperty); } + args.Add(parameterText); } diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index b00c49b1d3e..a434a694cfe 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -218,6 +218,7 @@ internal Serializer(XmlWriter writer, SerializationContext context) { throw PSTraceSource.NewArgumentException("writer"); } + if (context == null) { throw PSTraceSource.NewArgumentException("context"); @@ -239,6 +240,7 @@ internal Serializer(XmlWriter writer, SerializationContext context) internal TypeTable TypeTable { get { return _serializer.TypeTable; } + set { _serializer.TypeTable = value; } } @@ -365,6 +367,7 @@ internal void AddCimClassToCache(TKey key, CimClass cimClass) { _cimClassIdToClass.Clear(); } + _cimClassIdToClass.Add(key, cimClass); /* PRINTF DEBUG @@ -414,6 +417,7 @@ internal void AddClassToCache(TKey key) { _cimClassesHeldByDeserializer.Clear(); } + _cimClassesHeldByDeserializer.Add(key); /* PRINTF DEBUG @@ -435,8 +439,11 @@ public CimClassSerializationId(string className, string namespaceName, string co } public string ClassName { get { return this.Item1; } } + public string NamespaceName { get { return this.Item2; } } + public string ComputerName { get { return this.Item3; } } + public int ClassHashCode { get { return this.Item4; } } } @@ -515,6 +522,7 @@ private static void ReportExceptionForETW(XmlException exception) internal TypeTable TypeTable { get { return _deserializer.TypeTable; } + set { _deserializer.TypeTable = value; } } @@ -553,6 +561,7 @@ private void Start() _done = true; } } + _deserializer.ValidateVersion(version); } @@ -577,10 +586,12 @@ internal bool Done() ReportExceptionForETW(exception); throw; } + _done = true; } } } + return _done; } @@ -655,6 +666,7 @@ internal static bool IsInstanceOfType(object o, Type type) { throw PSTraceSource.NewArgumentNullException("type"); } + if (o == null) { return false; @@ -675,6 +687,7 @@ internal static bool IsDeserializedInstanceOfType(object o, Type type) { throw PSTraceSource.NewArgumentNullException("type"); } + if (o == null) { return false; @@ -825,6 +838,7 @@ internal InternalSerializer(XmlWriter writer, SerializationContext context) { objectRefIdDictionary = new WeakReferenceDictionary(); } + _objectRefIdHandler = new ReferenceIdHandlerForSerializer(objectRefIdDictionary); _typeRefIdHandler = new ReferenceIdHandlerForSerializer( @@ -841,6 +855,7 @@ internal InternalSerializer(XmlWriter writer, SerializationContext context) internal TypeTable TypeTable { get { return _typeTable; } + set { _typeTable = value; } } @@ -865,6 +880,7 @@ internal void End() { _writer.WriteEndElement(); } + _writer.Flush(); } @@ -1027,6 +1043,7 @@ string property WriteOnePrimitiveKnownType(this, streamName, property, source, pktInfo); return true; } + return false; } @@ -1056,6 +1073,7 @@ int depth PSObject pktInfoPSObject = PSObject.AsPSObject(source); return HandlePrimitiveKnownTypePSObject(pktInfoPSObject, streamName, property, depth); } + return false; } @@ -1170,6 +1188,7 @@ int depth sourceHandled = true; } } + return sourceHandled; } @@ -1276,10 +1295,12 @@ string refId { WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } + if (property != null) { WriteNameAttribute(property); } + WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); _writer.WriteEndElement(); } @@ -1561,6 +1582,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c string miXmlString = Encoding.Unicode.GetString(miXmlBytes, 0, miXmlBytes.Length); psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimMiXmlProperty, miXmlString)); } + psoClasses.Reverse(); // @@ -1677,6 +1699,7 @@ string toStringValue { WriteEncodedElementString(SerializationStrings.TypeNamesItemTag, type); } + _writer.WriteEndElement(); } else @@ -1709,6 +1732,7 @@ private static bool PSObjectHasNotes(PSObject source) { return true; } + return false; } @@ -1755,6 +1779,7 @@ bool writeEnclosingMemberSetElementTag { continue; } + int depthOfMember = info.IsInstance ? depth : depth - 1; if (info.MemberType == (info.MemberType & PSMemberTypes.Properties)) @@ -1779,9 +1804,11 @@ bool writeEnclosingMemberSetElementTag enclosingTagWritten = true; WriteStartElement(SerializationStrings.MemberSet); } + WriteMemberSet((PSMemberSet)info, depthOfMember); } } + if (enclosingTagWritten) { _writer.WriteEndElement(); @@ -1803,6 +1830,7 @@ int depth { return; } + WriteStartElement(SerializationStrings.MemberSet); WriteNameAttribute(set.Name); WriteMemberInfoCollection(set.Members, depth, false); @@ -2061,6 +2089,7 @@ int depth break; } + WriteOneObject(item, null, null, depth); } } @@ -2330,6 +2359,7 @@ private void WriteNull(string streamName, string property) { WriteNameAttribute(property); } + _writer.WriteEndElement(); } @@ -2682,6 +2712,7 @@ internal static void WriteProgressRecord(InternalSerializer serializer, string s { serializer.WriteNameAttribute(property); } + if (streamName != null) { serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); @@ -2860,6 +2891,7 @@ private static string EncodeString(string s, int indexOfFirstEncodableCharacter) rlen += 7; } } + return new String(result, 0, rlen); } @@ -3009,6 +3041,7 @@ internal InternalDeserializer(XmlReader reader, DeserializationContext context) internal TypeTable TypeTable { get { return _typeTable; } + set { _typeTable = value; } } @@ -3037,6 +3070,7 @@ internal void ValidateVersion(string version) { exceptionToRethrow = e; } + if (exceptionToRethrow != null) { throw NewXmlException(Serialization.InvalidVersion, exceptionToRethrow); @@ -3177,6 +3211,7 @@ private bool RehydrateCimInstanceProperty( { cimInstance.SetCimSessionComputerName(psComputerNameValue); } + return true; } @@ -3197,27 +3232,33 @@ private bool RehydrateCimInstanceProperty( { return false; } + string originalArrayTypeName = Deserializer.MaskDeserializationPrefix(psoPropertyValue.InternalTypeNames[0]); if (originalArrayTypeName == null) { return false; } + Type originalArrayType; if (!LanguagePrimitives.TryConvertTo(originalArrayTypeName, CultureInfo.InvariantCulture, out originalArrayType)) { return false; } + if (!originalArrayType.IsArray || !s_knownCimArrayTypes.Value.Contains(originalArrayType.GetElementType())) { return false; } + object newPropertyValue; if (!LanguagePrimitives.TryConvertTo(propertyValue, originalArrayType, CultureInfo.InvariantCulture, out newPropertyValue)) { return false; } + psoPropertyValue = PSObject.AsPSObject(newPropertyValue); } + propertyValue = psoPropertyValue.BaseObject; } @@ -3286,6 +3327,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass); PSPropertyInfo namespaceProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] as PSPropertyInfo; @@ -3293,6 +3335,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + string cimNamespace = namespaceProperty.Value as string; PSPropertyInfo classNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] as PSPropertyInfo; @@ -3300,6 +3343,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + string cimClassName = classNameProperty.Value as string; PSPropertyInfo computerNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] as PSPropertyInfo; @@ -3307,6 +3351,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + string computerName = computerNameProperty.Value as string; PSPropertyInfo hashCodeProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] as PSPropertyInfo; @@ -3314,19 +3359,23 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + var hashCodeObject = hashCodeProperty.Value; if (hashCodeObject == null) { return null; } + if (hashCodeObject is PSObject) { hashCodeObject = ((PSObject)hashCodeObject).BaseObject; } + if (!(hashCodeObject is int)) { return null; } + int hashCode = (int)hashCodeObject; CimClassSerializationId cimClassSerializationId = new CimClassSerializationId(cimClassName, cimNamespace, computerName, hashCode); @@ -3341,6 +3390,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { return null; } + string miXmlString = miXmlProperty.Value.ToString(); byte[] miXmlBytes = Encoding.Unicode.GetBytes(miXmlString); uint offset = 0; @@ -3386,6 +3436,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) { return deserializedObject; } + CimInstance cimInstance; try { @@ -3395,6 +3446,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) { return deserializedObject; } + PSObject psoCimInstance = PSObject.AsPSObject(cimInstance); // process __InstanceMetadata @@ -3642,6 +3694,7 @@ private PSObject ReadPSObject() throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); } } + if (baseObject != null) { dso.SetCoreOnDeserialization(baseObject, overrideTypeInfo); @@ -3676,6 +3729,7 @@ private PSObject ReadAttributeAndCreatePSObject() s_trace.WriteLine("Read PSObject with refId: {0}", refId); _objectRefIdHandler.SetRefId(sh, refId, this.DuplicateRefIdsAllowed); } + return sh; } @@ -3717,8 +3771,10 @@ private void ReadTypeNames(PSObject dso) throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); } } + ReadEndElement(); } + dso.InternalTypeNames = new ConsolidatedString(typeNames); if (refId != null) @@ -3791,6 +3847,7 @@ private void ReadProperties(PSObject dso) PSProperty prop = new PSProperty(property, value); dso.adaptedMembers.Add(prop); } + ReadEndElement(); } } @@ -3918,8 +3975,10 @@ private object ReadListContainer(ContainerType ct) { list.Add(ReadOneObject()); } + ReadEndElement(); } + if (ct == ContainerType.Stack) { list.Reverse(); @@ -3929,6 +3988,7 @@ private object ReadListContainer(ContainerType ct) { return new Queue(list); } + return list; } @@ -3956,11 +4016,13 @@ private object ReadDictionary(ContainerType ct) { throw NewXmlException(Serialization.DictionaryKeyNotSpecified, null); } + string name = ReadNameAttribute(); if (string.Compare(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase) != 0) { throw NewXmlException(Serialization.InvalidDictionaryKeyName, null); } + object key = ReadOneObject(); if (key == null) @@ -3972,11 +4034,13 @@ private object ReadDictionary(ContainerType ct) { throw NewXmlException(Serialization.DictionaryValueNotSpecified, null); } + name = ReadNameAttribute(); if (string.Compare(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase) != 0) { throw NewXmlException(Serialization.InvalidDictionaryValueName, null); } + object value = ReadOneObject(); // On the first collision, copy the hash table to one that uses the default comparer. @@ -4019,6 +4083,7 @@ private object ReadDictionary(ContainerType ct) ReadEndElement(); } + ReadEndElement(); } @@ -4107,6 +4172,7 @@ internal static object DeserializeByte(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(byte).FullName); } @@ -4126,6 +4192,7 @@ internal static object DeserializeChar(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(char).FullName); } @@ -4158,6 +4225,7 @@ internal static object DeserializeDecimal(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(decimal).FullName); } @@ -4177,6 +4245,7 @@ internal static object DeserializeDouble(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(double).FullName); } @@ -4199,6 +4268,7 @@ internal static object DeserializeGuid(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Guid).FullName); } @@ -4222,6 +4292,7 @@ internal static object DeserializeVersion(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Version).FullName); } @@ -4245,6 +4316,7 @@ internal static object DeserializeSemanticVersion(InternalDeserializer deseriali { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Version).FullName); } @@ -4264,6 +4336,7 @@ internal static object DeserializeInt16(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int16).FullName); } @@ -4283,6 +4356,7 @@ internal static object DeserializeInt32(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int32).FullName); } @@ -4302,6 +4376,7 @@ internal static object DeserializeInt64(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int64).FullName); } @@ -4321,6 +4396,7 @@ internal static object DeserializeSByte(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(sbyte).FullName); } @@ -4340,6 +4416,7 @@ internal static object DeserializeSingle(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(float).FullName); } @@ -4393,6 +4470,7 @@ internal static object DeserializeUInt16(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt16).FullName); } @@ -4412,6 +4490,7 @@ internal static object DeserializeUInt32(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt32).FullName); } @@ -4431,6 +4510,7 @@ internal static object DeserializeUInt64(InternalDeserializer deserializer) { recognizedException = e; } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); } @@ -4503,6 +4583,7 @@ internal static XmlDocument LoadUnsafeXmlDocument(TextReader textReader, bool pr { settings.MaxCharactersInDocument = maxCharactersInDocument.Value; } + if (preserveNonElements) { settings.IgnoreWhitespace = false; @@ -4593,6 +4674,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ { recognizedException = e; } + if (recognizedException != null) { throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); @@ -4684,6 +4766,7 @@ internal bool ReadStartElementAndHandleEmpty(string element) ReadEndElement(); isEmpty = true; } + return !isEmpty; } @@ -4699,6 +4782,7 @@ private void ReadStartElement(string element) { _reader.ReadStartElement(element, SerializationStrings.MonadNamespace); } + _reader.MoveToContent(); } @@ -4722,6 +4806,7 @@ private string ReadDecodedElementString(string element) { temp = _reader.ReadElementContentAsString(element, SerializationStrings.MonadNamespace); } + _reader.MoveToContent(); temp = DecodeString(temp); return temp; @@ -4823,6 +4908,7 @@ private string ReadNameAttribute() { throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.NameAttribute); } + return DecodeString(encodedName); } @@ -5033,6 +5119,7 @@ internal static TypeSerializationInfo GetTypeSerializationInfo(Type type) { temp = s_xdInfo; } + return temp; } @@ -5379,8 +5466,10 @@ private static bool DerivesFromGenericType(Type derived, Type baseType) { return true; } + derived = derived.BaseType; } + return false; } @@ -5618,6 +5707,7 @@ private void CleanUp() alive.Add(weakKeyValuePair.Key, weakKeyValuePair.Value); } } + _dictionary = alive; _cleanupTriggerSize = initialCleanupTriggerSize + this.Count * 2; } @@ -5649,6 +5739,7 @@ public ICollection Keys keys.Add(key); } } + return keys; } } @@ -5678,6 +5769,7 @@ public T this[object key] { return _dictionary[new WeakReference(key)]; } + set { _dictionary[new WeakReference(key)] = value; @@ -5725,6 +5817,7 @@ public void CopyTo(KeyValuePair[] array, int arrayIndex) { rawList.Add(keyValuePair); } + rawList.CopyTo(array, arrayIndex); } @@ -5922,6 +6015,7 @@ private void VerifyValue(object value) { VerifyValue(o); } + return; } @@ -5967,6 +6061,7 @@ public override object this[object key] { return base[key]; } + set { string keyAsString = this.VerifyKey(key); @@ -5995,6 +6090,7 @@ public object this[string key] { return base[key]; } + set { this.VerifyValue(value); @@ -6423,6 +6519,7 @@ internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDicti { result = new PSPrimitiveDictionary(); } + PSPrimitiveDictionary versionTable = new PSPrimitiveDictionary(PSVersionInfo.GetPSVersionTableForDownLevel()) { {"PSSemanticVersion", PSVersionInfo.PSVersion.ToString()} @@ -6800,6 +6897,7 @@ private static ListType RehydrateList(PSObject pso, string p ItemType item = (ItemType)LanguagePrimitives.ConvertTo(deserializedItem, typeof(ItemType), CultureInfo.InvariantCulture); newList.Add(item); } + return newList; } } @@ -6880,6 +6978,7 @@ private static CommandCompletion RehydrateCommandCompletion(PSObject pso) { completions.Add((CompletionResult)match); } + var currentMatchIndex = GetPropertyValue(pso, "CurrentMatchIndex"); var replacementIndex = GetPropertyValue(pso, "ReplacementIndex"); var replacementLength = GetPropertyValue(pso, "ReplacementLength"); @@ -7377,6 +7476,7 @@ private static CustomItemBase RehydrateCustomItemBase(PSObject deserializedItem) { throw PSTraceSource.NewArgumentException("deserializedItem"); } + return result; } @@ -7505,6 +7605,7 @@ private static ExtendedTypeDefinition RehydrateExtendedTypeDefinition(PSObject d result.TypeNames.Add(typeNames[i]); } } + return result; } From 1e2d9bc90e260b351cfcf84912b508c4e217003c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:54 -0800 Subject: [PATCH 38/81] Update help --- .../help/CabinetNativeApi.cs | 1 + .../help/CommandHelpProvider.cs | 8 +++++ .../help/DefaultCommandHelpObjectBuilder.cs | 2 ++ .../help/HelpCommands.cs | 5 +++ .../help/HelpCommentsParser.cs | 36 +++++++++++++++++++ .../help/HelpFileHelpProvider.cs | 1 + .../help/HelpProviderWithFullCache.cs | 2 ++ .../help/HelpSystem.cs | 1 + .../help/MUIFileSearcher.cs | 5 +++ .../help/MamlCommandHelpInfo.cs | 3 ++ .../help/MamlNode.cs | 2 ++ .../help/MamlUtil.cs | 1 + .../help/ProviderHelpProvider.cs | 1 + .../help/RemoteHelpInfo.cs | 2 ++ .../help/SaveHelpCommand.cs | 4 +++ .../help/UpdatableHelpCommandBase.cs | 12 +++++++ .../help/UpdatableHelpModuleInfo.cs | 1 + .../help/UpdatableHelpSystem.cs | 3 ++ .../help/UpdateHelpCommand.cs | 9 +++++ 19 files changed, 99 insertions(+) diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index d4e33013ab0..dc259a319a1 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -420,6 +420,7 @@ internal static IntPtr FdiNotify(FdiNotificationType fdint, FdiNotification fdin return new IntPtr(1); } } + return new IntPtr(0); } diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 89f389282ea..cd94d68cfc7 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -142,6 +142,7 @@ private string GetHelpName(CommandInfo commandInfo) { return cmdletInfo.FullName; } + return commandInfo.Name; } @@ -228,6 +229,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se { LoadHelpFile(helpFile, cmdletInfo.ModuleName, cmdletInfo.Name, reportErrors); } + result = GetFromCommandCacheOrCmdletInfo(cmdletInfo); } } @@ -241,6 +243,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se { LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors); } + result = GetFromCommandCache(helpFile, commandInfo); } } @@ -298,6 +301,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se { LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors); } + result = GetFromCommandCache(helpFile, commandInfo) ?? result; } } @@ -859,6 +863,7 @@ private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) { commandDetails.Properties.Remove("Noun"); } + commandDetails.Properties.Add(new PSNoteProperty("Noun", cmdletInfo.Noun)); } @@ -906,6 +911,7 @@ private MamlCommandHelpInfo GetFromCommandCacheByRemovingPrefix(string helpIdent { result.FullHelp.Properties.Remove("Name"); } + result.FullHelp.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name)); if (result.FullHelp.Properties["Details"] != null && @@ -920,6 +926,7 @@ private MamlCommandHelpInfo GetFromCommandCacheByRemovingPrefix(string helpIdent { commandDetails.Properties.Remove("Name"); } + commandDetails.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name)); // Note we made the change to a copy..so assigning the copy back to @@ -1074,6 +1081,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool { hiddenCommands.Add(helpName, null); } + continue; } diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index fc756fc6e80..47e84f6892f 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -834,10 +834,12 @@ private static string GetPipelineInputString(ParameterAttribute paramAttrib) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue)); } + if (paramAttrib.ValueFromPipelineByPropertyName) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName)); } + if (paramAttrib.ValueFromRemainingArguments) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments)); diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 537272b74d1..125501745b3 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -193,11 +193,13 @@ public SwitchParameter Online VerifyParameterForbiddenInRemoteRunspace(this, "Online"); } } + get { return _showOnlineHelp; } } + private bool _showOnlineHelp; // The following variable controls the view. @@ -295,6 +297,7 @@ protected override void ProcessRecord() WriteObjectsOrShowOnlineHelp(helpInfo, false); } + countOfHelpInfos++; } @@ -705,6 +708,7 @@ private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() } } } + return false; } @@ -726,6 +730,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) { return string.Empty; } + CommandInfo cmdInfo = PSObject.Base(commandInfoPSObject) as CommandInfo; // GetHelpUri helper method is expected to be used only by System.Management.Automation.CommandInfo // objects from types.ps1xml diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index b7b23d82831..649bd9f446d 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -48,6 +48,7 @@ private HelpCommentsParser(CommandInfo commandInfo, List parameterDescri _commandName = si.Path; } } + _commandMetadata = commandInfo.CommandMetadata; _parameterDescriptions = parameterDescriptions; } @@ -90,6 +91,7 @@ private void DetermineParameterDescriptions() _parameters.Add(parameterName.ToUpperInvariant(), _parameterDescriptions[i]); } } + ++i; } } @@ -136,6 +138,7 @@ private XmlElement BuildXmlForParameter( { fromPipeline = "false"; } + command_parameter.SetAttribute("pipelineInput", fromPipeline); command_parameter.SetAttribute("position", position); @@ -165,6 +168,7 @@ private XmlElement BuildXmlForParameter( XmlText parameterValue_text = _doc.CreateTextNode(valueName); parameterValueGroup.AppendChild(parameterValue).AppendChild(parameterValue_text); } + command_parameter.AppendChild(parameterValueGroup); } else @@ -256,6 +260,7 @@ internal XmlDocument BuildXmlFromComments() { continue; } + string parameterName = pair.Key; string description = GetParameterDescription(parameterName); @@ -272,6 +277,7 @@ internal XmlDocument BuildXmlFromComments() { parameterSetData = parameter.GetParameterSetData(1u << i++); } + if (parameterSetData != null) { isMandatory = parameterSetData.IsMandatory; @@ -322,6 +328,7 @@ internal XmlDocument BuildXmlFromComments() parameter.Type, description, supportsWildcards, defaultValueStr, forSyntax: false); commandParameters.AppendChild(parameterElement); } + command.AppendChild(commandParameters); #endregion Parameters @@ -333,6 +340,7 @@ internal XmlDocument BuildXmlFromComments() XmlText description_text = _doc.CreateTextNode(_sections.Description); command.AppendChild(description).AppendChild(description_para).AppendChild(description_text); } + if (!string.IsNullOrEmpty(_sections.Notes)) { XmlElement alertSet = _doc.CreateElement("maml:alertSet", mamlURI); @@ -341,6 +349,7 @@ internal XmlDocument BuildXmlFromComments() XmlText alert_para_text = _doc.CreateTextNode(_sections.Notes); command.AppendChild(alertSet).AppendChild(alert).AppendChild(alert_para).AppendChild(alert_para_text); } + if (_examples.Count > 0) { XmlElement examples = _doc.CreateElement("command:examples", commandURI); @@ -383,10 +392,13 @@ internal XmlDocument BuildXmlFromComments() { remarks.AppendChild(_doc.CreateElement("maml:para", mamlURI)); } + examples.AppendChild(example_node); } + command.AppendChild(examples); } + if (_inputs.Count > 0) { XmlElement inputTypes = _doc.CreateElement("command:inputTypes", commandURI); @@ -398,6 +410,7 @@ internal XmlDocument BuildXmlFromComments() XmlText maml_name_text = _doc.CreateTextNode(inputStr); inputTypes.AppendChild(inputType).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } + command.AppendChild(inputTypes); } // For outputs, we prefer what was specified in the comments, but if there are no comments @@ -411,6 +424,7 @@ internal XmlDocument BuildXmlFromComments() { outputs = _scriptBlock.OutputType; } + if (outputs != null) { XmlElement returnValues = _doc.CreateElement("command:returnValues", commandURI); @@ -423,8 +437,10 @@ internal XmlDocument BuildXmlFromComments() XmlText maml_name_text = _doc.CreateTextNode(returnValueStr); returnValues.AppendChild(returnValue).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } + command.AppendChild(returnValues); } + if (_links.Count > 0) { XmlElement links = _doc.CreateElement("maml:relatedLinks", mamlURI); @@ -437,6 +453,7 @@ internal XmlDocument BuildXmlFromComments() XmlText linkText_text = _doc.CreateTextNode(link); links.AppendChild(navigationLink).AppendChild(linkText).AppendChild(linkText_text); } + command.AppendChild(links); } @@ -472,6 +489,7 @@ private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, M parameter.Type, description, supportsWildcards, defaultValue: string.Empty, forSyntax: true); syntaxItem.AppendChild(parameterElement); } + command.AppendChild(syntax).AppendChild(syntaxItem); } @@ -492,17 +510,20 @@ private static void GetExampleSections(string content, out string prompt_str, ou ++collectingPart; continue; } + if (c == '\n' && collectingPart < 3) { if (collectingPart == 1) { prompt_str = default_prompt_str; } + code_str = builder.ToString().Trim(); builder = new StringBuilder(); collectingPart = 3; continue; } + builder.Append(c); } @@ -553,9 +574,11 @@ private static void CollectCommentText(string text, List commentLines) { i++; } + start = i + 1; } } + commentLines.Add(text.Substring(start, i - start)); } else @@ -569,6 +592,7 @@ private static void CollectCommentText(string text, List commentLines) break; } } + commentLines.Add(text.Substring(i)); } } @@ -595,6 +619,7 @@ private static string GetSection(List commentLines, ref int i) // Skip blank lines before capturing anything in the section. continue; } + if (Regex.IsMatch(line, directive)) { // Break on any directive even if we haven't started capturing. @@ -612,6 +637,7 @@ private static string GetSection(List commentLines, ref int i) j++; } } + capturing = true; // Skip leading whitespace based on the first line in the section, skipping @@ -622,9 +648,11 @@ private static string GetSection(List commentLines, ref int i) { start++; } + sb.Append(line.Substring(start)); sb.Append('\n'); } + return sb.ToString(); } @@ -646,6 +674,7 @@ internal string GetHelpFile(CommandInfo commandInfo) { helpFileToLoad = Path.Combine(Path.GetDirectoryName(commandInfo.Module.Path), _sections.MamlHelpFile); } + string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths); return location; @@ -723,6 +752,7 @@ private bool AnalyzeCommentBlock(List commentLines) { _parameters.Add(param, section); } + break; } case "FORWARDHELPTARGETNAME": @@ -888,6 +918,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf { localHelpInfo.ForwardTarget = helpCommentsParser._sections.ForwardHelpTargetName; } + if (!string.IsNullOrEmpty(helpCommentsParser._sections.ForwardHelpCategory)) { try @@ -996,6 +1027,7 @@ internal static bool IsCommentHelpText(List commentBlock) break; } } + result.Reverse(); return result; } @@ -1010,6 +1042,7 @@ private static int FirstTokenInExtent(Language.Token[] tokens, IScriptExtent ext break; } } + return index; } @@ -1023,6 +1056,7 @@ private static int LastTokenInExtent(Language.Token[] tokens, IScriptExtent exte break; } } + return index - 1; } @@ -1073,6 +1107,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam int n = -1; result.Add(GetSection(commentLines, ref n)); } + return result; } @@ -1190,6 +1225,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } + break; } } diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 51b847661b3..a13d9623f54 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -351,6 +351,7 @@ internal Collection GetExtendedSearchPaths() { searchPaths.RemoveAt(index); } + searchPaths.Insert(0, defaultShellSearchPath); } diff --git a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs index 5035ac73882..cafcf268c70 100644 --- a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs @@ -35,6 +35,7 @@ internal sealed override IEnumerable ExactMatchHelp(HelpRequest helpRe { LoadCache(); } + this.CacheFullyLoaded = true; return base.ExactMatchHelp(helpRequest); @@ -67,6 +68,7 @@ internal sealed override IEnumerable SearchHelp(HelpRequest helpReques { LoadCache(); } + this.CacheFullyLoaded = true; return base.SearchHelp(helpRequest, searchOnlyContent); diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index 69b9211edd3..04ddcaa9f5e 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -250,6 +250,7 @@ internal Collection GetSearchPaths() { return _searchPaths; } + _searchPaths = new Collection(); // add loaded modules paths to the search path diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 9eec89b4b40..e78466d10d7 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -142,6 +142,7 @@ private string[] GetFiles(string path, string pattern) } } } + return (String[])result.ToArray(typeof(string)); #else return Directory.GetFiles(path, pattern); @@ -181,6 +182,7 @@ private void AddFiles(string muiDirectory, string directory, string pattern) _result.Add(path); _uniqueMatches[uniqueToDirectory] = true; } + break; case SearchMode.First: @@ -211,6 +213,7 @@ private void SearchForFiles(string pattern, string directory) cultureNameList.Add(culture.Name); culture = culture.Parent; } + cultureNameList.Add(string.Empty); // Add en-US and en as fallback languages @@ -218,6 +221,7 @@ private void SearchForFiles(string pattern, string directory) { cultureNameList.Add("en-US"); } + if (!cultureNameList.Contains("en")) { cultureNameList.Add("en"); @@ -234,6 +238,7 @@ private void SearchForFiles(string pattern, string directory) return; } } + return; } diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index eebe20343cb..1b64f333a95 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -34,10 +34,12 @@ internal MamlCommandHelpInfo(PSObject helpObject, HelpCategory helpCategory) { _component = helpObject.Properties["Component"].Value as string; } + if (helpObject.Properties["Role"] != null) { _role = helpObject.Properties["Role"].Value as string; } + if (helpObject.Properties["Functionality"] != null) { _functionality = helpObject.Properties["Functionality"].Value as string; @@ -369,6 +371,7 @@ private string ExtractText(PSObject psObject) { result.Append(ExtractText(item)); } + break; case "system.management.automation.psobject": result.Append(ExtractText(PSObject.AsPSObject(propertyInfo.Value))); diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 02b994947b2..c5f0927d12b 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -658,6 +658,7 @@ private int GetParaMamlNodeCount(XmlNodeList nodes) { continue; } + ++i; } } @@ -768,6 +769,7 @@ private static PSObject GetParaPSObject(XmlNode xmlNode, bool newLine, bool trim { innerText = innerText.Trim(); } + sb.Append(innerText); } diff --git a/src/System.Management.Automation/help/MamlUtil.cs b/src/System.Management.Automation/help/MamlUtil.cs index bd2c9f5a6b6..ea4feeae6a9 100644 --- a/src/System.Management.Automation/help/MamlUtil.cs +++ b/src/System.Management.Automation/help/MamlUtil.cs @@ -37,6 +37,7 @@ internal static void OverridePSTypeNames(PSObject maml1, PSObject maml2) return; } } + maml1.TypeNames.Clear(); // User request at the top.. foreach (string typeName in maml2.TypeNames) diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 7c524599b09..9c8b208a4c7 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -245,6 +245,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}", providerInfo.PSSnapInName)); } + AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); } } diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index 7d3c31bf525..1b18e6537b3 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -32,6 +32,7 @@ internal RemoteHelpInfo( { powerShell.AddParameter("Category", remoteHelpCategory); } + powerShell.Runspace = remoteRunspace; Collection helpResults; @@ -57,6 +58,7 @@ internal RemoteHelpInfo( { nameInfo.Value = localCommandName; } + PSObject commandDetails = this.Details; if (commandDetails != null) { diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index b97dfeaa27d..fda6d8bec57 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -49,11 +49,13 @@ public string[] DestinationPath { return _path; } + set { _path = value; } } + private string[] _path; /// @@ -69,12 +71,14 @@ public string[] LiteralPath { return _path; } + set { _path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 237abe89e83..a7e56a4b4b9 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -54,8 +54,10 @@ public CultureInfo[] UICulture result[index] = new CultureInfo(_language[index]); } } + return result; } + set { if (value == null) return; @@ -66,6 +68,7 @@ public CultureInfo[] UICulture } } } + internal string[] _language; /// @@ -76,8 +79,10 @@ public CultureInfo[] UICulture public PSCredential Credential { get { return _credential; } + set { _credential = value; } } + internal PSCredential _credential; /// @@ -90,11 +95,13 @@ public SwitchParameter UseDefaultCredentials { return _useDefaultCredentials; } + set { _useDefaultCredentials = value; } } + internal bool _useDefaultCredentials = false; /// @@ -107,11 +114,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + internal bool _force; /// @@ -234,8 +243,10 @@ private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext con "HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null)); } + return; } + if (!(module.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || module.HelpInfoUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) { if (!noErrors) @@ -244,6 +255,7 @@ private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext con "InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, module.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null)); } + return; } diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index 9c246698d68..cdbf12013de 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -53,6 +53,7 @@ internal Guid ModuleGuid return _moduleGuid; } } + private Guid _moduleGuid; /// diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 63b4d1336af..35e01dbb116 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -647,6 +647,7 @@ private XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ErrorCategory.InvalidData, null, e); } } + return document; } @@ -823,9 +824,11 @@ private bool DownloadHelpContentHttpClient(string uri, string fileName, Updatabl } } } + SendProgressEvents(commandType); } } + return (Errors.Count == 0); } diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index e2378a67ea9..27aa7990bda 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -50,11 +50,13 @@ public string[] Module { return _module; } + set { _module = value; } } + private string[] _module; /// @@ -79,11 +81,13 @@ public string[] SourcePath { return _path; } + set { _path = value; } } + private string[] _path; /// @@ -99,12 +103,14 @@ public string[] LiteralPath { return _path; } + set { _path = value; _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -117,11 +123,13 @@ public SwitchParameter Recurse { return _recurse; } + set { _recurse = value; } } + private bool _recurse; #endregion @@ -173,6 +181,7 @@ protected override void ProcessRecord() PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); } + _isInitialized = true; } From 3dba527ef11c5c305f4dd9f3da80b1cdfdb98f42 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:54 -0800 Subject: [PATCH 39/81] Update logging --- src/System.Management.Automation/logging/MshLog.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 0a8415b63a8..f23541223f3 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -507,6 +507,7 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, logContext = GetLogContext(executionContext, null); logContext.CommandName = commandName; } + return logContext; }, commandState); } From bcdf012287a459d9d19773420ad50c1c7a160bad Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:55 -0800 Subject: [PATCH 40/81] Update namespaces --- .../namespaces/AliasProvider.cs | 6 ++ .../namespaces/CoreCommandContext.cs | 5 ++ .../namespaces/EnvironmentProvider.cs | 3 + .../namespaces/FileSystemContentStream.cs | 8 ++ .../namespaces/FileSystemProvider.cs | 77 +++++++++++++++++++ .../namespaces/FunctionProvider.cs | 5 ++ .../namespaces/LocationGlobber.cs | 14 ++++ .../namespaces/NavigationProviderBase.cs | 6 ++ .../namespaces/PathInfo.cs | 1 + .../namespaces/ProviderBase.cs | 14 ++++ .../namespaces/RegistryProvider.cs | 30 ++++++++ .../namespaces/RegistrySecurity.cs | 1 + .../namespaces/RegistryWrapper.cs | 2 + .../namespaces/SessionStateProviderBase.cs | 5 ++ .../namespaces/TransactedRegistryKey.cs | 32 ++++++++ .../namespaces/VariableProvider.cs | 1 + .../namespaces/Win32Native.cs | 1 + 17 files changed, 211 insertions(+) diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index f3c689bfa42..f525a47277b 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -159,6 +159,7 @@ internal override object GetValueOfItem(object item) { value = aliasInfo.Definition; } + return value; } @@ -219,6 +220,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { item = SessionState.Internal.SetAliasValue(name, stringValue, Force, Context.Origin); } + break; } @@ -236,6 +238,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { newAliasInfo.SetOptions(dynamicParameters.Options, Force); } + item = SessionState.Internal.SetAliasItem(newAliasInfo, Force, Context.Origin); break; } @@ -329,12 +332,14 @@ public class AliasProviderDynamicParameters public ScopedItemOptions Options { get { return _options; } + set { _optionsSet = true; _options = value; } } + private ScopedItemOptions _options; /// @@ -345,6 +350,7 @@ internal bool OptionsSet { get { return _optionsSet; } } + private bool _optionsSet = false; } } diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 52b36cb450f..fb0d6dde350 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -139,6 +139,7 @@ internal CmdletProviderContext( { throw PSTraceSource.NewArgumentException("command.Context"); } + ExecutionContext = command.Context; // Stream will default to true because command methods will be used. @@ -190,6 +191,7 @@ internal CmdletProviderContext( { throw PSTraceSource.NewArgumentException("command.Context"); } + ExecutionContext = command.Context; // Stream will default to true because command methods will be used. @@ -227,6 +229,7 @@ internal CmdletProviderContext( { throw PSTraceSource.NewArgumentException("command.Context"); } + ExecutionContext = command.Context; // Stream will default to true because command methods will be used. @@ -254,6 +257,7 @@ internal CmdletProviderContext( { throw PSTraceSource.NewArgumentNullException("contextToCopyFrom"); } + ExecutionContext = contextToCopyFrom.ExecutionContext; _command = contextToCopyFrom._command; @@ -514,6 +518,7 @@ public PSTransactionContext CurrentPSTransaction internal SwitchParameter Force { get { return _force; } + set { _force = value; } } diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index a251b7b9227..5f1fe7174a1 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -88,6 +88,7 @@ internal override object GetSessionStateItem(string name) { result = new DictionaryEntry(name, value); } + return result; } @@ -132,6 +133,7 @@ internal override void SetSessionStateItem(string name, object value, bool write PSObject wrappedObject = PSObject.AsPSObject(value); stringValue = wrappedObject.ToString(); } + Environment.SetEnvironmentVariable(name, stringValue); DictionaryEntry item = new DictionaryEntry(name, stringValue); @@ -234,6 +236,7 @@ internal override object GetValueOfItem(object item) { value = ((DictionaryEntry)item).Value; } + return value; } diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index ad0cfe505dc..a3a4dfa0554 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -452,6 +452,7 @@ internal void SeekItemsBackward(int backCount) _reader.Peek(); _alreadyDetectEncoding = true; } + Seek(0, SeekOrigin.End); if (backCount == 0) @@ -466,6 +467,7 @@ internal void SeekItemsBackward(int backCount) { builder.Insert(0, character); } + string actualDelimiter = builder.ToString(); long currentBlock = 0; string lastDelimiterMatch = null; @@ -697,6 +699,7 @@ private bool ReadDelimited(bool waitChanges, ArrayList blocks, bool readBackward { return true; } + return false; } } @@ -789,6 +792,7 @@ private void CreateStreams(string filePath, string streamName, FileMode fileMode { attributesToClear |= FileAttributes.ReadOnly; } + File.SetAttributes(_path, (File.GetAttributes(filePath) & ~attributesToClear)); } @@ -948,6 +952,7 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA // Seek to the place we last left off. _stream.Seek(_fileOffset, SeekOrigin.Begin); if (_reader != null) { _reader.DiscardBufferedData(); } + if (_backReader != null) { _backReader.DiscardBufferedData(); } } @@ -967,7 +972,9 @@ public void Seek(long offset, SeekOrigin origin) _stream.Seek(offset, origin); if (_writer != null) { _writer.Flush(); } + if (_reader != null) { _reader.DiscardBufferedData(); } + if (_backReader != null) { _backReader.DiscardBufferedData(); } } @@ -1042,6 +1049,7 @@ public IList Write(IList content) WriteObject(line); } } + return content; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1a0001f1a6a..a638e7b1b80 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -334,6 +334,7 @@ public string GetHelpMaml(string helpItemName, string path) ((IDisposable)reader).Dispose(); } } + return String.Empty; } @@ -371,6 +372,7 @@ protected override ProviderInfo Start(ProviderInfo providerInfo) s_tracer.WriteLine("Not setting home directory {0} - does not exist", homeDirectory); } } + return providerInfo; } @@ -706,6 +708,7 @@ private static string WinGetUNCForNetworkDrive(string driveName) uncBuffer = new StringBuilder(bufferSize); errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize); } + if (errorCode != 0) { throw new System.ComponentModel.Win32Exception(errorCode); @@ -948,6 +951,7 @@ protected override Collection InitializeDefaultDrives() break; } } + if (skipDuplicate) continue; @@ -995,6 +999,7 @@ protected override Collection InitializeDefaultDrives() } } } + return results; } @@ -1234,6 +1239,7 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool { filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } + if (switchEvaluator != null) { switchFilterHidden = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); @@ -1268,6 +1274,7 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool return new DirectoryInfo(path); } } + return null; } @@ -1513,6 +1520,7 @@ private void GetPathItems( attributeFilter = evaluator.Evaluate(fsinfo.Attributes); // expressions filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } + if (switchEvaluator != null) { switchAttributeFilter = switchEvaluator.Evaluate(fsinfo.Attributes); // switch parameters @@ -1639,6 +1647,7 @@ private void Dir( attributeFilter = evaluator.Evaluate(filesystemInfo.Attributes); filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } + if (switchEvaluator != null) { switchAttributeFilter = switchEvaluator.Evaluate(filesystemInfo.Attributes); @@ -1696,6 +1705,7 @@ private void Dir( { isFilterHiddenSpecified = evaluator.ExistsInExpression(FileAttributes.Hidden); } + if (switchEvaluator != null) { isSwitchFilterHiddenSpecified = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); @@ -1786,18 +1796,22 @@ private FlagsExpression FormatAttributeSwitchParameters() { sb.Append("+Directory"); } + if (((GetChildDynamicParameters)DynamicParameters).File) { sb.Append("+!Directory"); } + if (((GetChildDynamicParameters)DynamicParameters).System) { sb.Append("+System"); } + if (((GetChildDynamicParameters)DynamicParameters).ReadOnly) { sb.Append("+ReadOnly"); } + if (((GetChildDynamicParameters)DynamicParameters).Hidden) { sb.Append("+Hidden"); @@ -2608,6 +2622,7 @@ private bool CreateIntermediateDirectories(string path) { break; } + previousParent = parentPath; } while (!String.IsNullOrEmpty(previousParent)); @@ -2617,6 +2632,7 @@ private bool CreateIntermediateDirectories(string path) { CreateDirectory(directoryPath, false); } + result = true; } catch (ArgumentException argException) @@ -2732,6 +2748,7 @@ protected override void RemoveItem(string path, bool recurse) foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(fsinfo.FullName)) { if (!p.IsMatch(stream.Stream)) { continue; } + foundStream = true; string action = String.Format( @@ -3096,6 +3113,7 @@ protected override bool ItemExists(string path) { WriteError(error); } + return result; } @@ -3146,6 +3164,7 @@ private bool ItemExists(string path, out ErrorRecord error) { result = lastWriteTime < itemExistsDynamicParameters.OlderThan.Value; } + if (itemExistsDynamicParameters.NewerThan.HasValue) { result = lastWriteTime > itemExistsDynamicParameters.NewerThan.Value; @@ -3959,6 +3978,7 @@ private void SetFileMetadata(string sourceFileFullName, FileInfo destinationFile { destinationFile.LastWriteTimeUtc = (DateTime)metadata["LastWriteTimeUtc"]; } + if (metadata["LastWriteTime"] != null) { destinationFile.LastWriteTime = (DateTime)metadata["LastWriteTime"]; @@ -4079,6 +4099,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf { destinationFile.Attributes = destinationFile.Attributes & ~(FileAttributes.ReadOnly | FileAttributes.Hidden | FileAttributes.System); } + wStream = new FileStream(destinationFile.FullName, FileMode.Create); } @@ -4142,6 +4163,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf { content = (string)op["b64Fragment"]; } + bool more = (bool)op["moreAvailable"]; currentIndex += fragmentSize; byte[] bytes = System.Convert.FromBase64String(content); @@ -4205,6 +4227,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf } } } + return success; } @@ -4270,10 +4293,12 @@ private string MakeRemotePath(System.Management.Automation.PowerShell ps, string { isDirectoryInfo = (bool)op["IsDirectoryInfo"]; } + if (op["IsFileInfo"] != null) { isFileInfo = (bool)op["IsFileInfo"]; } + if (op["ParentIsDirectoryInfo"] != null) { parentIsDirectoryInfo = (bool)op["ParentIsDirectoryInfo"]; @@ -4370,6 +4395,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath { toRead = (int)remainingFileSize; } + if (fragment == null) { fragment = new byte[toRead]; @@ -4384,6 +4410,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath { readSoFar += fStream.Read(fragment, 0, toRead); } + remainingFileSize -= readSoFar; string b64Fragment = System.Convert.ToBase64String(fragment); @@ -4473,6 +4500,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath fStream.Dispose(); } } + return success; } @@ -4592,6 +4620,7 @@ private string CreateDirectoryOnRemoteSession(string destination, bool force, Sy WriteError(new ErrorRecord(e, "FailedToCreateDirectory", ErrorCategory.WriteError, destination)); return null; } + string path = (string)(op["DirectoryPath"]); if ((!force) && (bool)op["PathExists"]) @@ -4716,11 +4745,13 @@ private static bool IsUNCRoot(string path) { break; } + --lastIndex; if (lastIndex < 3) { break; } + ++separatorsFound; } while (lastIndex > 3); @@ -4730,6 +4761,7 @@ private static bool IsUNCRoot(string path) } } } + return result; } @@ -5237,8 +5269,10 @@ private Stack TokenizePathToStack(string path, string basePath) s_tracer.WriteLine("tokenizedPathStack.Push({0})", tempPath); tokenizedPathStack.Push(tempPath); } + break; } + previousParent = tempPath; } @@ -5334,6 +5368,7 @@ private Stack NormalizeThePath(string basepath, Stack tokenizedP } } } + s_tracer.WriteLine("normalizedPathStack.Push({0})", childName); normalizedPathStack.Push(childName); } @@ -5371,6 +5406,7 @@ private string CreateNormalizedRelativePathFromStack(Stack normalizedPat leafElement = MakePath(parentElement, leafElement); } } + return leafElement; } @@ -5913,6 +5949,7 @@ public void GetProperty(string path, Collection providerSpecificPickList { result = new PSObject(); } + result.Properties.Add(new PSNoteProperty(property, value)); } else @@ -6936,6 +6973,7 @@ internal static bool PathIsNetworkPath(string path) return true; } } + return false; } #else @@ -7072,6 +7110,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS { return Invoke(ps, fileSystemContext, cmdletContext, true); } + public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileSystemProvider fileSystemContext, CmdletProviderContext cmdletContext, bool shouldHaveOutput) { bool useFileSystemProviderContext = (cmdletContext == null); @@ -7098,6 +7137,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS cmdletContext.WriteError(new ErrorRecord(e, "CopyFileRemoteExecutionError", ErrorCategory.InvalidOperation, ps)); ps.Commands.Clear(); } + return null; } @@ -7126,6 +7166,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS Dbg.Diagnostics.Assert(output[0] != null, "Expected an output from the remote call."); return null; } + return (Hashtable)output[0]; } @@ -7173,8 +7214,10 @@ internal sealed class GetChildDynamicParameters public SwitchParameter Directory { get { return _attributeDirectory; } + set { _attributeDirectory = value; } } + private bool _attributeDirectory; /// @@ -7185,8 +7228,10 @@ public SwitchParameter Directory public SwitchParameter File { get { return _attributeFile; } + set { _attributeFile = value; } } + private bool _attributeFile; /// @@ -7197,8 +7242,10 @@ public SwitchParameter File public SwitchParameter Hidden { get { return _attributeHidden; } + set { _attributeHidden = value; } } + private bool _attributeHidden; /// @@ -7209,8 +7256,10 @@ public SwitchParameter Hidden public SwitchParameter ReadOnly { get { return _attributeReadOnly; } + set { _attributeReadOnly = value; } } + private bool _attributeReadOnly; /// @@ -7221,8 +7270,10 @@ public SwitchParameter ReadOnly public SwitchParameter System { get { return _attributeSystem; } + set { _attributeSystem = value; } } + private bool _attributeSystem; } @@ -7245,6 +7296,7 @@ public Encoding Encoding { return _encoding; } + set { _encoding = value; @@ -7252,6 +7304,7 @@ public Encoding Encoding WasStreamTypeSpecified = true; } } + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// @@ -7306,6 +7359,7 @@ public SwitchParameter NoNewline { return _suppressNewline; } + set { _suppressNewline = value; @@ -7338,6 +7392,7 @@ public string Delimiter _delimiter = value; } } + private string _delimiter = "\n"; /// @@ -7358,6 +7413,7 @@ public SwitchParameter Wait _wait = value; } } + private bool _wait; /// @@ -7371,11 +7427,13 @@ public SwitchParameter Raw { return _isRaw; } + set { _isRaw = value; } } + private bool _isRaw; /// @@ -8296,6 +8354,7 @@ internal static void DeleteFileStream(string path, string streamName) { adjustedStreamName = ":" + adjustedStreamName; } + string resultPath = path + adjustedStreamName; File.Delete(resultPath); @@ -8397,6 +8456,7 @@ internal static class CopyFileRemoteUtils [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")] [Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"")] {0} + [string] $copyToFilePath, [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"", Mandatory=$false)] @@ -8416,10 +8476,12 @@ internal static class CopyFileRemoteUtils [Parameter(ParameterSetName=""PSTargetSupportsAlternateStreams"", Mandatory=$true)] {0} + [string] $supportAltStreamPath, [Parameter(ParameterSetName=""PSSetFileMetadata"", Mandatory=$true)] {0} + [string] $metaDataFilePath, [Parameter(ParameterSetName=""PSSetFileMetadata"", Mandatory=$true)] @@ -8428,14 +8490,17 @@ internal static class CopyFileRemoteUtils [Parameter(ParameterSetName=""PSRemoteDestinationPathIsFile"", Mandatory=$true)] {0} + [string] $isFilePath, [Parameter(ParameterSetName=""PSGetRemotePathInfo"", Mandatory=$true)] {0} + [string] $remotePath, [Parameter(ParameterSetName=""PSCreateDirectoryOnRemoteSession"", Mandatory=$true)] {0} + [string] $createDirectoryPath, [Parameter(ParameterSetName=""PSCreateDirectoryOnRemoteSession"")] @@ -8458,6 +8523,7 @@ function CheckPSDriveSize Microsoft.PowerShell.Management\Get-ChildItem -LiteralPath ($resolvedPath.Drive.Name + "":"") -Recurse | ForEach-Object {{ Microsoft.PowerShell.Management\Get-Item -LiteralPath $_.FullName -Stream * | ForEach-Object {{ $dirSize += $_.Length }} }} + if (($dirSize + $fragmentLength) -gt $maxUserSize) {{ $msg = ""{1}"" -f $maxUserSize @@ -8641,6 +8707,7 @@ function PSSetFileMetadata {{ $item.LastWriteTimeUtc = $metaDataToSet['LastWriteTimeUtc'] }} + if ($metaDataToSet['LastWriteTime']) {{ $item.LastWriteTime = $metaDataToSet['LastWriteTime'] @@ -8853,6 +8920,7 @@ function PSCreateDirectoryOnRemoteSession param ( [Parameter(ParameterSetName=""PSCopyFileFromRemoteSession"", Mandatory=$true)] {0} + [string] $copyFromFilePath, [Parameter(ParameterSetName=""PSCopyFileFromRemoteSession"", Mandatory=$true)] @@ -8875,18 +8943,22 @@ function PSCreateDirectoryOnRemoteSession [Parameter(ParameterSetName=""PSSourceSupportsAlternateStreams"", Mandatory=$true)] {0} + [string] $supportAltStreamPath, [Parameter(ParameterSetName=""PSGetFileMetadata"", Mandatory=$true)] {0} + [string] $getMetaFilePath, [Parameter(ParameterSetName=""PSGetPathItems"", Mandatory=$true)] {0} + [string] $getPathItems, [Parameter(ParameterSetName=""PSGetPathDirAndFiles"", Mandatory=$true)] {0} + [string] $getPathDir ) @@ -8962,6 +9034,7 @@ function PerformCopyFileFromRemoteSession $op['moreAvailable'] = $true }} }} + $op }} finally @@ -9046,6 +9119,7 @@ function WriteException {{ WriteException $e }} + $finalResult.ExceptionThrown = $true }} }} @@ -9335,10 +9409,12 @@ PSGetPathDirAndFiles @params param ( [Parameter(ParameterSetName=""PSRemoteDirectoryExist"", Mandatory=$true)] {0} + [string] $dirPathExists, [Parameter(ParameterSetName=""PSValidatePath"", Mandatory=$true)] {0} + [string] $pathToValidate, [Parameter(ParameterSetName=""PSValidatePath"")] @@ -9355,6 +9431,7 @@ function PSRemoteDirectoryExist ) $result = @{{ Exists = (Microsoft.PowerShell.Management\Test-Path $dirPathExists -PathType Container) }} + return $result }} diff --git a/src/System.Management.Automation/namespaces/FunctionProvider.cs b/src/System.Management.Automation/namespaces/FunctionProvider.cs index 53b7dfe7d5f..390b51c32fd 100644 --- a/src/System.Management.Automation/namespaces/FunctionProvider.cs +++ b/src/System.Management.Automation/namespaces/FunctionProvider.cs @@ -202,6 +202,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue, null, Force, Context.Origin); } + break; } @@ -232,6 +233,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, Force, Context.Origin); } + break; } @@ -360,12 +362,14 @@ public class FunctionProviderDynamicParameters public ScopedItemOptions Options { get { return _options; } + set { _optionsSet = true; _options = value; } } + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -376,6 +380,7 @@ internal bool OptionsSet { get { return _optionsSet; } } + private bool _optionsSet; } } diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index de6f3b3a72c..567af9525ce 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -242,6 +242,7 @@ internal Collection GetGlobbedMonadPathsFromMonadPath( throw pathNotFound; } } + return result; } @@ -476,6 +477,7 @@ private Collection ResolveDriveQualifiedPath( userPath = GetDriveQualifiedPath(relativePath, drive); itemPath = GetProviderPath(path, context); } + s_pathResolutionTracer.WriteLine("PROVIDER path: {0}", itemPath); Collection stringResult = new Collection(); @@ -870,6 +872,7 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( throw errorRecord.Exception; } } + return results; } @@ -1294,6 +1297,7 @@ internal string GetProviderPath( { result = GetProviderSpecificPath(drive, relativePath, context); } + provider = drive.Provider; } @@ -1525,6 +1529,7 @@ internal static bool IsAbsolutePath(string path) { separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index-1); } + if (separator == -1 || index < separator) { // We must have a drive specified @@ -2642,6 +2647,7 @@ private Collection ExpandMshGlobPath( { throw PSTraceSource.NewArgumentNullException("drive"); } + s_tracer.WriteLine("path = {0}", path); NavigationCmdletProvider navigationProvider = provider as NavigationCmdletProvider; @@ -2726,6 +2732,7 @@ private Collection ExpandMshGlobPath( path); throw invalidOperation; } + path = newParentPath; } else @@ -3160,6 +3167,7 @@ private static string RemoveDriveQualifier(string path) { separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index); } + if (separator == -1 || index < separator) { // Remove the \ or / if it follows the drive indicator @@ -3697,6 +3705,7 @@ internal Collection ExpandGlobPath( path); throw invalidOperation; } + path = newParentPath; } else @@ -3735,6 +3744,7 @@ internal Collection ExpandGlobPath( { path = String.Empty; } + leafElements.Push(leafElement); s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); } @@ -3868,6 +3878,7 @@ internal Collection ExpandGlobPath( } } } + Dbg.Diagnostics.Assert( result != null, "This method should at least return the path or more if it has glob characters"); @@ -4675,6 +4686,7 @@ internal string GetHomeRelativePath(string path) throw e; } } + result = path; } @@ -4696,6 +4708,7 @@ private static void TraceFilters(CmdletProviderContext context) { includeString.AppendFormat("{0} ", includeFilter); } + s_pathResolutionTracer.WriteLine("Include: {0}", includeString.ToString()); } @@ -4707,6 +4720,7 @@ private static void TraceFilters(CmdletProviderContext context) { excludeString.AppendFormat("{0} ", excludeFilter); } + s_pathResolutionTracer.WriteLine("Exclude: {0}", excludeString.ToString()); } } diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index d53c1816446..b26fec86ff6 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -407,6 +407,7 @@ protected string MakePath(string parent, string child, bool childIsLeaf) { builder.Append(StringLiterals.DefaultPathSeparator); } + builder.Append(child); } } @@ -501,6 +502,7 @@ protected virtual string GetParentPath(string path, string root) parentPath = String.Empty; } } + return parentPath; } } @@ -603,6 +605,7 @@ internal string ContractRelativePath( path = path.TrimEnd(StringLiterals.DefaultPathSeparator); originalPathHadTrailingSlash = true; } + basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator); // See if the base and the path are already the same. We resolve this to @@ -1001,6 +1004,7 @@ private Stack TokenizePathToStack(string path, string basePath) { break; } + previousParent = tempPath; } @@ -1072,6 +1076,7 @@ private static Stack NormalizeThePath( } } } + providerBaseTracer.WriteLine("normalizedPathStack.Push({0})", childName); normalizedPathStack.Push(childName); } @@ -1109,6 +1114,7 @@ private string CreateNormalizedRelativePathFromStack(Stack normalizedPat leafElement = MakePath(parentElement, leafElement); } } + return leafElement; } diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index 6d23cbbeaaa..510dddb9292 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -76,6 +76,7 @@ public string ProviderPath return _providerPath; } } + private string _providerPath; private SessionState _sessionState; diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 3ec004c46d0..8838e4b0191 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -304,6 +304,7 @@ internal object GetPropertyDynamicParameters( { return null; } + return propertyProvider.GetPropertyDynamicParameters(path, providerSpecificPickList); } @@ -374,6 +375,7 @@ internal object SetPropertyDynamicParameters( { return null; } + return propertyProvider.SetPropertyDynamicParameters(path, propertyValue); } @@ -447,6 +449,7 @@ internal object ClearPropertyDynamicParameters( { return null; } + return propertyProvider.ClearPropertyDynamicParameters(path, providerSpecificPickList); } @@ -539,6 +542,7 @@ internal object NewPropertyDynamicParameters( { return null; } + return propertyProvider.NewPropertyDynamicParameters(path, propertyName, propertyTypeName, value); } @@ -611,6 +615,7 @@ internal object RemovePropertyDynamicParameters( { return null; } + return propertyProvider.RemovePropertyDynamicParameters(path, propertyName); } @@ -691,6 +696,7 @@ internal object RenamePropertyDynamicParameters( { return null; } + return propertyProvider.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty); } @@ -779,6 +785,7 @@ internal object CopyPropertyDynamicParameters( { return null; } + return propertyProvider.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } @@ -867,6 +874,7 @@ internal object MovePropertyDynamicParameters( { return null; } + return propertyProvider.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } @@ -934,6 +942,7 @@ internal object GetContentReaderDynamicParameters( { return null; } + return contentProvider.GetContentReaderDynamicParameters(path); } @@ -997,6 +1006,7 @@ internal object GetContentWriterDynamicParameters( { return null; } + return contentProvider.GetContentWriterDynamicParameters(path); } @@ -1057,6 +1067,7 @@ internal object ClearContentDynamicParameters( { return null; } + return contentProvider.ClearContentDynamicParameters(path); } @@ -1422,6 +1433,7 @@ public virtual string GetResourceString(string baseName, string resourceId) { throw PSTraceSource.NewArgumentException("baseName", GetErrorText.ResourceBaseNameFailure, baseName); } + if (retValue == null) { throw PSTraceSource.NewArgumentException("resourceId", GetErrorText.ResourceIdFailure, resourceId); @@ -1775,6 +1787,7 @@ private PSObject WrapOutputInPSObject( { throw PSTraceSource.NewArgumentNullException("item"); } + PSObject result = new PSObject(item); Diagnostics.Assert( @@ -1823,6 +1836,7 @@ private PSObject WrapOutputInPSObject( providerQualifiedParentPath = LocationGlobber.GetProviderQualifiedPath(parentPath, ProviderInfo); } + result.AddOrSetProperty("PSParentPath", providerQualifiedParentPath); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSParentPath", providerQualifiedParentPath); diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index cdb891d3e19..0862faeda16 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -115,6 +115,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) ErrorCategory.InvalidArgument, drive.Root)); } + return drive; } @@ -1011,6 +1012,7 @@ protected override void NewItem( { return; } + SetRegistryValue(newKey, String.Empty, newItem, kind, path, false); } } @@ -1552,6 +1554,7 @@ private bool ErrorIfDestinationIsSourceOrChildOfSource( ErrorCategory.InvalidArgument, destinationPath)); } + return result; } @@ -1808,9 +1811,11 @@ public void GetProperty( notePropertyName = GetLocalizedDefaultToken(); } + propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); valueAdded = true; } + key.Close(); if (valueAdded) @@ -2011,10 +2016,12 @@ public void ClearProperty( { propertyNameToAdd = GetLocalizedDefaultToken(); } + result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); addedOnce = true; } } + key.Close(); if (addedOnce) @@ -2246,6 +2253,7 @@ public void RemoveProperty( { continue; } + hadAMatch = true; // Confirm the set item with the user @@ -2411,6 +2419,7 @@ public void CopyProperty( { throw PSTraceSource.NewArgumentNullException("sourcePath"); } + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException("destinationPath"); @@ -2510,6 +2519,7 @@ public void MoveProperty( { throw PSTraceSource.NewArgumentNullException("sourcePath"); } + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException("destinationPath"); @@ -3053,6 +3063,7 @@ private void GetFilteredRegistryKeyProperties(string path, valueNameToMatch = GetLocalizedDefaultToken(); } + hadAMatch = true; filteredCollection.Add(valueName); } @@ -3107,27 +3118,32 @@ private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) { defaultValue = new byte[0]; } + break; case RegistryValueKind.DWord: { defaultValue = (int)0; } + break; case RegistryValueKind.ExpandString: case RegistryValueKind.String: { defaultValue = string.Empty; } + break; case RegistryValueKind.MultiString: { defaultValue = new string[0]; } + break; case RegistryValueKind.QWord: { defaultValue = (long)0; } + break; } @@ -3156,6 +3172,7 @@ private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, valueName)); } + return defaultValue; } @@ -3182,6 +3199,7 @@ private bool IsHiveContainer(string path) { result = true; } + return result; } @@ -3201,6 +3219,7 @@ private bool CheckOperationNotAllowedOnHiveContainer(string path) WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, path)); return false; } + return true; } @@ -3219,6 +3238,7 @@ private bool CheckOperationNotAllowedOnHiveContainer(string sourcePath, string d WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, sourcePath)); return false; } + if (IsHiveContainer(destinationPath)) { string message = @@ -3227,6 +3247,7 @@ private bool CheckOperationNotAllowedOnHiveContainer(string sourcePath, string d WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, destinationPath)); return false; } + return true; } @@ -3269,6 +3290,7 @@ private IRegistryWrapper GetHiveRoot(string path) return new RegistryWrapper(s_wellKnownHives[k]); } } + return null; } @@ -3449,6 +3471,7 @@ private IRegistryWrapper GetRegkeyForPathWriteIfError(string path, bool writeAcc WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } + return result; } @@ -3752,6 +3775,7 @@ private void WriteWrappedPropertyObject(object value, string propertyName, strin { propertyNameToAdd = GetLocalizedDefaultToken(); } + result.Properties.Add(new PSNoteProperty(propertyNameToAdd, value)); WritePropertyObject(result, path); @@ -3850,6 +3874,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) // If kind is Unknown then just leave the value as-is. } + return value; } @@ -3876,18 +3901,22 @@ private static RegistryValueKind GetValueKindFromObject(object value) { result = RegistryValueKind.DWord; } + if (valueType == typeof(string)) { result = RegistryValueKind.String; } + if (valueType == typeof(string[])) { result = RegistryValueKind.MultiString; } + if (valueType == typeof(long)) { result = RegistryValueKind.QWord; } + return result; } @@ -3947,6 +3976,7 @@ private static object ReadExistingKeyValue(IRegistryWrapper key, string valueNam catch (System.UnauthorizedAccessException) { } + return null; } diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index 1ebd307c71c..1dd8f6be50d 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -71,6 +71,7 @@ public void GetSecurityDescriptor(string path, WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } + WriteSecurityDescriptorObject(sd, path); } } diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 0ba6d7d8042..da134c62077 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -31,10 +31,12 @@ internal interface IRegistryWrapper object GetValue(string name, object defaultValue, RegistryValueOptions options); RegistryValueKind GetValueKind(string name); object RegistryKey { get; } + void SetAccessControl(ObjectSecurity securityDescriptor); ObjectSecurity GetAccessControl(AccessControlSections includeSections); void Close(); string Name { get; } + int SubKeyCount { get; } } diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index c0dd2d06c24..099deee0c0e 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -109,6 +109,7 @@ internal virtual object GetValueOfItem(object item) { value = ((DictionaryEntry)item).Value; } + return value; } @@ -323,6 +324,7 @@ protected override void GetChildItems(string path, bool recurse) { sortedEntries.Add(entry); } + sortedEntries.Sort( delegate (DictionaryEntry left, DictionaryEntry right) { @@ -1109,6 +1111,7 @@ internal SessionStateProviderBaseContentReaderWriter(string path, SessionStatePr { throw PSTraceSource.NewArgumentNullException("provider"); } + _path = path; _provider = provider; } @@ -1145,12 +1148,14 @@ public IList Read(long readCount) { result = getItemValueResult as IList ?? new object[] { getItemValueResult }; } + _contentRead = true; } } return result; } + private bool _contentRead; /// diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index fee75fdea59..af9af0c71ab 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -190,11 +190,13 @@ private int RegOpenKeyTransactedWrapper(SafeRegistryHandle hKey, String lpSubKey hKeyToReturn.Dispose(); hKeyToReturn = txKey; } + nonTxKey.Dispose(); nonTxKey = null; } } } + hkResult = hKeyToReturn; return error; } @@ -215,6 +217,7 @@ private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool syste { _state |= STATE_SYSTEMKEY; } + if (writable) { _state |= STATE_WRITEACCESS; @@ -255,6 +258,7 @@ private SafeTransactionHandle GetTransactionHandle() { safeTransactionHandle = SafeTransactionHandle.Create(); } + return safeTransactionHandle; } @@ -437,6 +441,7 @@ private unsafe TransactedRegistryKey CreateSubKeyInternal(String subkey, Registr Microsoft.PowerShell.Commands.Internal.Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length); secAttrs.pSecurityDescriptor = pSecDescriptor; } + int disposition = 0; // By default, the new key will be writable. @@ -701,6 +706,7 @@ public void DeleteValue(String name, bool throwOnMissingValue) errorCode = Win32Native.ERROR_SUCCESS; } } + if (Win32Native.ERROR_SUCCESS != errorCode) { Win32Error(errorCode, null); @@ -884,6 +890,7 @@ internal TransactedRegistryKey InternalOpenSubKey(String name, bool writable) key._keyName = _keyName + "\\" + name; return key; } + return null; } @@ -1087,6 +1094,7 @@ public String[] GetValueNames() name = new StringBuilder(currentlen); } } + names[i] = name.ToString(); } } @@ -1143,6 +1151,7 @@ public Object GetValue(String name, Object defaultValue, RegistryValueOptions op string resource = String.Format(CultureInfo.CurrentCulture, resourceTemplate, options.ToString()); throw new ArgumentException(resource); } + bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); CheckValueReadPermission(name); return InternalGetValue(name, defaultValue, doNotExpand, true); @@ -1182,6 +1191,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob; } + break; case Win32Native.REG_QWORD: { // also REG_QWORD_LITTLE_ENDIAN @@ -1190,6 +1200,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp // prevent an AV in the edge case that datasize is larger than sizeof(long) goto case Win32Native.REG_BINARY; } + long blob = 0; BCLDebug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this @@ -1197,6 +1208,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp data = blob; } + break; case Win32Native.REG_DWORD: { // also REG_DWORD_LITTLE_ENDIAN @@ -1205,6 +1217,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp // prevent an AV in the edge case that datasize is larger than sizeof(int) goto case Win32Native.REG_QWORD; } + int blob = 0; BCLDebug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this @@ -1212,6 +1225,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp data = blob; } + break; case Win32Native.REG_SZ: @@ -1220,6 +1234,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob.ToString(); } + break; case Win32Native.REG_EXPAND_SZ: @@ -1231,6 +1246,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp else data = Environment.ExpandEnvironmentVariables(blob.ToString()); } + break; case Win32Native.REG_MULTI_SZ: { @@ -1269,6 +1285,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp { strings.Add(new String(blob, cur, len - cur)); } + cur = nextNull + 1; } @@ -1276,6 +1293,7 @@ internal Object InternalGetValue(String name, Object defaultValue, bool doNotExp strings.CopyTo((String[])data, 0); //data = strings.GetAllItems(String.class); } + break; case Win32Native.REG_NONE: case Win32Native.REG_LINK: @@ -1416,6 +1434,7 @@ public unsafe void SetValue(String name, Object value, RegistryValueKind valueKi { throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); } + ret = Win32Native.RegSetValueEx(_hkey, name, 0, @@ -1441,14 +1460,17 @@ public unsafe void SetValue(String name, Object value, RegistryValueKind valueKi { throw new ArgumentException(RegistryProviderStrings.Arg_RegSetStrArrNull); } + sizeInBytes += (dataStrings[i].Length + 1) * 2; } + sizeInBytes += 2; if (MaxValueDataLength < sizeInBytes) { throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); } + byte[] basePtr = new byte[sizeInBytes]; fixed (byte* b = basePtr) { @@ -1473,6 +1495,7 @@ public unsafe void SetValue(String name, Object value, RegistryValueKind valueKi basePtr, sizeInBytes); } + break; } @@ -1482,6 +1505,7 @@ public unsafe void SetValue(String name, Object value, RegistryValueKind valueKi { throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); } + ret = Win32Native.RegSetValueEx(_hkey, name, 0, @@ -1676,6 +1700,7 @@ internal void Win32Error(int errorCode, String str) throw new IOException(Win32Native.GetMessage(errorCode), errorCode); } } + internal static void Win32ErrorStatic(int errorCode, String str) { switch (errorCode) @@ -1733,6 +1758,7 @@ private static void FixupPath(StringBuilder path) break; } } + i++; } @@ -1747,10 +1773,12 @@ private static void FixupPath(StringBuilder path) i++; continue; } + path[j] = path[i]; i++; j++; } + path.Length += j - i; } } @@ -1783,6 +1811,7 @@ private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionC CheckSubKeyReadPermission(subkeyName); } } + CheckSubTreePermission(subkeyName, subKeyCheck); } @@ -1956,6 +1985,7 @@ private static int GetRegistryKeyAccess(bool isWritable) { winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; } + return winAccess; } @@ -1977,6 +2007,7 @@ private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) BCLDebug.Assert(false, "unexpected code path"); break; } + return winAccess; } @@ -2046,6 +2077,7 @@ private void VerifyTransaction() { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NotAssociatedWithTransaction); } + if (!_myTransaction.Equals(Transaction.Current)) { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); diff --git a/src/System.Management.Automation/namespaces/VariableProvider.cs b/src/System.Management.Automation/namespaces/VariableProvider.cs index 86ddd5cbbba..d2df4f0dc04 100644 --- a/src/System.Management.Automation/namespaces/VariableProvider.cs +++ b/src/System.Management.Automation/namespaces/VariableProvider.cs @@ -192,6 +192,7 @@ internal override object GetValueOfItem(object item) { value = var.Value; } + return value; } diff --git a/src/System.Management.Automation/namespaces/Win32Native.cs b/src/System.Management.Automation/namespaces/Win32Native.cs index 6f58314997e..cfba77e6eeb 100644 --- a/src/System.Management.Automation/namespaces/Win32Native.cs +++ b/src/System.Management.Automation/namespaces/Win32Native.cs @@ -406,6 +406,7 @@ internal UNICODE_INTPTR_STRING(int length, int maximumLength, IntPtr buffer) this.MaxLength = (ushort)maximumLength; this.Buffer = buffer; } + internal ushort Length; internal ushort MaxLength; internal IntPtr Buffer; From 53738276d45e54554aacb8f7dcc1b2cdf386fe37 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:56 -0800 Subject: [PATCH 41/81] Update security --- .../security/Authenticode.cs | 1 + .../security/CatalogHelper.cs | 12 ++++++++++ .../security/MshSignature.cs | 2 ++ .../security/SecureStringHelper.cs | 2 ++ .../security/SecurityManager.cs | 2 ++ .../security/SecuritySupport.cs | 23 +++++++++++++++++++ .../security/nativeMethods.cs | 1 + .../security/wldpNativeMethods.cs | 5 ++++ 8 files changed, 48 insertions(+) diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index d9850133bdf..db94b8cf41f 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -526,6 +526,7 @@ private static DWORD GetWinTrustData(string fileName, string fileContent, Marshal.DestroyStructure(wtdBuffer); Marshal.FreeCoTaskMem(wtdBuffer); } + return dwResult; } diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index a48f1ae891b..ef8c609de8c 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -116,6 +116,7 @@ private static int GetCatalogVersion(IntPtr catalogHandle) ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } + return catalogVersion; } @@ -146,6 +147,7 @@ private static string GetCatalogHashAlgorithm(int catalogVersion) ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } + return hashAlgorithm; } @@ -195,6 +197,7 @@ internal static string GenerateCDFFile(Collection Path, string catalogFi fileWriter.WriteLine(); fileWriter.WriteLine(cdfFilesContent); } + return cdfFilePath; } @@ -363,6 +366,7 @@ internal static FileInfo GenerateCatalog(PSCmdlet cmdlet, Collection Pat File.Delete(cdfFilePath); } } + return null; } @@ -465,6 +469,7 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } + return hashValue; } @@ -562,6 +567,7 @@ internal static Dictionary GetHashesFromCatalog(string catalogFi ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } + return catalogHashes; } @@ -675,6 +681,7 @@ internal static Dictionary CalculateHashesFromPath(Collection catalogItems } } } + return Status; } /// @@ -750,10 +758,12 @@ internal static CatalogInformation ValidateCatalog(PSCmdlet cmdlet, Collection @@ -789,6 +800,7 @@ private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, st case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: break; default: break; } + switch (dwLocalError) { case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILE_PATH: diff --git a/src/System.Management.Automation/security/MshSignature.cs b/src/System.Management.Automation/security/MshSignature.cs index 2c0143e0ab3..8b570974105 100644 --- a/src/System.Management.Automation/security/MshSignature.cs +++ b/src/System.Management.Automation/security/MshSignature.cs @@ -347,6 +347,7 @@ private static string GetSignatureStatusMessage(SignatureStatus status, { resourceString = MshSignature.MshSignature_Incompatible; } + arg = filePath; break; @@ -374,6 +375,7 @@ private static string GetSignatureStatusMessage(SignatureStatus status, resourceString = MshSignature.MshSignature_NotSupportedFileFormat_NoExtension; arg = null; } + break; } diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index a7943727e32..31152626c86 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -442,6 +442,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec entropy.cbData = (uint)optionalEntropy.Length; entropy.pbData = pOptionalEntropy.AddrOfPinnedObject(); } + uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE; @@ -523,6 +524,7 @@ public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, Dat entropy.cbData = (uint)optionalEntropy.Length; entropy.pbData = pOptionalEntropy.AddrOfPinnedObject(); } + uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE; diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 9068815b932..baeac7fea81 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -84,6 +84,7 @@ public PSAuthorizationManager(string shellId) { throw PSTraceSource.NewArgumentNullException("shellId"); } + _shellId = shellId; } @@ -620,6 +621,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, allowRun = CheckPolicy(si, host, out reason); if (etwEnabled) ParserEventSource.Log.CheckSecurityStop(si.Path); } + break; case CommandTypes.Application: diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 1a7767d17bb..46a93d2b45b 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -176,6 +176,7 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); } + break; } @@ -190,6 +191,7 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); } + break; } } @@ -225,6 +227,7 @@ private static bool HasGpScriptParent { _hasGpScriptParent = IsCurrentProcessLaunchedByGpScript(); } + return _hasGpScriptParent.Value; } } @@ -267,6 +270,7 @@ private static bool IsCurrentProcessLaunchedByGpScript() // our goal here is to not have the Group Policy execution policy // affect logon / logoff scripts. } + return foundGpScriptParent; } @@ -312,6 +316,7 @@ internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPoli { return ExecutionPolicy.Undefined; } + return ParseExecutionPolicy(groupPolicyPreference); } } @@ -645,6 +650,7 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa { return true; } + break; } } @@ -762,6 +768,7 @@ internal CertificateFilterInfo() internal CertificatePurpose Purpose { get { return _purpose; } + set { _purpose = value; } } @@ -771,6 +778,7 @@ internal CertificatePurpose Purpose internal bool SSLServerAuthentication { get { return _sslServerAuthentication; } + set { _sslServerAuthentication = value; } } @@ -821,33 +829,41 @@ internal string FilterString { ekuT = ekuT + ","; } + ekuT = ekuT + _eku[i]; } } + if (_purpose == CertificatePurpose.CodeSigning) { if (ekuT.Length != 0) { ekuT = ekuT + ","; } + ekuT = ekuT + CodeSigningOid; } + if (_purpose == CertificatePurpose.DocumentEncryption) { if (ekuT.Length != 0) { ekuT = ekuT + ","; } + ekuT = ekuT + DocumentEncryptionOid; } + if (_sslServerAuthentication) { if (ekuT.Length != 0) { ekuT = ekuT + ","; } + ekuT = ekuT + szOID_PKIX_KP_SERVER_AUTH; } + if (ekuT.Length != 0) { filterString = AppendFilter(filterString, "eku", ekuT); @@ -857,6 +873,7 @@ internal string FilterString filterString = AppendFilter(filterString, "key", "*"); } } + if (_expiringInDays >= 0) { filterString = AppendFilter( @@ -869,6 +886,7 @@ internal string FilterString { filterString = null; } + return filterString; } } @@ -895,12 +913,14 @@ private string AppendFilter( throw Marshal.GetExceptionForHR( Security.NativeMethods.E_INVALID_DATA); } + newfilter = name + "=" + newfilter; if (filterString.Length != 0) { newfilter = "&" + newfilter; } } + return filterString + newfilter; } @@ -1092,6 +1112,7 @@ public CmsMessageRecipient(string identifier) _identifier = identifier; this.Certificates = new X509Certificate2Collection(); } + private string _identifier = null; /// @@ -1103,6 +1124,7 @@ public CmsMessageRecipient(X509Certificate2 certificate) _pendingCertificate = certificate; this.Certificates = new X509Certificate2Collection(); } + private X509Certificate2 _pendingCertificate = null; /// @@ -1709,6 +1731,7 @@ internal static void WinUninitialize() } } } + public static bool AmsiUninitializeCalled = false; public static bool AmsiInitialized = false; public static bool AmsiCleanedUp = false; diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index d20b1b5cf1d..3e69e331377 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -1911,6 +1911,7 @@ internal static bool IsSystem32DllPresent(string DllName) catch (Exception) { } + return DllExists; } } diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 8f74903c324..675fa7d72cf 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -172,6 +172,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } } + private static SystemEnforcementMode? s_cachedWldpSystemPolicy = null; private const string AppLockerTestFileName = "__PSScriptPolicyTest_"; @@ -277,6 +278,7 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle finally { if (IO.File.Exists(testPathScript)) { IO.File.Delete(testPathScript); } + if (IO.File.Exists(testPathModule)) { IO.File.Delete(testPathModule); } } @@ -304,6 +306,7 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle return SystemEnforcementMode.None; } } + private static SaferPolicy? s_cachedSaferSystemPolicy = null; private static string GetKnownFolderPath(Guid knownFolderId) @@ -335,6 +338,7 @@ private static SaferPolicy TestSaferPolicy(string testPathScript, string testPat { result = SecuritySupport.GetSaferPolicy(testPathModule, null); } + return result; } @@ -395,6 +399,7 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) // If the system-wide debug policy had no preference, then there is no enforcement. return SystemEnforcementMode.None; } + private static bool s_hadMissingWldpAssembly = false; /// From 9700c82c249d26bbee5f00b9e304fd8ce1b14ac2 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:57 -0800 Subject: [PATCH 42/81] Update utils --- .../utils/ClrFacade.cs | 3 +++ .../utils/CommandDiscoveryExceptions.cs | 12 ++++++++++ .../utils/CryptoUtils.cs | 8 +++++++ .../utils/ExecutionExceptions.cs | 13 ++++++++++ .../utils/ExtensionMethods.cs | 2 ++ .../utils/FormatAndTypeDataHelper.cs | 7 ++++++ .../utils/MetadataExceptions.cs | 1 + .../utils/MshArgumentException.cs | 3 +++ .../utils/MshArgumentNullException.cs | 3 +++ .../utils/MshArgumentOutOfRangeException.cs | 2 ++ .../utils/MshInvalidOperationException.cs | 2 ++ .../utils/MshNotImplementedException.cs | 2 ++ .../utils/MshNotSupportedException.cs | 2 ++ .../utils/MshObjectDisposedException.cs | 2 ++ .../utils/MshTraceSource.cs | 7 ++++++ .../utils/ObjectReader.cs | 4 ++++ .../utils/ObjectStream.cs | 24 +++++++++++++++++++ .../utils/PSTelemetryMethods.cs | 17 +++++++++++++ .../utils/ParameterBinderExceptions.cs | 13 ++++++++++ .../utils/PathUtils.cs | 4 ++++ .../utils/PlatformInvokes.cs | 5 ++++ .../utils/PowerShellETWTracer.cs | 3 +++ .../utils/PowerShellExecutionHelper.cs | 2 ++ .../utils/PsUtils.cs | 10 ++++++++ .../utils/ResourceManagerCache.cs | 2 ++ .../utils/RuntimeException.cs | 8 +++++++ .../utils/SessionStateExceptions.cs | 14 +++++++++++ .../utils/StructuredTraceSource.cs | 12 ++++++++++ .../utils/assert.cs | 4 ++++ 29 files changed, 191 insertions(+) diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index fd51cf565a0..c4b92228403 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -91,6 +91,7 @@ internal static Encoding GetDefaultEncoding() EncodingRegisterProvider(); s_defaultEncoding = new UTF8Encoding(false); } + return s_defaultEncoding; } @@ -113,6 +114,7 @@ internal static Encoding GetOEMEncoding() s_oemEncoding = Encoding.GetEncoding((int)oemCp); #endif } + return s_oemEncoding; } @@ -347,6 +349,7 @@ internal static string ToDmtfDateTime(DateTime date) { strMicrosec = strMicrosec.Substring(0, 6); } + dmtfDateTime = dmtfDateTime + strMicrosec.PadLeft(6, '0'); // adding the UTC offset dmtfDateTime = dmtfDateTime + UtcString; diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index d5b93ee352d..b5285fca861 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -131,9 +131,11 @@ public override ErrorRecord ErrorRecord _errorCategory, _commandName); } + return _errorRecord; } } + private ErrorRecord _errorRecord; /// @@ -142,8 +144,10 @@ public override ErrorRecord ErrorRecord public string CommandName { get { return _commandName; } + set { _commandName = value; } } + private string _commandName = String.Empty; #endregion Properties @@ -170,6 +174,7 @@ params object[] messageArgs a = new object[1]; a[0] = commandName; } + return StringUtil.Format(resourceStr, a); } #endregion Private @@ -410,6 +415,7 @@ public string CommandName { get { return _commandName; } } + private string _commandName = String.Empty; /// @@ -419,6 +425,7 @@ public Version RequiresPSVersion { get { return _requiresPSVersion; } } + private Version _requiresPSVersion; /// @@ -428,6 +435,7 @@ public ReadOnlyCollection MissingPSSnapIns { get { return _missingPSSnapIns; } } + private ReadOnlyCollection _missingPSSnapIns = new ReadOnlyCollection(new string[0]); /// @@ -437,6 +445,7 @@ public string RequiresShellId { get { return _requiresShellId; } } + private string _requiresShellId; /// @@ -446,6 +455,7 @@ public string RequiresShellPath { get { return _requiresShellPath; } } + private string _requiresShellPath; #endregion Properties @@ -462,10 +472,12 @@ private static string BuildMessage( { throw PSTraceSource.NewArgumentNullException("missingItems"); } + foreach (string missingItem in missingItems) { sb.Append(missingItem).Append(", "); } + if (sb.Length > 1) { sb.Remove(sb.Length - 2, 2); diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 98f25e6a058..231604b965a 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -455,6 +455,7 @@ private PSRSACryptoServiceProvider(bool serverMode) _hRSAKey = new PSSafeCryptKey(); } + _hSessionKey = new PSSafeCryptKey(); } @@ -776,6 +777,7 @@ internal bool CanEncrypt { return _canEncrypt; } + set { _canEncrypt = value; @@ -864,6 +866,7 @@ protected void Dispose(bool disposing) { _hSessionKey.Dispose(); } + _hSessionKey = null; } @@ -880,6 +883,7 @@ protected void Dispose(bool disposing) { _hRSAKey.Dispose(); } + _hRSAKey = null; } } @@ -892,6 +896,7 @@ protected void Dispose(bool disposing) { _hProv.Dispose(); } + _hProv = null; } } @@ -998,6 +1003,7 @@ protected string EncryptSecureStringCore(SecureString secureString) { data[i] = Marshal.ReadByte(ptr, i); } + Marshal.ZeroFreeCoTaskMemUnicode(ptr); try @@ -1136,6 +1142,7 @@ public void Dispose(bool disposing) { _rsaCryptoProvider.Dispose(); } + _rsaCryptoProvider = null; _keyExchangeCompleted.Dispose(); @@ -1247,6 +1254,7 @@ internal override RemoteSession Session { return _session; } + set { _session = value; diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 8fa123234e1..3bbc9153b53 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -35,6 +35,7 @@ internal CmdletInvocationException(ErrorRecord errorRecord) { throw new ArgumentNullException("errorRecord"); } + _errorRecord = errorRecord; if (errorRecord.Exception != null) { @@ -76,6 +77,7 @@ internal CmdletInvocationException(Exception innerException, ErrorCategory.NotSpecified, null); } + _errorRecord.SetInvocationInfo(invocationInfo); // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = innerException.HelpLink; // Exception.Source is set by Throw @@ -169,9 +171,11 @@ public override ErrorRecord ErrorRecord ErrorCategory.NotSpecified, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord = null; #endregion Properties @@ -206,6 +210,7 @@ internal CmdletProviderInvocationException( { throw new ArgumentNullException("innerException"); } + _providerInvocationException = innerException; } @@ -269,6 +274,7 @@ public ProviderInvocationException ProviderInvocationException return _providerInvocationException; } } + [NonSerialized] private ProviderInvocationException _providerInvocationException; @@ -469,6 +475,7 @@ internal ActionPreferenceStopException(ErrorRecord error) { throw new ArgumentNullException("error"); } + _errorRecord = error; } @@ -496,6 +503,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, { throw new ArgumentNullException("errorRecord"); } + _errorRecord = errorRecord; } @@ -607,6 +615,7 @@ public override ErrorRecord ErrorRecord { get { return _errorRecord ?? base.ErrorRecord; } } + private readonly ErrorRecord _errorRecord = null; #endregion Properties } @@ -896,9 +905,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidOperation, CallDepth); } + return _errorRecord; } } + private ErrorRecord _errorRecord = null; /// @@ -1004,9 +1015,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidOperation, CallDepth); } + return _errorRecord; } } + private ErrorRecord _errorRecord = null; /// diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index 5ed41206675..a8544af77cf 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -43,6 +43,7 @@ internal static int SequenceGetHashCode(this IEnumerable xs) { return 82460653; // random number } + unchecked { int hash = 41; // 41 is a random prime number @@ -54,6 +55,7 @@ internal static int SequenceGetHashCode(this IEnumerable xs) hash = hash + x.GetHashCode(); } } + return hash; } } diff --git a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs index 18a493aa690..f9b9bc34847 100644 --- a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs +++ b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs @@ -48,14 +48,19 @@ internal PSSnapInTypeAndFormatErrors(string psSnapinName, ExtendedTypeDefinition } internal ExtendedTypeDefinition FormatData { get; } + internal TypeData TypeData { get; } + internal bool IsRemove { get; } + internal string FullPath { get; } + internal FormatTable FormatTable { get; } internal ConcurrentBag Errors { get; set; } internal string PSSnapinName { get { return psSnapinName; } } + internal bool FailToLoadFile; } @@ -157,6 +162,7 @@ internal static void ThrowExceptionOnError( { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } + RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; @@ -191,6 +197,7 @@ internal static void ThrowExceptionOnError( { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } + RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index 70a3c0dc38b..284996ded18 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -150,6 +150,7 @@ internal bool SwallowException { get { return _swallowException; } } + private bool _swallowException = false; } diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index 2c98d6706a8..bcc93d0c596 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -131,9 +131,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidArgument, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "Argument"; @@ -149,6 +151,7 @@ public override string Message { get { return String.IsNullOrEmpty(_message) ? base.Message : _message; } } + private string _message; } } diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index bece2f66b25..d89c2343bc3 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -129,9 +129,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidArgument, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "ArgumentNull"; @@ -147,6 +149,7 @@ public override string Message { get { return String.IsNullOrEmpty(_message) ? base.Message : _message; } } + private string _message; } } diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index 5aee06f7b39..cdbaf366ad3 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -127,9 +127,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidArgument, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "ArgumentOutOfRange"; } diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index 2d9b3dc87f9..1e036f4c6c7 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -125,9 +125,11 @@ public ErrorRecord ErrorRecord _errorCategory, _target); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "InvalidOperation"; internal void SetErrorId(string errorId) diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index 7ab0bce7720..b707784cc00 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -108,9 +108,11 @@ public ErrorRecord ErrorRecord ErrorCategory.NotImplemented, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "NotImplemented"; } diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index 861a648b395..07d2f0dc120 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -108,9 +108,11 @@ public ErrorRecord ErrorRecord ErrorCategory.NotImplemented, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "NotSupported"; } diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index cfbf75a37b2..56820a90978 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -114,9 +114,11 @@ public ErrorRecord ErrorRecord ErrorCategory.InvalidOperation, null); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "ObjectDisposed"; } diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index e250efd5dcf..f973bfec472 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -172,6 +172,7 @@ internal static PSTraceSource GetTracer( // Trace the object specific tracer information result.TracerObjectHeader(Assembly.GetCallingAssembly()); } + return result; } } @@ -260,6 +261,7 @@ internal static PSArgumentNullException NewArgumentNullException( { throw NewArgumentNullException("paramName"); } + if (String.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); @@ -289,6 +291,7 @@ internal static PSArgumentException NewArgumentException(string paramName) { throw new ArgumentNullException("paramName"); } + string message = StringUtil.Format(AutomationExceptions.Argument, paramName); // Note that the message param comes first var e = new PSArgumentException(message, paramName); @@ -318,6 +321,7 @@ internal static PSArgumentException NewArgumentException( { throw NewArgumentNullException("paramName"); } + if (String.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); @@ -477,6 +481,7 @@ internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException(str { throw new ArgumentNullException("paramName"); } + string message = StringUtil.Format(AutomationExceptions.ArgumentOutOfRange, paramName); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); @@ -508,6 +513,7 @@ internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException( { throw NewArgumentNullException("paramName"); } + if (String.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); @@ -538,6 +544,7 @@ internal static PSObjectDisposedException NewObjectDisposedException(string obje { throw NewArgumentNullException("objectName"); } + string message = StringUtil.Format(AutomationExceptions.ObjectDisposed, objectName); var e = new PSObjectDisposedException(objectName, message); diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 818ca7a4033..747791d7ff4 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -52,6 +52,7 @@ public override event EventHandler DataReady } } } + remove { lock (_monitorObject) @@ -469,6 +470,7 @@ private static Collection MakePSObjectCollection( { retval.Add(MakePSObject(o)); } + return retval; } #endregion Private @@ -578,6 +580,7 @@ public override Collection NonBlockingRead(int maxRequested) { return new Collection(); } + Collection results = new Collection(); int readCount = maxRequested; @@ -759,6 +762,7 @@ public override Collection NonBlockingRead(int maxRequested) { return new Collection(); } + Collection results = new Collection(); int readCount = maxRequested; diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index d90fbdac241..3188c012852 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -621,6 +621,7 @@ internal override WaitHandle ReadHandle handle = _readWaitHandle; } + return handle; } } @@ -648,6 +649,7 @@ internal override WaitHandle WriteHandle handle = _writeWaitHandle; } + return handle; } } @@ -731,6 +733,7 @@ internal override PipelineWriter ObjectWriter writer = _writer; } + return writer; } } @@ -754,6 +757,7 @@ internal override bool EndOfPipeline { endOfStream = (_objects.Count == 0 && _isOpen == false); } + return endOfStream; } } @@ -780,6 +784,7 @@ internal override bool IsOpen { isOpen = _isOpen; } + return isOpen; } } @@ -797,6 +802,7 @@ internal override int Count { count = _objects.Count; } + return count; } } @@ -914,6 +920,7 @@ private void RaiseEvents() { } } + if (_writeWaitHandle != null) { try @@ -949,6 +956,7 @@ private void RaiseEvents() { } } + if (unblockWriters) { try @@ -1060,6 +1068,7 @@ internal override void Close() catch (ObjectDisposedException) { } + RaiseEvents(); } } @@ -1081,6 +1090,7 @@ internal override object Read() { return result[0]; } + Diagnostics.Assert(result.Count == 0, "Invalid number of objects returned"); return AutomationNull.Value; @@ -1116,6 +1126,7 @@ internal override Collection Read(int count) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } + if (count == 0) { return new Collection(); @@ -1135,6 +1146,7 @@ internal override Collection Read(int count) { continue; // wait some more } + raiseEvents = true; // NTRAID#Windows Out Of Band Releases-925566-2005/12/07-JonN int objectsAdded = 0; @@ -1145,6 +1157,7 @@ internal override Collection Read(int count) if (--count <= 0) break; } + _objects.RemoveRange(0, objectsAdded); } } @@ -1216,6 +1229,7 @@ internal override Collection NonBlockingRead(int maxRequested) { return new Collection(); } + if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); @@ -1239,6 +1253,7 @@ internal override Collection NonBlockingRead(int maxRequested) { results.Add(_objects[i]); } + raiseEvents = true; _objects.RemoveRange(0, readCount); } @@ -1251,6 +1266,7 @@ internal override Collection NonBlockingRead(int maxRequested) RaiseEvents(); } } + return results ?? new Collection(); } @@ -1276,6 +1292,7 @@ internal override object Peek() result = _objects[0]; } } + return result; } @@ -1333,6 +1350,7 @@ internal override int Write(object obj, bool enumerateCollection) { enumerable = LanguagePrimitives.GetEnumerable(obj); } + if (enumerable == null) a.Add(obj); else @@ -1351,6 +1369,7 @@ internal override int Write(object obj, bool enumerateCollection) // we just ignore it continue; } + a.Add(o); } } @@ -1456,6 +1475,7 @@ private void DFT_AddHandler_OnDataReady(EventHandler eventHandler) { DataReady += eventHandler; } + private void DFT_RemoveHandler_OnDataReady(EventHandler eventHandler) { DataReady -= eventHandler; @@ -1620,6 +1640,7 @@ internal override bool EndOfPipeline { endOfStream = (_objects.Count == 0 && !_isOpen); } + return endOfStream; } } @@ -1769,6 +1790,7 @@ internal override PipelineWriter ObjectWriter } } } + return _writer; } } @@ -1822,6 +1844,7 @@ internal override int Write(object obj, bool enumerateCollection) { enumerable = LanguagePrimitives.GetEnumerable(obj); } + if (enumerable == null) { objectsToAdd.Add((T)LanguagePrimitives.ConvertTo(obj, @@ -1841,6 +1864,7 @@ internal override int Write(object obj, bool enumerateCollection) // we just ignore it continue; } + objectsToAdd.Add((T)LanguagePrimitives.ConvertTo(obj, typeof(T), Globalization.CultureInfo.InvariantCulture)); } diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index 229f24803ac..a452e8924c8 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -80,6 +80,7 @@ public static void ReportStartupTelemetry(IHostProvidesTelemetryData ihptd) ProcessName = hostName, }); } + s_sessionStartTime = DateTime.Now; } @@ -244,6 +245,7 @@ internal static void ReportRemoteSessionCreated( configurationName = configurationName.Substring(index + 1); } } + configurationType = GetConfigurationTypefromName(configurationName); } else @@ -393,7 +395,9 @@ internal ScriptBlockTelemetry() } internal Dictionary CommandsCalled { get; private set; } + internal int CountOfCommands { get; private set; } + internal int CountOfDotSourcedCommands { get; private set; } public override AstVisitAction VisitCommand(CommandAst commandAst) @@ -414,8 +418,11 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) } internal int MaxStringSize { get; private set; } + internal int StringLiteralCount { get; private set; } + internal int StringLiteralCumulativeSize { get; private set; } + public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { var stringSize = stringConstantExpressionAst.Value.Length; @@ -435,8 +442,11 @@ public override AstVisitAction VisitExpandableStringExpression(ExpandableStringE } internal int MaxArraySize { get; private set; } + internal int ArrayLiteralCount { get; private set; } + internal int ArrayLiteralCumulativeSize { get; private set; } + public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { var elementCount = arrayLiteralAst.Elements.Count; @@ -447,6 +457,7 @@ public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst } internal int StatementCount { get; private set; } + public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) { StatementCount += blockStatementAst.Body.Statements.Count; @@ -460,6 +471,7 @@ public override AstVisitAction VisitNamedBlock(NamedBlockAst namedBlockAst) } internal int FunctionCount { get; private set; } + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { FunctionCount += 1; @@ -467,6 +479,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun } internal int ScriptBlockCount { get; private set; } + public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { ScriptBlockCount += 1; @@ -474,7 +487,9 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA } internal int MaxPipelineDepth { get; private set; } + internal int PipelineCount { get; private set; } + public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) { MaxPipelineDepth = Math.Max(MaxPipelineDepth, pipelineAst.PipelineElements.Count); @@ -483,7 +498,9 @@ public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) } internal int ClassCount { get; private set; } + internal int EnumCount { get; private set; } + public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { if (typeDefinitionAst.IsClass) diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index af368ecf0c6..ee27aa7219a 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -109,11 +109,13 @@ internal ParameterBindingException( { errorPosition = invocationInfo.ScriptPosition; } + if (errorPosition != null) { _line = errorPosition.StartLineNumber; _offset = errorPosition.StartColumnNumber; } + _resourceString = resourceString; _errorId = errorId; @@ -215,6 +217,7 @@ internal ParameterBindingException( { errorPosition = invocationInfo.ScriptPosition; } + if (errorPosition != null) { _line = errorPosition.StartLineNumber; @@ -258,6 +261,7 @@ internal ParameterBindingException( { _commandName = _invocationInfo.MyCommand.Name; } + IScriptExtent errorPosition = null; if (_invocationInfo != null) { @@ -398,6 +402,7 @@ public string ParameterName return _parameterName; } } + private string _parameterName = String.Empty; /// @@ -410,6 +415,7 @@ public Type ParameterType return _parameterType; } } + private Type _parameterType; /// @@ -422,6 +428,7 @@ public Type TypeSpecified return _typeSpecified; } } + private Type _typeSpecified; /// @@ -434,6 +441,7 @@ public string ErrorId return _errorId; } } + private string _errorId; /// @@ -446,6 +454,7 @@ public Int64 Line return _line; } } + private Int64 _line = Int64.MinValue; /// @@ -458,6 +467,7 @@ public Int64 Offset return _offset; } } + private Int64 _offset = Int64.MinValue; /// @@ -470,6 +480,7 @@ public InvocationInfo CommandInvocation return _invocationInfo; } } + private InvocationInfo _invocationInfo; #endregion Properties @@ -501,6 +512,7 @@ private string BuildMessage() { result = StringUtil.Format(_resourceString, messageArgs); } + return result; } @@ -697,6 +709,7 @@ internal bool SwallowException { get { return _swallowException; } } + private readonly bool _swallowException = false; #endregion Property diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index a2808fd8e3c..844ebac54fc 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -275,6 +275,7 @@ internal static string ResolveFilePath(string filePath, PSCmdlet command, bool i { ReportMultipleFilesNotSupported(command); } + if (filePaths.Count == 0) { ReportWildcardingFailure(command, filePath); @@ -286,6 +287,7 @@ internal static string ResolveFilePath(string filePath, PSCmdlet command, bool i { path = null; } + if (string.IsNullOrEmpty(path)) { CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(command); @@ -300,6 +302,7 @@ internal static string ResolveFilePath(string filePath, PSCmdlet command, bool i ReportWrongProviderType(command, provider.FullName); } } + return path; } @@ -359,6 +362,7 @@ internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string modu PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem); rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath); } + if (string.IsNullOrEmpty(rootedPath)) { string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath(); diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index a428af3cc18..a00bc63831a 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -367,6 +367,7 @@ internal static bool EnableTokenPrivilege(string privilegeName, ref TOKEN_PRIVIL { CloseHandle(tokenHandler); } + CloseHandle(processHandler); } } @@ -422,6 +423,7 @@ internal static bool RestoreTokenPrivilege(string privilegeName, ref TOKEN_PRIVI { CloseHandle(tokenHandler); } + CloseHandle(processHandler); } } @@ -649,11 +651,13 @@ public void Dispose(bool disposing) this.hStdInput.Dispose(); this.hStdInput = null; } + if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) { this.hStdOutput.Dispose(); this.hStdOutput = null; } + if ((this.hStdError != null) && !this.hStdError.IsInvalid) { this.hStdError.Dispose(); @@ -775,6 +779,7 @@ internal enum SnapshotFlags : uint Inherit = 0x80000000, NoHeaps = 0x40000000 } + [StructLayout(LayoutKind.Sequential)] internal struct PROCESSENTRY32 { diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 227b4bcf88d..e99acea2eaa 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -768,6 +768,7 @@ public virtual PowerShellTraceKeywords Keywords { return PowerShellTraceKeywords.None; } + set { PowerShellTraceKeywords powerShellTraceKeywords = value; @@ -818,6 +819,7 @@ public override PowerShellTraceKeywords Keywords { return _keywords; } + set { _keywords = value; @@ -1014,6 +1016,7 @@ public bool TraceErrorRecord(ErrorRecord errorRecord) { message = errorRecord.ErrorDetails.Message; } + return DebugChannel.TraceError(PowerShellTraceEvent.ErrorRecord, PowerShellTraceOperationCode.Exception, PowerShellTraceTask.None, message, diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index b3c4b95d7d0..1054bbf59fc 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -198,6 +198,7 @@ internal static string SafeToString(object obj) { result = obj.ToString(); } + return result; } catch (Exception) @@ -248,6 +249,7 @@ internal static PowerShell AddCommandWithPreferenceSetting(this PowerShell power { powershell.AddCommand(command); } + powershell .AddParameter("ErrorAction", ActionPreference.Ignore) .AddParameter("WarningAction", ActionPreference.Ignore) diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 33951ef1ea3..70442ae7898 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -199,6 +199,7 @@ internal static string GetTemporaryDirectory() { tempDir = String.Empty; // will become current working directory } + return tempDir; } @@ -303,6 +304,7 @@ internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAs { usingAstText = usingAstText.ToLowerInvariant(); } + return StringToBase64Converter.StringToBase64String(usingAstText); } @@ -371,7 +373,9 @@ internal static Hashtable EvaluatePowerShellDataFile( bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } + if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } + if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; @@ -528,6 +532,7 @@ internal static Hashtable GetModuleManifestProperties(string psDataFilePath, str } } } + return result; } } @@ -557,6 +562,7 @@ internal static string StringToBase64String(string input) { throw PSTraceSource.NewArgumentNullException("input"); } + string base64 = Convert.ToBase64String ( Encoding.Unicode.GetBytes(input.ToCharArray()) @@ -575,6 +581,7 @@ internal static string Base64ToString(string base64) { throw PSTraceSource.NewArgumentNullException("base64"); } + string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); return output; } @@ -590,6 +597,7 @@ internal static object[] Base64ToArgsConverter(string base64) { throw PSTraceSource.NewArgumentNullException("base64"); } + string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); //Deserialize string @@ -653,6 +661,7 @@ static CRC32Hash() temp >>= 1; } } + table[i] = temp; } } @@ -665,6 +674,7 @@ private static uint Compute(byte[] buffer) var index = (byte)(crc ^ buffer[i] & 0xff); crc = (crc >> 8) ^ table[index]; } + return ~crc; } diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index 24ee0e34526..f52dedad778 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -116,6 +116,7 @@ internal static ResourceManager GetResourceManager( internal static bool DFT_DoMonitorFailingResourceLookup { get { return ResourceManagerCache.s_DFT_monitorFailingResourceLookup; } + set { ResourceManagerCache.s_DFT_monitorFailingResourceLookup = value; } } @@ -202,6 +203,7 @@ internal static string GetResourceString( Diagnostics.Assert(false, "Lookup failure: baseName " + baseName + " resourceId " + resourceId); } + return text; } diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index f0e8ead985a..bc54603f41f 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -161,9 +161,11 @@ public virtual ErrorRecord ErrorRecord _errorCategory, _targetObject); } + return _errorRecord; } } + private ErrorRecord _errorRecord; private string _errorId = "RuntimeException"; private ErrorCategory _errorCategory = ErrorCategory.NotSpecified; @@ -229,6 +231,7 @@ internal static string RetrieveMessage(ErrorRecord errorRecord) { return errorRecord.ErrorDetails.Message; } + if (errorRecord.Exception == null) return string.Empty; return errorRecord.Exception.Message; @@ -264,6 +267,7 @@ internal static Exception RetrieveException(ErrorRecord errorRecord) public bool WasThrownFromThrowStatement { get { return _thrownByThrowStatement; } + set { _thrownByThrowStatement = value; @@ -277,6 +281,7 @@ public bool WasThrownFromThrowStatement } } } + private bool _thrownByThrowStatement; /// @@ -289,8 +294,10 @@ public bool WasThrownFromThrowStatement internal bool SuppressPromptInInterpreter { get { return _suppressPromptInInterpreter; } + set { _suppressPromptInInterpreter = value; } } + private bool _suppressPromptInInterpreter; #endregion Internal @@ -302,6 +309,7 @@ internal Token ErrorToken { return _errorToken; } + set { _errorToken = value; diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 7005ba7d765..884eda3ce0a 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -224,6 +224,7 @@ internal ProviderInvocationException( /// Gets the provider information of the provider that threw an exception. /// public ProviderInfo ProviderInfo { get { return _providerInfo; } } + [NonSerialized] internal ProviderInfo _providerInfo; @@ -242,9 +243,11 @@ public override ErrorRecord ErrorRecord ErrorCategory.NotSpecified, null); } + return _errorRecord; } } + [NonSerialized] private ErrorRecord _errorRecord; #endregion Properties @@ -263,12 +266,14 @@ private static string RetrieveMessage( "ProviderInvocationException.RetrieveMessage needs innerException"); return string.Empty; } + if (String.IsNullOrEmpty(errorId)) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs errorId"); return RuntimeException.RetrieveMessage(innerException); } + if (provider == null) { Diagnostics.Assert(false, @@ -283,6 +288,7 @@ private static string RetrieveMessage( "ProviderInvocationException.RetrieveMessage bad errorId " + errorId); return RuntimeException.RetrieveMessage(innerException); } + string result = null; if (path == null) @@ -304,6 +310,7 @@ private static string RetrieveMessage( path, RuntimeException.RetrieveMessage(innerException)); } + return result; } @@ -314,6 +321,7 @@ public override string Message { get { return (String.IsNullOrEmpty(_message)) ? base.Message : _message; } } + [NonSerialized] private string _message /* = null */; @@ -499,9 +507,11 @@ public override ErrorRecord ErrorRecord _errorCategory, _itemName); } + return _errorRecord; } } + private ErrorRecord _errorRecord; /// @@ -511,6 +521,7 @@ public string ItemName { get { return _itemName; } } + private string _itemName = String.Empty; /// @@ -520,6 +531,7 @@ public SessionStateCategory SessionStateCategory { get { return _sessionStateCategory; } } + private SessionStateCategory _sessionStateCategory = SessionStateCategory.Variable; #endregion Properties @@ -544,6 +556,7 @@ private static string BuildMessage( a = new object[1]; a[0] = itemName; } + return StringUtil.Format(resourceStr, a); } #endregion Private @@ -841,6 +854,7 @@ public ReadOnlyCollection PossibleMatches return _possibleMatches; } } + private ReadOnlyCollection _possibleMatches; #endregion public properties diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 680e257332e..1d090050209 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -296,6 +296,7 @@ internal PSTraceSource(string fullName, string name, string description, bool tr _flags = (PSTraceSourceOptions)Enum.Parse(typeof(PSTraceSourceOptions), options, true); } } + ShowHeaders = traceHeaders; Description = description; } @@ -455,6 +456,7 @@ internal IDisposable TraceScope(string msg) } catch { } } + return null; } @@ -468,6 +470,7 @@ internal IDisposable TraceScope(string format, object arg1) } catch { } } + return null; } @@ -481,6 +484,7 @@ internal IDisposable TraceScope(string format, object arg1, object arg2) } catch { } } + return null; } @@ -558,6 +562,7 @@ internal IDisposable TraceMethod( // normal operation. } } + return null; } @@ -605,6 +610,7 @@ internal IDisposable TraceEventHandlers() // normal operation. } } + return null; } @@ -657,6 +663,7 @@ internal IDisposable TraceEventHandlers( // normal operation. } } + return null; } #endregion PSTraceSourceOptions.Events methods/helpers @@ -718,6 +725,7 @@ internal IDisposable TraceLock(string lockName) // normal operation. } } + return null; } @@ -1143,6 +1151,7 @@ private static string GetCallingMethodNameAndParameters(int skipFrames) // raised while a thread is shutting down during // normal operation. } + return methodAndParameters.ToString(); } @@ -1405,6 +1414,7 @@ internal TraceSource TraceSource { get { return _traceSource ?? (_traceSource = new MonadTraceSource(_name)); } } + private TraceSource _traceSource; #endregion Class helper methods and properties @@ -1476,6 +1486,7 @@ public SourceSwitch Switch { return TraceSource.Switch; } + set { TraceSource.Switch = value; @@ -1716,6 +1727,7 @@ public void Dispose() { _tracer.OutputLine(_flag, _leavingScopeFormatter, _scopeName); } + GC.SuppressFinalize(this); } diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs index ce5312a7710..8d8577a861f 100644 --- a/src/System.Management.Automation/utils/assert.cs +++ b/src/System.Management.Automation/utils/assert.cs @@ -67,6 +67,7 @@ internal static string StackTrace(int framesToSkip) StackFrame frame = frames[i]; frameString.Append(frame.ToString()); } + return frameString.ToString(); } @@ -87,6 +88,7 @@ internal static bool ThrowInsteadOfAssert return s_throwInsteadOfAssert; } } + set { lock (s_throwInsteadOfAssertLock) @@ -173,6 +175,7 @@ internal static void tracer.TraceException(e); throw e; } + StringBuilder builder = new StringBuilder(); builder.Append("ASSERT: "); builder.Append(whyThisShouldNeverHappen); @@ -192,6 +195,7 @@ internal static void string assertionMessage = "ASSERT: " + whyThisShouldNeverHappen + " " + detailMessage + " "; throw new AssertException(assertionMessage); } + System.Diagnostics.Debug.Fail(whyThisShouldNeverHappen, detailMessage); #endif } From b1f591c9f54a0ce20a42cf1c63e09a53c1abc517 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:58 -0800 Subject: [PATCH 43/81] Update config --- .../singleshell/config/MshSnapinInfo.cs | 17 +++++++++++++++++ .../config/MshSnapinLoadException.cs | 1 + 2 files changed, 18 insertions(+) diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index ab0847fdce1..f0cf85fd8be 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -276,6 +276,7 @@ public string Description { LoadIndirectResources(); } + return _description; } } @@ -294,6 +295,7 @@ public string Vendor { LoadIndirectResources(); } + return _vendor; } } @@ -333,6 +335,7 @@ internal RegistryKey MshSnapinKey catch (System.IO.IOException) { } + return mshsnapinKey; } } @@ -426,6 +429,7 @@ internal static bool IsPSSnapinIdValid(string psSnapinId) { return false; } + return Regex.IsMatch(psSnapinId, "^[A-Za-z0-9-_\x2E]*$"); } @@ -509,6 +513,7 @@ internal static Collection ReadAll() { continue; } + Collection oneVersionMshSnapins = null; try { @@ -522,6 +527,7 @@ internal static Collection ReadAll() catch (ArgumentException) { } + if (oneVersionMshSnapins != null) { foreach (PSSnapInInfo info in oneVersionMshSnapins) @@ -552,6 +558,7 @@ bool MeetsVersionFormat(string version) { r = false; } + return r; } @@ -573,6 +580,7 @@ internal static Collection ReadAll(string psVersion) { throw PSTraceSource.NewArgumentNullException("psVersion"); } + RegistryKey monadRootKey = GetMonadRootKey(); return ReadAll(monadRootKey, psVersion); } @@ -607,6 +615,7 @@ private static Collection ReadAll(RegistryKey monadRootKey, string { continue; } + try { mshsnapins.Add(ReadOne(mshsnapinRoot, id)); @@ -648,6 +657,7 @@ internal static PSSnapInInfo Read(string psVersion, string mshsnapinId) { throw PSTraceSource.NewArgumentNullException("psVersion"); } + if (string.IsNullOrEmpty(mshsnapinId)) { throw PSTraceSource.NewArgumentNullException("mshsnapinId"); @@ -703,6 +713,7 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI s_mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); description = string.Empty; } + string vendor = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Vendor, false); if (vendor == null) { @@ -892,6 +903,7 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu { throw PSTraceSource.NewArgumentException("PublicKeyToken", MshSnapinInfo.PublicKeyTokenAccessFailed); } + publicKeyToken = ConvertByteArrayToString(publicTokens); // save some cpu cycles by hardcoding the culture to neutral // assembly should never be targeted to a particular culture @@ -1119,6 +1131,7 @@ internal static RegistryKey GetMonadRootKey() Dbg.Assert(false, "Root Key of Monad installation is not present"); throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadRootRegistryAccessFailed); } + return rootKey; } @@ -1180,6 +1193,7 @@ internal static { throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.SpecifiedVersionNotFound, versionKey); } + return versionRoot; } @@ -1206,6 +1220,7 @@ private static { throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } + return mshsnapinRoot; } @@ -1232,6 +1247,7 @@ internal static { throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } + RegistryKey mshsnapinKey = mshsnapinRoot.OpenSubKey(mshSnapInName); return mshsnapinKey; } @@ -1316,6 +1332,7 @@ private static IList DefaultMshSnapins return s_defaultMshSnapins; } } + private static IList s_defaultMshSnapins = null; private static object s_syncObject = new object(); diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index c29544a02f6..a6e3ee1bbc9 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -141,6 +141,7 @@ public override ErrorRecord ErrorRecord ErrorCategory.NotSpecified, null); } + return _errorRecord; } } From dc939927077690632e9b56c27a81c89fc82e5315 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:58 -0800 Subject: [PATCH 44/81] Update perfCounters --- .../utils/perfCounters/CounterSetInstanceBase.cs | 6 ++++++ .../utils/perfCounters/CounterSetRegistrarBase.cs | 2 ++ .../utils/perfCounters/PSPerfCountersMgr.cs | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs index 9c1e4d718ed..e32aef992c6 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs @@ -96,6 +96,7 @@ protected bool RetrieveTargetCounterIdIfValid(int counterId, bool isNumerator, o isDenominatorValid = true; break; } + if (isDenominatorValid == false) { InvalidOperationException invalidOperationException = @@ -107,8 +108,10 @@ protected bool RetrieveTargetCounterIdIfValid(int counterId, bool isNumerator, o _tracer.TraceException(invalidOperationException); return false; } + targetCounterId = counterId + 1; } + return true; } @@ -485,6 +488,7 @@ public override bool SetCounterValue(string counterName, long counterValue, bool _tracer.TraceException(argNullException); return false; } + try { int targetCounterId = this._counterNameToIdMapping[counterName]; @@ -517,6 +521,7 @@ public override bool GetCounterValue(int counterId, bool isNumerator, out long c _tracer.TraceException(objectDisposedException); return false; } + int targetCounterId; if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) { @@ -567,6 +572,7 @@ public override bool GetCounterValue(string counterName, bool isNumerator, out l _tracer.TraceException(argNullException); return false; } + try { int targetCounterId = this._counterNameToIdMapping[counterName]; diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 03865fd3f6d..b7574ffe008 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -124,6 +124,7 @@ protected CounterSetRegistrarBase( counterInfoArray[i].Name ); } + this._counterSetInstanceBase = null; } @@ -137,6 +138,7 @@ protected CounterSetRegistrarBase( { throw new ArgumentNullException("srcCounterSetRegistrarBase"); } + ProviderId = srcCounterSetRegistrarBase.ProviderId; CounterSetId = srcCounterSetRegistrarBase.CounterSetId; CounterSetInstType = srcCounterSetRegistrarBase.CounterSetInstType; diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs index 52b19a14f76..126f36748bb 100644 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs @@ -82,6 +82,7 @@ public bool IsCounterSetRegistered(string counterSetName, out Guid counterSetId) _tracer.TraceException(argNullException); return false; } + return _CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId); } @@ -138,8 +139,10 @@ public bool AddCounterSetInstance(CounterSetRegistrarBase counterSetRegistrarIns _tracer.TraceException(invalidOperationException); return false; } + _CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId); } + _CounterSetIdToInstanceMapping.TryAdd( counterSetId, counterSetRegistrarInstance.CounterSetInstance); @@ -149,6 +152,7 @@ public bool AddCounterSetInstance(CounterSetRegistrarBase counterSetRegistrarIns _tracer.TraceException(overflowException); return false; } + return true; } @@ -234,6 +238,7 @@ public bool UpdateCounterByValue( _tracer.TraceException(argNullException); return false; } + Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { @@ -451,6 +456,7 @@ internal void RemoveAllCounterSets() CounterSetInstanceBase currentCounterSetInstance = _CounterSetIdToInstanceMapping[counterSetId]; currentCounterSetInstance.Dispose(); } + _CounterSetIdToInstanceMapping.Clear(); _CounterSetNameToIdMapping.Clear(); } From 561eca168395f53bddbddba4db96c5bd3ea0fe3f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:58 -0800 Subject: [PATCH 45/81] Update tracing --- .../utils/tracing/EtwActivity.cs | 14 ++++++++++++++ .../utils/tracing/IMethodInvoker.cs | 1 + .../utils/tracing/PSSysLogProvider.cs | 1 + .../utils/tracing/SysLogProvider.cs | 7 +++++++ .../utils/tracing/Tracing.cs | 1 + 5 files changed, 24 insertions(+) diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index cd8dcf2204d..28491fd2bdc 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -124,10 +124,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) { throw new ArgumentNullException("callback"); } + if (tracer == null) { throw new ArgumentNullException("tracer"); } + this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); this.callbackNoParam = callback; @@ -144,10 +146,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) { throw new ArgumentNullException("callback"); } + if (tracer == null) { throw new ArgumentNullException("tracer"); } + this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); this.callbackWithState = callback; @@ -164,10 +168,12 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) { throw new ArgumentNullException("callback"); } + if (tracer == null) { throw new ArgumentNullException("tracer"); } + this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); this.asyncCallback = callback; @@ -189,10 +195,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) { throw new ArgumentNullException("callback"); } + if (tracer == null) { throw new ArgumentNullException("tracer"); } + this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); this.callbackWithStateAndArgs = callback; @@ -282,6 +290,7 @@ public static bool SetActivityId(Guid activityId) EventProvider.SetActivityId(ref activityId); return true; } + return false; } @@ -377,6 +386,7 @@ public CallbackNoParameter Correlate(CallbackNoParameter callback) { throw new ArgumentNullException("callback"); } + return new CorrelatedCallback(this, callback).Callback; } @@ -391,6 +401,7 @@ public CallbackWithState Correlate(CallbackWithState callback) { throw new ArgumentNullException("callback"); } + return new CorrelatedCallback(this, callback).Callback; } @@ -405,6 +416,7 @@ public AsyncCallback Correlate(AsyncCallback callback) { throw new ArgumentNullException("callback"); } + return new CorrelatedCallback(this, callback).Callback; } @@ -420,6 +432,7 @@ public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback) { throw new ArgumentNullException("callback"); } + return new CorrelatedCallback(this, callback).Callback; } @@ -494,6 +507,7 @@ private EventProvider GetProvider() providers[ProviderId] = currentProvider; } } + return currentProvider; } diff --git a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs index 0b07aad161f..20f60433cc1 100644 --- a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs @@ -9,6 +9,7 @@ namespace System.Management.Automation.Tracing internal interface IMethodInvoker { Delegate Invoker { get; } + object[] CreateInvokerArgs(Delegate methodToInvoke, object[] methodToInvokeArgs); } } diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index fa07b20883a..f60ece39bf8 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -53,6 +53,7 @@ private static StringBuilder PayloadBuilder // NOTE: Thread static fields must be explicitly initialized for each thread. _payloadBuilder = new StringBuilder(200); } + return _payloadBuilder; } } diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index d7f4827af05..c136aeac8c4 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -108,6 +108,7 @@ public SysLogProvider(string applicationId, PSLevel level, PSKeyword keywords, P { _keywordFilter |= (ulong) PSKeyword.UseAlwaysOperational; } + if ((_channelFilter & (ulong) PSChannel.Analytic) != 0) { _keywordFilter |= (ulong) PSKeyword.UseAlwaysAnalytic; @@ -133,6 +134,7 @@ private static StringBuilder MessageBuilder // NOTE: Thread static fields must be explicitly initialized for each thread. _messageBuilder = new StringBuilder(200); } + return _messageBuilder; } } @@ -156,8 +158,10 @@ private static Guid Activity // NOTE: Thread static fields must be explicitly initialized for each thread. _activity = Guid.NewGuid(); } + return _activity.Value; } + set { _activity = value; @@ -200,6 +204,7 @@ private bool ShouldLog(PSLevel level, PSKeyword keywords, PSChannel channel) { _resourceManager = new global::System.Resources.ResourceManager("System.Management.Automation.resources.EventResource", typeof(EventResource).Assembly); } + return _resourceManager; } } @@ -215,6 +220,7 @@ private bool ShouldLog(PSLevel level, PSKeyword keywords, PSChannel channel) { return _resourceCulture; } + set { _resourceCulture = value; @@ -229,6 +235,7 @@ private static string GetResourceString(string resourceName) value = string.Format(CultureInfo.InvariantCulture, "Unknown resource: {0}", resourceName); Diagnostics.Assert(false, value); } + return value; } diff --git a/src/System.Management.Automation/utils/tracing/Tracing.cs b/src/System.Management.Automation/utils/tracing/Tracing.cs index d3a1cbecf14..1ed3663ffa3 100644 --- a/src/System.Management.Automation/utils/tracing/Tracing.cs +++ b/src/System.Management.Automation/utils/tracing/Tracing.cs @@ -38,6 +38,7 @@ public static string GetExceptionString(Exception exception) { exception = exception.InnerException; } + return sb.ToString(); } From 03810a17d0761757f5aef4ac088b8a0aea9be37c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:59 -0800 Subject: [PATCH 46/81] Update cmdletization --- .../cmdletization/MethodInvocationInfo.cs | 4 +++ .../cmdletization/ObjectModelWrapper.cs | 8 +++++ .../cimSupport/cmdletization/ScriptWriter.cs | 35 +++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 226ee1edd19..9e40b087ebc 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -61,12 +61,14 @@ internal IEnumerable GetArgumentsOfType() where T : class { continue; } + var objectInstance = methodParameter.Value as T; if (objectInstance != null) { result.Add(objectInstance); continue; } + var objectInstanceArray = methodParameter.Value as IEnumerable; if (objectInstanceArray != null) { @@ -78,9 +80,11 @@ internal IEnumerable GetArgumentsOfType() where T : class result.Add(objectInstance2); } } + continue; } } + return result; } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index dbf58e240d8..f5a1400a26d 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -21,14 +21,17 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, { throw new ArgumentNullException("cmdlet"); } + if (string.IsNullOrEmpty(className)) { throw new ArgumentNullException("className"); } + if (classVersion == null) // possible and ok to have classVersion==string.Empty { throw new ArgumentNullException("classVersion"); } + if (privateData == null) { throw new ArgumentNullException("privateData"); @@ -161,6 +164,7 @@ public PSCmdlet Cmdlet return _cmdlet; } } + private PSCmdlet _cmdlet; /// @@ -173,6 +177,7 @@ public string ClassName return _className; } } + private string _className; /// @@ -186,6 +191,7 @@ public string ClassVersion return _classVersion; } } + private string _classVersion; /// @@ -198,6 +204,7 @@ public Version ModuleVersion return _moduleVersion; } } + private Version _moduleVersion; /// @@ -210,6 +217,7 @@ public IDictionary PrivateData return _privateData; } } + private IDictionary _privateData; } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index b9c21d92ef8..10e675e9382 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -139,6 +139,7 @@ internal ScriptWriter( objectModelWrapperName); throw new XmlException(message); } + Type baseType = _objectModelWrapper; while ((!baseType.IsGenericType) || baseType.GetGenericTypeDefinition() != typeof(CmdletAdapter<>)) { @@ -153,6 +154,7 @@ internal ScriptWriter( throw new XmlException(message); } } + _objectInstanceType = baseType.GetGenericArguments()[0]; _moduleName = moduleName; @@ -256,6 +258,7 @@ private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) string newline = (attributes.Length > 0) ? Environment.NewLine : string.Empty; attributes.AppendFormat(CultureInfo.InvariantCulture, "{0}[Obsolete({1})]", newline, obsoleteMsg); } + return attributes.ToString(); } @@ -306,6 +309,7 @@ private Dictionary GetCommonParameters() psetMetadata.ValueFromPipelineByPropertyName = false; psetMetadata.ValueFromRemainingArguments = false; } + commonParameters.Add(parameterMetadata.Name, parameterMetadata); } @@ -318,6 +322,7 @@ private Dictionary GetCommonParameters() _objectModelWrapper.FullName); throw new XmlException(message); } + foreach (ParameterMetadata parameter in commonParameters.Values) { if ((parameter.ParameterSets.Count == 1) && (parameter.ParameterSets.ContainsKey(ParameterAttribute.AllParameterSets))) @@ -381,6 +386,7 @@ private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) parameterSetName); throw new XmlException(message); } + parameterSetNames.Add(parameterSetName, null); } @@ -460,6 +466,7 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet } } } + if (getCmdletParameters.QueryableAssociations != null) { foreach (Association association in getCmdletParameters.QueryableAssociations) @@ -474,6 +481,7 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet } } } + if (getCmdletParameters.QueryOptions != null) { foreach (QueryOption option in getCmdletParameters.QueryOptions) @@ -636,6 +644,7 @@ private ParameterMetadata GetParameter( { elementType = parameterType.HasElementType ? parameterType.GetElementType() : parameterType; } + object min = LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateRange.Min, elementType, CultureInfo.InvariantCulture); object max = LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateRange.Max, elementType, CultureInfo.InvariantCulture); parameterMetadata.Attributes.Add(new ValidateRangeAttribute(min, max)); @@ -648,6 +657,7 @@ private ParameterMetadata GetParameter( { allowedValues.Add(allowedValue); } + parameterMetadata.Attributes.Add(new ValidateSetAttribute(allowedValues.ToArray())); } } @@ -666,14 +676,17 @@ private ParameterMetadata GetParameter( parameterFlags |= ParameterSetMetadata.ParameterFlags.Mandatory; } } + if (isValueFromPipeline) { parameterFlags |= ParameterSetMetadata.ParameterFlags.ValueFromPipeline; } + if (isValueFromPipelineByPropertyName) { parameterFlags |= ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName; } + parameterMetadata.ParameterSets.Add(parameterSetName, new ParameterSetMetadata(position, parameterFlags, null)); return parameterMetadata; @@ -714,6 +727,7 @@ private ParameterMetadata GetParameter( { queryParameterSets = parameterCmdletization.CmdletParameterSets; } + foreach (string parameterSetName in queryParameterSets) { if (parameterSetName.Equals(ScriptWriter.InputObjectQueryParameterSetName, StringComparison.OrdinalIgnoreCase)) @@ -832,6 +846,7 @@ private static string EscapeModuleNameForHelpComment(string name) result.Append(c); } } + return result.ToString(); } @@ -849,6 +864,7 @@ private static List> GetCombinations(params IEnumerable[] x subresult.Add(s); result.Add(subresult); } + return result; } else @@ -979,6 +995,7 @@ private static MethodParameterBindings GetMethodParameterKind(InstanceMethodPara { bindings |= MethodParameterBindings.In; } + if (methodParameter.CmdletOutputMetadata != null) { if (methodParameter.CmdletOutputMetadata.ErrorCode == null) @@ -1003,6 +1020,7 @@ private static MethodParameterBindings GetMethodParameterKind(StaticMethodParame { bindings |= MethodParameterBindings.In; } + if (methodParameter.CmdletOutputMetadata != null) { if (methodParameter.CmdletOutputMetadata.ErrorCode == null) @@ -1139,6 +1157,7 @@ private void GenerateMethodParametersProcessing( { output.WriteLine(" switch -exact ($PSCmdlet.ParameterSetName) { "); } + foreach (StaticMethodMetadata method in staticCmdlet.Method) { if (multipleMethods) @@ -1154,6 +1173,7 @@ string parameterSetName in firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } + output.WriteLine(") -contains $_ } {"); } @@ -1216,6 +1236,7 @@ string parameterSetName in } } } + if (method.ReturnValue != null) { MethodParameterBindings methodParameterBindings = GetMethodParameterKind(method.ReturnValue); @@ -1269,6 +1290,7 @@ string parameterSetName in } } } + if (multipleMethods) { output.WriteLine(" }"); @@ -1302,6 +1324,7 @@ private void GenerateMethodParametersProcessing( firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } + output.WriteLine(") -contains $_ } {"); List typesOfOutParameters = new List(); @@ -1354,6 +1377,7 @@ private void GenerateMethodParametersProcessing( } } } + if (method.ReturnValue != null) { MethodParameterBindings methodParameterBindings = GetMethodParameterKind(method.ReturnValue); @@ -1442,6 +1466,7 @@ private void GenerateIfBoundParameter( firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } + output.WriteLine(") -contains $PSCmdlet.ParameterSetName )) {"); } @@ -1467,6 +1492,7 @@ private ParameterMetadata GenerateQueryClause( { cmdletParameterMetadata.ParameterType = typeof(object); } + cmdletParameterMetadata.ParameterType = cmdletParameterMetadata.ParameterType.MakeArrayType(); } @@ -1487,6 +1513,7 @@ private ParameterMetadata GenerateQueryClause( localVariableName, CodeGeneration.EscapeVariableName(cmdletParameterMetadata.Name)); } + output.Write( " $__cmdletization_queryBuilder.{0}('{1}', ${2}", queryBuilderMethodName, @@ -1520,6 +1547,7 @@ private static BehaviorOnNoMatch GetBehaviorWhenNoMatchesFound(CmdletParameterMe { return BehaviorOnNoMatch.Default; } + if (cmdletParameterMetadata.ErrorOnNoMatch) { return BehaviorOnNoMatch.ReportErrors; @@ -1735,6 +1763,7 @@ private void GenerateQueryParametersProcessing( _objectInstanceType.FullName, _cmdletizationMetadata.Class.ClassName); } + inputObjectParameter.Attributes.Add(new PSTypeNameAttribute(psTypeNameOfInputObjectElements)); inputObjectParameter.Attributes.Add(new ValidateNotNullAttribute()); @@ -1757,6 +1786,7 @@ private void GenerateQueryParametersProcessing( {1} {2} {3} + param( {4}) @@ -1915,6 +1945,7 @@ private static void AddPassThruParameter(IDictionary } } } + if (instanceCmdletMetadata.Method.ReturnValue != null) { if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata != null) && @@ -1963,6 +1994,7 @@ private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdle { commandMetadata.DefaultParameterSetName = queryParameterSets.Single(); } + AddPassThruParameter(commonParameters, instanceCmdlet); MultiplyParameterSets(commonParameters, InstanceCommonParameterSetTemplate, queryParameterSets, methodParameterSets); MultiplyParameterSets(queryParameters, InstanceQueryParameterSetTemplate, commonParameterSets, methodParameterSets); @@ -2025,6 +2057,7 @@ private CommonCmdletMetadata GetGetCmdletMetadata() cmdletMetadata.Noun = _cmdletizationMetadata.Class.DefaultNoun; cmdletMetadata.Verb = VerbsCommon.Get; } + Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); return cmdletMetadata; } @@ -2051,6 +2084,7 @@ private void WriteGetCmdlet(TextWriter output) { commandMetadata.DefaultParameterSetName = getCmdletParameters.DefaultCmdletParameterSet; } + MultiplyParameterSets(commonParameters, InstanceCommonParameterSetTemplate, queryParameterSets, methodParameterSets); MultiplyParameterSets(queryParameters, InstanceQueryParameterSetTemplate, commonParameterSets, methodParameterSets); EnsureOrderOfPositionalParameters(commonParameters, queryParameters); @@ -2184,6 +2218,7 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet.Select(c => c.CmdletMetadata)); } } + if (_cmdletizationMetadata.Class.StaticCmdlets != null) { cmdletMetadatas = From 823c0576306735cfd0082e2f053798ad60eb0aff Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:59 -0800 Subject: [PATCH 47/81] Update other --- .../cimSupport/other/ciminstancetypeadapter.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index cb93eeef2e2..a6cdb880f62 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -235,6 +235,7 @@ private List GetInheritanceChain(CimInstance cimInstance) break; } } + return inheritanceChain; } @@ -370,6 +371,7 @@ public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object Dbg.Assert(paramType != null, "'default' case should only be used for well-defined CimType->DotNetType conversions"); break; } + valueToSet = Adapter.PropertySetAndMethodArgumentConvertTo( value, paramType, CultureInfo.InvariantCulture); } From 4c49c901c4b3eec59b0446162c3136197ae91a46 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:59 -0800 Subject: [PATCH 48/81] Update cim --- .../cmdletization/cim/WildcardPatternToCimQueryParser.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index e225e2c49c1..28786651989 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -84,6 +84,7 @@ protected override void AppendCharacterRangeToBracketExpression(char startOfChar startOfCharacterRange = (char)90; _needClientSideFiltering = true; } + if ((91 <= endOfCharacterRange) && (endOfCharacterRange <= 94)) { endOfCharacterRange = (char)95; @@ -98,6 +99,7 @@ protected override void AppendCharacterRangeToBracketExpression(char startOfChar startOfCharacterRange = (char)44; _needClientSideFiltering = true; } + if (endOfCharacterRange == 45) { endOfCharacterRange = (char)46; From 50d5500c211ec4402369f5eec89ca96c59086db7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:45:59 -0800 Subject: [PATCH 49/81] Update xml --- ...mdlets-over-objects.objectModel.autogen.cs | 110 ++++ ...lets-over-objects.xmlSerializer.autogen.cs | 585 ++++++++++++++++++ 2 files changed, 695 insertions(+) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs index d6f90a3c61d..43f0817c92c 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs @@ -47,6 +47,7 @@ public ClassMetadata Class { return this._classField; } + set { this._classField = value; @@ -61,6 +62,7 @@ public EnumMetadataEnum[] Enums { return this._enumsField; } + set { this._enumsField = value; @@ -99,6 +101,7 @@ public string Version { return this._versionField; } + set { this._versionField = value; @@ -112,6 +115,7 @@ public string DefaultNoun { return this._defaultNounField; } + set { this._defaultNounField = value; @@ -125,6 +129,7 @@ public ClassMetadataInstanceCmdlets InstanceCmdlets { return this._instanceCmdletsField; } + set { this._instanceCmdletsField = value; @@ -139,6 +144,7 @@ public StaticCmdletMetadata[] StaticCmdlets { return this._staticCmdletsField; } + set { this._staticCmdletsField = value; @@ -153,6 +159,7 @@ public ClassMetadataData[] CmdletAdapterPrivateData { return this._cmdletAdapterPrivateDataField; } + set { this._cmdletAdapterPrivateDataField = value; @@ -167,6 +174,7 @@ public string CmdletAdapter { return this._cmdletAdapterField; } + set { this._cmdletAdapterField = value; @@ -181,6 +189,7 @@ public string ClassName { return this._classNameField; } + set { this._classNameField = value; @@ -195,6 +204,7 @@ public string ClassVersion { return this._classVersionField; } + set { this._classVersionField = value; @@ -223,6 +233,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -236,6 +247,7 @@ public GetCmdletMetadata GetCmdlet { return this._getCmdletField; } + set { this._getCmdletField = value; @@ -250,6 +262,7 @@ public InstanceCmdletMetadata[] Cmdlet { return this._cmdletField; } + set { this._cmdletField = value; @@ -281,6 +294,7 @@ public PropertyMetadata[] QueryableProperties { return this._queryablePropertiesField; } + set { this._queryablePropertiesField = value; @@ -295,6 +309,7 @@ public Association[] QueryableAssociations { return this._queryableAssociationsField; } + set { this._queryableAssociationsField = value; @@ -309,6 +324,7 @@ public QueryOption[] QueryOptions { return this._queryOptionsField; } + set { this._queryOptionsField = value; @@ -323,6 +339,7 @@ public string DefaultCmdletParameterSet { return this._defaultCmdletParameterSetField; } + set { this._defaultCmdletParameterSetField = value; @@ -353,6 +370,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -371,6 +389,7 @@ public PropertyQuery[] Items { return this._itemsField; } + set { this._itemsField = value; @@ -386,6 +405,7 @@ public ItemsChoiceType[] ItemsElementName { return this._itemsElementNameField; } + set { this._itemsElementNameField = value; @@ -400,6 +420,7 @@ public string PropertyName { return this._propertyNameField; } + set { this._propertyNameField = value; @@ -427,6 +448,7 @@ public string PSType { return this._pSTypeField; } + set { this._pSTypeField = value; @@ -441,6 +463,7 @@ public string ETSType { return this._eTSTypeField; } + set { this._eTSTypeField = value; @@ -471,6 +494,7 @@ public AssociationAssociatedInstance AssociatedInstance { return this._associatedInstanceField; } + set { this._associatedInstanceField = value; @@ -485,6 +509,7 @@ public string Association1 { return this._association1Field; } + set { this._association1Field = value; @@ -499,6 +524,7 @@ public string SourceRole { return this._sourceRoleField; } + set { this._sourceRoleField = value; @@ -513,6 +539,7 @@ public string ResultRole { return this._resultRoleField; } + set { this._resultRoleField = value; @@ -539,6 +566,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -552,6 +580,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -579,6 +608,7 @@ public bool ErrorOnNoMatch { return this._errorOnNoMatchField; } + set { this._errorOnNoMatchField = value; @@ -593,6 +623,7 @@ public bool ErrorOnNoMatchSpecified { return this._errorOnNoMatchFieldSpecified; } + set { this._errorOnNoMatchFieldSpecified = value; @@ -627,6 +658,7 @@ public bool ValueFromPipeline { return this._valueFromPipelineField; } + set { this._valueFromPipelineField = value; @@ -641,6 +673,7 @@ public bool ValueFromPipelineSpecified { return this._valueFromPipelineFieldSpecified; } + set { this._valueFromPipelineFieldSpecified = value; @@ -655,6 +688,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -669,6 +703,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -683,6 +718,7 @@ public string[] CmdletParameterSets { return this._cmdletParameterSetsField; } + set { this._cmdletParameterSetsField = value; @@ -739,6 +775,7 @@ public object AllowEmptyCollection { return this._allowEmptyCollectionField; } + set { this._allowEmptyCollectionField = value; @@ -752,6 +789,7 @@ public object AllowEmptyString { return this._allowEmptyStringField; } + set { this._allowEmptyStringField = value; @@ -765,6 +803,7 @@ public object AllowNull { return this._allowNullField; } + set { this._allowNullField = value; @@ -778,6 +817,7 @@ public object ValidateNotNull { return this._validateNotNullField; } + set { this._validateNotNullField = value; @@ -791,6 +831,7 @@ public object ValidateNotNullOrEmpty { return this._validateNotNullOrEmptyField; } + set { this._validateNotNullOrEmptyField = value; @@ -804,6 +845,7 @@ public CmdletParameterMetadataValidateCount ValidateCount { return this._validateCountField; } + set { this._validateCountField = value; @@ -817,6 +859,7 @@ public CmdletParameterMetadataValidateLength ValidateLength { return this._validateLengthField; } + set { this._validateLengthField = value; @@ -830,6 +873,7 @@ public CmdletParameterMetadataValidateRange ValidateRange { return this._validateRangeField; } + set { this._validateRangeField = value; @@ -844,6 +888,7 @@ public string[] ValidateSet { return this._validateSetField; } + set { this._validateSetField = value; @@ -857,6 +902,7 @@ public ObsoleteAttributeMetadata Obsolete { return this._obsoleteField; } + set { this._obsoleteField = value; @@ -871,6 +917,7 @@ public bool IsMandatory { return this._isMandatoryField; } + set { this._isMandatoryField = value; @@ -885,6 +932,7 @@ public bool IsMandatorySpecified { return this._isMandatoryFieldSpecified; } + set { this._isMandatoryFieldSpecified = value; @@ -899,6 +947,7 @@ public string[] Aliases { return this._aliasesField; } + set { this._aliasesField = value; @@ -913,6 +962,7 @@ public string PSName { return this._pSNameField; } + set { this._pSNameField = value; @@ -927,6 +977,7 @@ public string Position { return this._positionField; } + set { this._positionField = value; @@ -954,6 +1005,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -968,6 +1020,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -995,6 +1048,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -1009,6 +1063,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -1036,6 +1091,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -1050,6 +1106,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -1075,6 +1132,7 @@ public string Message { return this._messageField; } + set { this._messageField = value; @@ -1102,6 +1160,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -1116,6 +1175,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -1147,6 +1207,7 @@ public bool ValueFromPipeline { return this._valueFromPipelineField; } + set { this._valueFromPipelineField = value; @@ -1161,6 +1222,7 @@ public bool ValueFromPipelineSpecified { return this._valueFromPipelineFieldSpecified; } + set { this._valueFromPipelineFieldSpecified = value; @@ -1175,6 +1237,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -1189,6 +1252,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -1217,6 +1281,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1230,6 +1295,7 @@ public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1244,6 +1310,7 @@ public string OptionName { return this._optionNameField; } + set { this._optionNameField = value; @@ -1270,6 +1337,7 @@ public CommonCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1283,6 +1351,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -1319,6 +1388,7 @@ public ObsoleteAttributeMetadata Obsolete { return this._obsoleteField; } + set { this._obsoleteField = value; @@ -1333,6 +1403,7 @@ public string Verb { return this._verbField; } + set { this._verbField = value; @@ -1347,6 +1418,7 @@ public string Noun { return this._nounField; } + set { this._nounField = value; @@ -1361,6 +1433,7 @@ public string[] Aliases { return this._aliasesField; } + set { this._aliasesField = value; @@ -1375,6 +1448,7 @@ public ConfirmImpact ConfirmImpact { return this._confirmImpactField; } + set { this._confirmImpactField = value; @@ -1389,6 +1463,7 @@ public bool ConfirmImpactSpecified { return this._confirmImpactFieldSpecified; } + set { this._confirmImpactFieldSpecified = value; @@ -1403,6 +1478,7 @@ public string HelpUri { return this._helpUriField; } + set { this._helpUriField = value; @@ -1448,6 +1524,7 @@ public StaticCmdletMetadataCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1462,6 +1539,7 @@ public StaticMethodMetadata[] Method { return this._methodField; } + set { this._methodField = value; @@ -1487,6 +1565,7 @@ public string DefaultCmdletParameterSet { return this._defaultCmdletParameterSetField; } + set { this._defaultCmdletParameterSetField = value; @@ -1514,6 +1593,7 @@ public StaticMethodParameterMetadata[] Parameters { return this._parametersField; } + set { this._parametersField = value; @@ -1528,6 +1608,7 @@ public string CmdletParameterSet { return this._cmdletParameterSetField; } + set { this._cmdletParameterSetField = value; @@ -1554,6 +1635,7 @@ public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1567,6 +1649,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1593,6 +1676,7 @@ public object ErrorCode { return this._errorCodeField; } + set { this._errorCodeField = value; @@ -1607,6 +1691,7 @@ public string PSName { return this._pSNameField; } + set { this._pSNameField = value; @@ -1637,6 +1722,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1651,6 +1737,7 @@ public string ParameterName { return this._parameterNameField; } + set { this._parameterNameField = value; @@ -1665,6 +1752,7 @@ public string DefaultValue { return this._defaultValueField; } + set { this._defaultValueField = value; @@ -1691,6 +1779,7 @@ public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1704,6 +1793,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1732,6 +1822,7 @@ public CommonMethodMetadataReturnValue ReturnValue { return this._returnValueField; } + set { this._returnValueField = value; @@ -1746,6 +1837,7 @@ public string MethodName { return this._methodNameField; } + set { this._methodNameField = value; @@ -1772,6 +1864,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1785,6 +1878,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1810,6 +1904,7 @@ public InstanceMethodParameterMetadata[] Parameters { return this._parametersField; } + set { this._parametersField = value; @@ -1838,6 +1933,7 @@ public CommonCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1851,6 +1947,7 @@ public InstanceMethodMetadata Method { return this._methodField; } + set { this._methodField = value; @@ -1864,6 +1961,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -1889,6 +1987,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1916,6 +2015,7 @@ public bool AllowGlobbing { return this._allowGlobbingField; } + set { this._allowGlobbingField = value; @@ -1930,6 +2030,7 @@ public bool AllowGlobbingSpecified { return this._allowGlobbingFieldSpecified; } + set { this._allowGlobbingFieldSpecified = value; @@ -1976,6 +2077,7 @@ public string Name { return this._nameField; } + set { this._nameField = value; @@ -1990,6 +2092,7 @@ public string Value { return this._valueField; } + set { this._valueField = value; @@ -2023,6 +2126,7 @@ public EnumMetadataEnumValue[] Value { return this._valueField; } + set { this._valueField = value; @@ -2037,6 +2141,7 @@ public string EnumName { return this._enumNameField; } + set { this._enumNameField = value; @@ -2051,6 +2156,7 @@ public string UnderlyingType { return this._underlyingTypeField; } + set { this._underlyingTypeField = value; @@ -2065,6 +2171,7 @@ public bool BitwiseFlags { return this._bitwiseFlagsField; } + set { this._bitwiseFlagsField = value; @@ -2079,6 +2186,7 @@ public bool BitwiseFlagsSpecified { return this._bitwiseFlagsFieldSpecified; } + set { this._bitwiseFlagsFieldSpecified = value; @@ -2106,6 +2214,7 @@ public string Name { return this._nameField; } + set { this._nameField = value; @@ -2120,6 +2229,7 @@ public string Value { return this._valueField; } + set { this._valueField = value; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs index a5dadac6e55..ce8053e7b0e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -26,6 +26,7 @@ public void Write50_PowerShellMetadata(object o) WriteEmptyTag(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); return; } + TopLevelElement(); Write39_PowerShellMetadata(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)o), false, false); } @@ -38,6 +39,7 @@ public void Write51_ClassMetadata(object o) WriteNullTagLiteral(@"ClassMetadata", string.Empty); return; } + TopLevelElement(); Write36_ClassMetadata(@"ClassMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o), true, false); } @@ -50,6 +52,7 @@ public void Write52_ClassMetadataInstanceCmdlets(object o) WriteNullTagLiteral(@"ClassMetadataInstanceCmdlets", string.Empty); return; } + TopLevelElement(); Write40_ClassMetadataInstanceCmdlets(@"ClassMetadataInstanceCmdlets", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o), true, false); } @@ -62,6 +65,7 @@ public void Write53_GetCmdletParameters(object o) WriteNullTagLiteral(@"GetCmdletParameters", string.Empty); return; } + TopLevelElement(); Write19_GetCmdletParameters(@"GetCmdletParameters", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o), true, false); } @@ -74,6 +78,7 @@ public void Write54_PropertyMetadata(object o) WriteNullTagLiteral(@"PropertyMetadata", string.Empty); return; } + TopLevelElement(); Write15_PropertyMetadata(@"PropertyMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o), true, false); } @@ -86,6 +91,7 @@ public void Write55_TypeMetadata(object o) WriteNullTagLiteral(@"TypeMetadata", string.Empty); return; } + TopLevelElement(); Write2_TypeMetadata(@"TypeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o), true, false); } @@ -98,6 +104,7 @@ public void Write56_Association(object o) WriteNullTagLiteral(@"Association", string.Empty); return; } + TopLevelElement(); Write17_Association(@"Association", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)o), true, false); } @@ -110,6 +117,7 @@ public void Write57_AssociationAssociatedInstance(object o) WriteNullTagLiteral(@"AssociationAssociatedInstance", string.Empty); return; } + TopLevelElement(); Write41_AssociationAssociatedInstance(@"AssociationAssociatedInstance", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o), true, false); } @@ -122,6 +130,7 @@ public void Write58_CmdletParameterMetadata(object o) WriteNullTagLiteral(@"CmdletParameterMetadata", string.Empty); return; } + TopLevelElement(); Write10_CmdletParameterMetadata(@"CmdletParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o), true, false); } @@ -134,6 +143,7 @@ public void Write59_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletParameter", string.Empty); return; } + TopLevelElement(); Write11_Item(@"CmdletParameterMetadataForGetCmdletParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o), true, false); } @@ -146,6 +156,7 @@ public void Write60_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletFilteringParameter", string.Empty); return; } + TopLevelElement(); Write12_Item(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o), true, false); } @@ -158,6 +169,7 @@ public void Write61_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataValidateCount", string.Empty); return; } + TopLevelElement(); Write42_Item(@"CmdletParameterMetadataValidateCount", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o), true, false); } @@ -170,6 +182,7 @@ public void Write62_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataValidateLength", string.Empty); return; } + TopLevelElement(); Write43_Item(@"CmdletParameterMetadataValidateLength", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o), true, false); } @@ -182,6 +195,7 @@ public void Write63_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataValidateRange", string.Empty); return; } + TopLevelElement(); Write44_Item(@"CmdletParameterMetadataValidateRange", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o), true, false); } @@ -194,6 +208,7 @@ public void Write64_ObsoleteAttributeMetadata(object o) WriteNullTagLiteral(@"ObsoleteAttributeMetadata", string.Empty); return; } + TopLevelElement(); Write7_ObsoleteAttributeMetadata(@"ObsoleteAttributeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o), true, false); } @@ -206,6 +221,7 @@ public void Write65_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataForInstanceMethodParameter", string.Empty); return; } + TopLevelElement(); Write9_Item(@"CmdletParameterMetadataForInstanceMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o), true, false); } @@ -218,6 +234,7 @@ public void Write66_Item(object o) WriteNullTagLiteral(@"CmdletParameterMetadataForStaticMethodParameter", string.Empty); return; } + TopLevelElement(); Write8_Item(@"CmdletParameterMetadataForStaticMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o), true, false); } @@ -230,6 +247,7 @@ public void Write67_QueryOption(object o) WriteNullTagLiteral(@"QueryOption", string.Empty); return; } + TopLevelElement(); Write18_QueryOption(@"QueryOption", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o), true, false); } @@ -242,6 +260,7 @@ public void Write68_GetCmdletMetadata(object o) WriteNullTagLiteral(@"GetCmdletMetadata", string.Empty); return; } + TopLevelElement(); Write22_GetCmdletMetadata(@"GetCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o), true, false); } @@ -254,6 +273,7 @@ public void Write69_CommonCmdletMetadata(object o) WriteNullTagLiteral(@"CommonCmdletMetadata", string.Empty); return; } + TopLevelElement(); Write21_CommonCmdletMetadata(@"CommonCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o), true, false); } @@ -266,6 +286,7 @@ public void Write70_ConfirmImpact(object o) WriteEmptyTag(@"ConfirmImpact", string.Empty); return; } + WriteElementString(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o))); } @@ -277,6 +298,7 @@ public void Write71_StaticCmdletMetadata(object o) WriteNullTagLiteral(@"StaticCmdletMetadata", string.Empty); return; } + TopLevelElement(); Write34_StaticCmdletMetadata(@"StaticCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o), true, false); } @@ -289,6 +311,7 @@ public void Write72_Item(object o) WriteNullTagLiteral(@"StaticCmdletMetadataCmdletMetadata", string.Empty); return; } + TopLevelElement(); Write45_Item(@"StaticCmdletMetadataCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o), true, false); } @@ -301,6 +324,7 @@ public void Write73_CommonMethodMetadata(object o) WriteNullTagLiteral(@"CommonMethodMetadata", string.Empty); return; } + TopLevelElement(); Write29_CommonMethodMetadata(@"CommonMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o), true, false); } @@ -313,6 +337,7 @@ public void Write74_StaticMethodMetadata(object o) WriteNullTagLiteral(@"StaticMethodMetadata", string.Empty); return; } + TopLevelElement(); Write28_StaticMethodMetadata(@"StaticMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o), true, false); } @@ -325,6 +350,7 @@ public void Write75_CommonMethodParameterMetadata(object o) WriteNullTagLiteral(@"CommonMethodParameterMetadata", string.Empty); return; } + TopLevelElement(); Write26_CommonMethodParameterMetadata(@"CommonMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o), true, false); } @@ -337,6 +363,7 @@ public void Write76_StaticMethodParameterMetadata(object o) WriteNullTagLiteral(@"StaticMethodParameterMetadata", string.Empty); return; } + TopLevelElement(); Write27_StaticMethodParameterMetadata(@"StaticMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o), true, false); } @@ -349,6 +376,7 @@ public void Write77_CmdletOutputMetadata(object o) WriteNullTagLiteral(@"CmdletOutputMetadata", string.Empty); return; } + TopLevelElement(); Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o), true, false); } @@ -361,6 +389,7 @@ public void Write78_Item(object o) WriteNullTagLiteral(@"InstanceMethodParameterMetadata", string.Empty); return; } + TopLevelElement(); Write25_Item(@"InstanceMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o), true, false); } @@ -373,6 +402,7 @@ public void Write79_Item(object o) WriteNullTagLiteral(@"CommonMethodMetadataReturnValue", string.Empty); return; } + TopLevelElement(); Write46_Item(@"CommonMethodMetadataReturnValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o), true, false); } @@ -385,6 +415,7 @@ public void Write80_InstanceMethodMetadata(object o) WriteNullTagLiteral(@"InstanceMethodMetadata", string.Empty); return; } + TopLevelElement(); Write30_InstanceMethodMetadata(@"InstanceMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o), true, false); } @@ -397,6 +428,7 @@ public void Write81_InstanceCmdletMetadata(object o) WriteNullTagLiteral(@"InstanceCmdletMetadata", string.Empty); return; } + TopLevelElement(); Write31_InstanceCmdletMetadata(@"InstanceCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o), true, false); } @@ -409,6 +441,7 @@ public void Write82_PropertyQuery(object o) WriteNullTagLiteral(@"PropertyQuery", string.Empty); return; } + TopLevelElement(); Write14_PropertyQuery(@"PropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o), true, false); } @@ -421,6 +454,7 @@ public void Write83_WildcardablePropertyQuery(object o) WriteNullTagLiteral(@"WildcardablePropertyQuery", string.Empty); return; } + TopLevelElement(); Write13_WildcardablePropertyQuery(@"WildcardablePropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o), true, false); } @@ -433,6 +467,7 @@ public void Write84_ItemsChoiceType(object o) WriteEmptyTag(@"ItemsChoiceType", string.Empty); return; } + WriteElementString(@"ItemsChoiceType", @"", Write3_ItemsChoiceType(((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o))); } @@ -444,6 +479,7 @@ public void Write85_ClassMetadataData(object o) WriteNullTagLiteral(@"ClassMetadataData", string.Empty); return; } + TopLevelElement(); Write47_ClassMetadataData(@"ClassMetadataData", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o), true, false); } @@ -456,6 +492,7 @@ public void Write86_EnumMetadataEnum(object o) WriteNullTagLiteral(@"EnumMetadataEnum", string.Empty); return; } + TopLevelElement(); Write48_EnumMetadataEnum(@"EnumMetadataEnum", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o), true, false); } @@ -468,6 +505,7 @@ public void Write87_EnumMetadataEnumValue(object o) WriteNullTagLiteral(@"EnumMetadataEnumValue", string.Empty); return; } + TopLevelElement(); Write49_EnumMetadataEnumValue(@"EnumMetadataEnumValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o), true, false); } @@ -479,6 +517,7 @@ private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsof if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -490,6 +529,7 @@ private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsof throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"EnumMetadataEnumValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); @@ -504,6 +544,7 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -515,6 +556,7 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"EnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); @@ -533,9 +575,11 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow } } } + if (o.@BitwiseFlagsSpecified) { } + WriteEndElement(o); } @@ -546,6 +590,7 @@ private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsof if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -557,6 +602,7 @@ private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsof throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); @@ -571,6 +617,7 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -582,6 +629,7 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); @@ -589,6 +637,7 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po { WriteValue(((global::System.String)o.@Value)); } + WriteEndElement(o); } @@ -603,6 +652,7 @@ private string Write3_ItemsChoiceType(global::Microsoft.PowerShell.Cmdletization case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery: s = @"RegularQuery"; break; default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType"); } + return s; } @@ -613,6 +663,7 @@ private void Write13_WildcardablePropertyQuery(string n, string ns, global::Micr if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -624,16 +675,19 @@ private void Write13_WildcardablePropertyQuery(string n, string ns, global::Micr throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"WildcardablePropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@AllowGlobbingSpecified) { WriteAttribute(@"AllowGlobbing", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@AllowGlobbing))); } + Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); if (o.@AllowGlobbingSpecified) { } + WriteEndElement(o); } @@ -644,6 +698,7 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -655,6 +710,7 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@IsMandatorySpecified) @@ -672,15 +728,18 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); if (o.@ValueFromPipelineSpecified) { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } + if (o.@ValueFromPipelineByPropertyNameSpecified) { WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); @@ -696,13 +755,16 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + if (o.@ErrorOnNoMatchSpecified) { WriteAttribute(@"ErrorOnNoMatch", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ErrorOnNoMatch))); } + Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); @@ -720,22 +782,28 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl { WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); } + WriteEndElement(); } } + Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@IsMandatorySpecified) { } + if (o.@ValueFromPipelineSpecified) { } + if (o.@ValueFromPipelineByPropertyNameSpecified) { } + if (o.@ErrorOnNoMatchSpecified) { } + WriteEndElement(o); } @@ -746,6 +814,7 @@ private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Micro if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -757,6 +826,7 @@ private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Micro throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"ObsoleteAttributeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Message", @"", ((global::System.String)o.@Message)); @@ -770,6 +840,7 @@ private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -781,6 +852,7 @@ private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -795,6 +867,7 @@ private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -806,6 +879,7 @@ private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -820,6 +894,7 @@ private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -831,6 +906,7 @@ private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -845,6 +921,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1048,6 +1125,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1065,6 +1143,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1082,6 +1161,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1099,6 +1179,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1124,6 +1205,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1141,6 +1223,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1158,6 +1241,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1175,6 +1259,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1192,6 +1277,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is } } } + Writer.WriteEndElement(); return; } @@ -1201,6 +1287,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is return; } } + WriteStartElement(n, ns, o, false, null); WriteEndElement(o); } @@ -1212,6 +1299,7 @@ private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1223,6 +1311,7 @@ private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); @@ -1241,9 +1330,11 @@ private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow } } } + if (o.@BitwiseFlagsSpecified) { } + WriteEndElement(o); } @@ -1254,6 +1345,7 @@ private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.Po if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1265,6 +1357,7 @@ private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.Po throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); @@ -1272,6 +1365,7 @@ private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.Po { WriteValue(((global::System.String)o.@Value)); } + WriteEndElement(o); } @@ -1282,6 +1376,7 @@ private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1293,6 +1388,7 @@ private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"StaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write33_Item(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o.@CmdletMetadata), false, false); @@ -1306,6 +1402,7 @@ private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft } } } + WriteEndElement(o); } @@ -1316,6 +1413,7 @@ private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1327,6 +1425,7 @@ private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"StaticMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); @@ -1341,9 +1440,11 @@ private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft { Write27_StaticMethodParameterMetadata(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)a[ia]), false, false); } + WriteEndElement(); } } + WriteEndElement(o); } @@ -1354,6 +1455,7 @@ private void Write27_StaticMethodParameterMetadata(string n, string ns, global:: if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1365,6 +1467,7 @@ private void Write27_StaticMethodParameterMetadata(string n, string ns, global:: throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"StaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); @@ -1382,6 +1485,7 @@ private void Write23_CmdletOutputMetadata(string n, string ns, global::Microsoft if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1393,6 +1497,7 @@ private void Write23_CmdletOutputMetadata(string n, string ns, global::Microsoft throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); @@ -1407,6 +1512,7 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1418,6 +1524,7 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataForStaticMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@IsMandatorySpecified) @@ -1435,19 +1542,23 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); if (o.@ValueFromPipelineSpecified) { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } + if (o.@ValueFromPipelineByPropertyNameSpecified) { WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); } + Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); @@ -1465,19 +1576,24 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle { WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); } + WriteEndElement(); } } + Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@IsMandatorySpecified) { } + if (o.@ValueFromPipelineSpecified) { } + if (o.@ValueFromPipelineByPropertyNameSpecified) { } + WriteEndElement(o); } @@ -1488,6 +1604,7 @@ private void Write2_TypeMetadata(string n, string ns, global::Microsoft.PowerShe if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1499,6 +1616,7 @@ private void Write2_TypeMetadata(string n, string ns, global::Microsoft.PowerShe throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"TypeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"PSType", @"", ((global::System.String)o.@PSType)); @@ -1513,6 +1631,7 @@ private void Write24_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1524,6 +1643,7 @@ private void Write24_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); @@ -1538,6 +1658,7 @@ private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1549,6 +1670,7 @@ private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); @@ -1564,19 +1686,23 @@ private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + if (o.@ConfirmImpactSpecified) { WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); } + WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@ConfirmImpactSpecified) { } + WriteEndElement(o); } @@ -1591,6 +1717,7 @@ private string Write20_ConfirmImpact(global::Microsoft.PowerShell.Cmdletization. case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@High: s = @"High"; break; default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact"); } + return s; } @@ -1601,6 +1728,7 @@ private void Write25_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1612,6 +1740,7 @@ private void Write25_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"InstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); @@ -1629,6 +1758,7 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1640,6 +1770,7 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataForInstanceMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@IsMandatorySpecified) @@ -1657,15 +1788,18 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); if (o.@ValueFromPipelineByPropertyNameSpecified) { WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); } + Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); @@ -1683,16 +1817,20 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle { WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); } + WriteEndElement(); } } + Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@IsMandatorySpecified) { } + if (o.@ValueFromPipelineByPropertyNameSpecified) { } + WriteEndElement(o); } @@ -1703,6 +1841,7 @@ private void Write18_QueryOption(string n, string ns, global::Microsoft.PowerShe if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1714,6 +1853,7 @@ private void Write18_QueryOption(string n, string ns, global::Microsoft.PowerShe throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"QueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"OptionName", @"", ((global::System.String)o.@OptionName)); @@ -1729,6 +1869,7 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1745,6 +1886,7 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@IsMandatorySpecified) @@ -1762,15 +1904,18 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); if (o.@ValueFromPipelineSpecified) { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } + if (o.@ValueFromPipelineByPropertyNameSpecified) { WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); @@ -1786,9 +1931,11 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); @@ -1806,19 +1953,24 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl { WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); } + WriteEndElement(); } } + Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@IsMandatorySpecified) { } + if (o.@ValueFromPipelineSpecified) { } + if (o.@ValueFromPipelineByPropertyNameSpecified) { } + WriteEndElement(o); } @@ -1829,6 +1981,7 @@ private void Write17_Association(string n, string ns, global::Microsoft.PowerShe if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1840,6 +1993,7 @@ private void Write17_Association(string n, string ns, global::Microsoft.PowerShe throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Association", @"", ((global::System.String)o.@Association1)); @@ -1856,6 +2010,7 @@ private void Write16_AssociationAssociatedInstance(string n, string ns, global:: if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1867,6 +2022,7 @@ private void Write16_AssociationAssociatedInstance(string n, string ns, global:: throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); @@ -1881,6 +2037,7 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1892,6 +2049,7 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"PropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"PropertyName", @"", ((global::System.String)o.@PropertyName)); @@ -1905,6 +2063,7 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow { throw CreateInvalidChoiceIdentifierValueException(@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType", @"ItemsElementName"); } + for (int ia = 0; ia < a.Length; ia++) { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery ai = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)a[ia]; @@ -1938,6 +2097,7 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow } } } + WriteEndElement(o); } @@ -1948,6 +2108,7 @@ private void Write14_PropertyQuery(string n, string ns, global::Microsoft.PowerS if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -1964,6 +2125,7 @@ private void Write14_PropertyQuery(string n, string ns, global::Microsoft.PowerS throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"PropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); @@ -1977,6 +2139,7 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2008,6 +2171,7 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); if (o.@IsMandatorySpecified) @@ -2025,9 +2189,11 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); @@ -2047,13 +2213,16 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros { WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); } + WriteEndElement(); } } + Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@IsMandatorySpecified) { } + WriteEndElement(o); } @@ -2064,6 +2233,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2075,6 +2245,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); @@ -2087,6 +2258,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. { Write15_PropertyMetadata(@"Property", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)a[ia]), false, false); } + WriteEndElement(); } } @@ -2099,6 +2271,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. { Write17_Association(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)a[ia]), false, false); } + WriteEndElement(); } } @@ -2111,9 +2284,11 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. { Write18_QueryOption(@"Option", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)a[ia]), false, false); } + WriteEndElement(); } } + WriteEndElement(o); } @@ -2124,6 +2299,7 @@ private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2135,6 +2311,7 @@ private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"StaticCmdletMetadataCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); @@ -2150,19 +2327,23 @@ private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + if (o.@ConfirmImpactSpecified) { WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); } + WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@ConfirmImpactSpecified) { } + WriteEndElement(o); } @@ -2173,6 +2354,7 @@ private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2189,6 +2371,7 @@ private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CommonCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); @@ -2204,18 +2387,22 @@ private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft if (i != 0) Writer.WriteString(" "); WriteValue(ai); } + Writer.WriteEndAttribute(); } } + if (o.@ConfirmImpactSpecified) { WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); } + WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); if (o.@ConfirmImpactSpecified) { } + WriteEndElement(o); } @@ -2226,6 +2413,7 @@ private void Write22_GetCmdletMetadata(string n, string ns, global::Microsoft.Po if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2237,6 +2425,7 @@ private void Write22_GetCmdletMetadata(string n, string ns, global::Microsoft.Po throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"GetCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); @@ -2251,6 +2440,7 @@ private void Write30_InstanceMethodMetadata(string n, string ns, global::Microso if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2262,6 +2452,7 @@ private void Write30_InstanceMethodMetadata(string n, string ns, global::Microso throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"InstanceMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); @@ -2275,9 +2466,11 @@ private void Write30_InstanceMethodMetadata(string n, string ns, global::Microso { Write25_Item(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)a[ia]), false, false); } + WriteEndElement(); } } + WriteEndElement(o); } @@ -2288,6 +2481,7 @@ private void Write29_CommonMethodMetadata(string n, string ns, global::Microsoft if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2309,6 +2503,7 @@ private void Write29_CommonMethodMetadata(string n, string ns, global::Microsoft throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CommonMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); @@ -2323,6 +2518,7 @@ private void Write26_CommonMethodParameterMetadata(string n, string ns, global:: if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2344,6 +2540,7 @@ private void Write26_CommonMethodParameterMetadata(string n, string ns, global:: throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CommonMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); @@ -2359,6 +2556,7 @@ private void Write31_InstanceCmdletMetadata(string n, string ns, global::Microso if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2370,6 +2568,7 @@ private void Write31_InstanceCmdletMetadata(string n, string ns, global::Microso throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"InstanceCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); @@ -2385,6 +2584,7 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2396,6 +2596,7 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"ClassMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"CmdletAdapter", @"", ((global::System.String)o.@CmdletAdapter)); @@ -2413,6 +2614,7 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS { Write34_StaticCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)a[ia]), false, false); } + WriteEndElement(); } } @@ -2425,9 +2627,11 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS { Write35_ClassMetadataData(@"Data", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)a[ia]), false, false); } + WriteEndElement(); } } + WriteEndElement(o); } @@ -2438,6 +2642,7 @@ private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::M if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2449,6 +2654,7 @@ private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::M throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); @@ -2463,6 +2669,7 @@ private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::M } } } + WriteEndElement(o); } @@ -2473,6 +2680,7 @@ private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::M if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2484,6 +2692,7 @@ private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::M throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"ClassMetadataInstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); @@ -2498,6 +2707,7 @@ private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::M } } } + WriteEndElement(o); } @@ -2508,6 +2718,7 @@ private void Write41_AssociationAssociatedInstance(string n, string ns, global:: if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2519,6 +2730,7 @@ private void Write41_AssociationAssociatedInstance(string n, string ns, global:: throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"AssociationAssociatedInstance", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); @@ -2533,6 +2745,7 @@ private void Write42_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2544,6 +2757,7 @@ private void Write42_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -2558,6 +2772,7 @@ private void Write43_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2569,6 +2784,7 @@ private void Write43_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -2583,6 +2799,7 @@ private void Write44_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2594,6 +2811,7 @@ private void Write44_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CmdletParameterMetadataValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); @@ -2608,6 +2826,7 @@ private void Write46_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2619,6 +2838,7 @@ private void Write46_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"CommonMethodMetadataReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); @@ -2633,6 +2853,7 @@ private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.P if (isNullable) WriteNullTagLiteral(n, ns); return; } + if (!needType) { System.Type t = o.GetType(); @@ -2644,6 +2865,7 @@ private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.P throw CreateUnknownTypeException(o); } } + WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); Write36_ClassMetadata(@"Class", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o.@Class), false, false); @@ -2656,9 +2878,11 @@ private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.P { Write38_EnumMetadataEnum(@"Enum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)a[ia]), false, false); } + WriteEndElement(); } } + WriteEndElement(o); } @@ -2689,6 +2913,7 @@ public object Read50_PowerShellMetadata() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); } + return (object)o; } @@ -2711,6 +2936,7 @@ public object Read51_ClassMetadata() { UnknownNode(null, @":ClassMetadata"); } + return (object)o; } @@ -2733,6 +2959,7 @@ public object Read52_ClassMetadataInstanceCmdlets() { UnknownNode(null, @":ClassMetadataInstanceCmdlets"); } + return (object)o; } @@ -2755,6 +2982,7 @@ public object Read53_GetCmdletParameters() { UnknownNode(null, @":GetCmdletParameters"); } + return (object)o; } @@ -2777,6 +3005,7 @@ public object Read54_PropertyMetadata() { UnknownNode(null, @":PropertyMetadata"); } + return (object)o; } @@ -2799,6 +3028,7 @@ public object Read55_TypeMetadata() { UnknownNode(null, @":TypeMetadata"); } + return (object)o; } @@ -2821,6 +3051,7 @@ public object Read56_Association() { UnknownNode(null, @":Association"); } + return (object)o; } @@ -2843,6 +3074,7 @@ public object Read57_AssociationAssociatedInstance() { UnknownNode(null, @":AssociationAssociatedInstance"); } + return (object)o; } @@ -2865,6 +3097,7 @@ public object Read58_CmdletParameterMetadata() { UnknownNode(null, @":CmdletParameterMetadata"); } + return (object)o; } @@ -2887,6 +3120,7 @@ public object Read59_Item() { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); } + return (object)o; } @@ -2909,6 +3143,7 @@ public object Read60_Item() { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); } + return (object)o; } @@ -2931,6 +3166,7 @@ public object Read61_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateCount"); } + return (object)o; } @@ -2953,6 +3189,7 @@ public object Read62_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateLength"); } + return (object)o; } @@ -2975,6 +3212,7 @@ public object Read63_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateRange"); } + return (object)o; } @@ -2997,6 +3235,7 @@ public object Read64_ObsoleteAttributeMetadata() { UnknownNode(null, @":ObsoleteAttributeMetadata"); } + return (object)o; } @@ -3019,6 +3258,7 @@ public object Read65_Item() { UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); } + return (object)o; } @@ -3041,6 +3281,7 @@ public object Read66_Item() { UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); } + return (object)o; } @@ -3063,6 +3304,7 @@ public object Read67_QueryOption() { UnknownNode(null, @":QueryOption"); } + return (object)o; } @@ -3085,6 +3327,7 @@ public object Read68_GetCmdletMetadata() { UnknownNode(null, @":GetCmdletMetadata"); } + return (object)o; } @@ -3107,6 +3350,7 @@ public object Read69_CommonCmdletMetadata() { UnknownNode(null, @":CommonCmdletMetadata"); } + return (object)o; } @@ -3131,6 +3375,7 @@ public object Read70_ConfirmImpact() { UnknownNode(null, @":ConfirmImpact"); } + return (object)o; } @@ -3153,6 +3398,7 @@ public object Read71_StaticCmdletMetadata() { UnknownNode(null, @":StaticCmdletMetadata"); } + return (object)o; } @@ -3175,6 +3421,7 @@ public object Read72_Item() { UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); } + return (object)o; } @@ -3197,6 +3444,7 @@ public object Read73_CommonMethodMetadata() { UnknownNode(null, @":CommonMethodMetadata"); } + return (object)o; } @@ -3219,6 +3467,7 @@ public object Read74_StaticMethodMetadata() { UnknownNode(null, @":StaticMethodMetadata"); } + return (object)o; } @@ -3241,6 +3490,7 @@ public object Read75_CommonMethodParameterMetadata() { UnknownNode(null, @":CommonMethodParameterMetadata"); } + return (object)o; } @@ -3263,6 +3513,7 @@ public object Read76_StaticMethodParameterMetadata() { UnknownNode(null, @":StaticMethodParameterMetadata"); } + return (object)o; } @@ -3285,6 +3536,7 @@ public object Read77_CmdletOutputMetadata() { UnknownNode(null, @":CmdletOutputMetadata"); } + return (object)o; } @@ -3307,6 +3559,7 @@ public object Read78_Item() { UnknownNode(null, @":InstanceMethodParameterMetadata"); } + return (object)o; } @@ -3329,6 +3582,7 @@ public object Read79_Item() { UnknownNode(null, @":CommonMethodMetadataReturnValue"); } + return (object)o; } @@ -3351,6 +3605,7 @@ public object Read80_InstanceMethodMetadata() { UnknownNode(null, @":InstanceMethodMetadata"); } + return (object)o; } @@ -3373,6 +3628,7 @@ public object Read81_InstanceCmdletMetadata() { UnknownNode(null, @":InstanceCmdletMetadata"); } + return (object)o; } @@ -3395,6 +3651,7 @@ public object Read82_PropertyQuery() { UnknownNode(null, @":PropertyQuery"); } + return (object)o; } @@ -3417,6 +3674,7 @@ public object Read83_WildcardablePropertyQuery() { UnknownNode(null, @":WildcardablePropertyQuery"); } + return (object)o; } @@ -3441,6 +3699,7 @@ public object Read84_ItemsChoiceType() { UnknownNode(null, @":ItemsChoiceType"); } + return (object)o; } @@ -3463,6 +3722,7 @@ public object Read85_ClassMetadataData() { UnknownNode(null, @":ClassMetadataData"); } + return (object)o; } @@ -3485,6 +3745,7 @@ public object Read86_EnumMetadataEnum() { UnknownNode(null, @":EnumMetadataEnum"); } + return (object)o; } @@ -3507,6 +3768,7 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @":EnumMetadataEnumValue"); } + return (object)o; } @@ -3523,6 +3785,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); @@ -3544,12 +3807,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name, :Value"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations0 = 0; @@ -3564,9 +3829,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations0, ref readerCount0); } + ReadEndElement(); return o; } @@ -3584,6 +3851,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); @@ -3613,6 +3881,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3620,6 +3889,7 @@ public object Read87_EnumMetadataEnumValue() o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations1 = 0; @@ -3641,9 +3911,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations1, ref readerCount1); } + o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); ReadEndElement(); return o; @@ -3662,6 +3934,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); @@ -3683,12 +3956,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name, :Value"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations2 = 0; @@ -3703,9 +3978,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations2, ref readerCount2); } + ReadEndElement(); return o; } @@ -3723,6 +4000,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); @@ -3739,12 +4017,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations3 = 0; @@ -3768,9 +4048,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations3, ref readerCount3); } + ReadEndElement(); return o; } @@ -3800,6 +4082,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery(); @@ -3817,12 +4100,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":AllowGlobbing"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations4 = 0; @@ -3845,9 +4130,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations4, ref readerCount4); } + ReadEndElement(); return o; } @@ -3865,6 +4152,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter(); @@ -3934,6 +4222,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3942,6 +4231,7 @@ public object Read87_EnumMetadataEnumValue() o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations5 = 0; @@ -4025,11 +4315,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations6, ref readerCount6); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -4047,9 +4340,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations5, ref readerCount5); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); ReadEndElement(); @@ -4069,6 +4364,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata(); @@ -4085,12 +4381,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Message"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations7 = 0; @@ -4105,9 +4403,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations7, ref readerCount7); } + ReadEndElement(); return o; } @@ -4125,6 +4425,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); @@ -4146,12 +4447,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations8 = 0; @@ -4166,9 +4469,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations8, ref readerCount8); } + ReadEndElement(); return o; } @@ -4186,6 +4491,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); @@ -4207,12 +4513,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations9 = 0; @@ -4227,9 +4535,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations9, ref readerCount9); } + ReadEndElement(); return o; } @@ -4247,6 +4557,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); @@ -4268,12 +4579,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations10 = 0; @@ -4288,9 +4601,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations10, ref readerCount10); } + ReadEndElement(); return o; } @@ -4307,6 +4622,7 @@ public object Read87_EnumMetadataEnumValue() if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } + if (xsiType == null) { return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); @@ -4424,13 +4740,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations11, ref readerCount11); } + ReadEndElement(); } + a = (global::System.String[])ShrinkArray(z_0_0, cz_0_0, typeof(global::System.String), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id70_ArrayOfPropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4467,13 +4787,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations12, ref readerCount12); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id72_ArrayOfAssociation && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4510,13 +4834,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations13, ref readerCount13); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id73_ArrayOfQueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4553,13 +4881,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations14, ref readerCount14); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id23_ConfirmImpact && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4603,13 +4935,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations15, ref readerCount15); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id77_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4646,13 +4982,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations16, ref readerCount16); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id78_ArrayOfStaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4689,13 +5029,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations17, ref readerCount17); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id80_ArrayOfClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4732,13 +5076,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations18, ref readerCount18); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id82_ArrayOfEnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4775,18 +5123,23 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations19, ref readerCount19); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } + return a; } else return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::System.Object o; o = new global::System.Object(); @@ -4798,12 +5151,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations20 = 0; @@ -4818,9 +5173,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations20, ref readerCount20); } + ReadEndElement(); return o; } @@ -4838,6 +5195,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); @@ -4867,6 +5225,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -4874,6 +5233,7 @@ public object Read87_EnumMetadataEnumValue() o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations21 = 0; @@ -4895,9 +5255,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations21, ref readerCount21); } + o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); ReadEndElement(); return o; @@ -4916,6 +5278,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); @@ -4932,12 +5295,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations22 = 0; @@ -4961,9 +5326,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations22, ref readerCount22); } + ReadEndElement(); return o; } @@ -4981,6 +5348,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata(); @@ -4994,6 +5362,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5001,6 +5370,7 @@ public object Read87_EnumMetadataEnumValue() o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations23 = 0; @@ -5027,9 +5397,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations23, ref readerCount23); } + o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); ReadEndElement(); return o; @@ -5048,6 +5420,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata(); @@ -5071,12 +5444,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations24 = 0; @@ -5123,11 +5498,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations25, ref readerCount25); } + ReadEndElement(); } + o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); } } @@ -5140,9 +5518,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations24, ref readerCount24); } + ReadEndElement(); return o; } @@ -5160,6 +5540,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata(); @@ -5181,12 +5562,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations26 = 0; @@ -5219,9 +5602,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations26, ref readerCount26); } + ReadEndElement(); return o; } @@ -5239,6 +5624,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata(); @@ -5255,12 +5641,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PSName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations27 = 0; @@ -5283,9 +5671,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations27, ref readerCount27); } + ReadEndElement(); return o; } @@ -5303,6 +5693,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter(); @@ -5355,6 +5746,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5362,6 +5754,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations28 = 0; @@ -5445,11 +5838,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations29, ref readerCount29); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -5467,9 +5863,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations28, ref readerCount28); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -5488,6 +5886,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata(); @@ -5509,12 +5908,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PSType, :ETSType"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations30 = 0; @@ -5529,9 +5930,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations30, ref readerCount30); } + ReadEndElement(); return o; } @@ -5549,6 +5952,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); @@ -5560,12 +5964,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations31 = 0; @@ -5593,9 +5999,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations31, ref readerCount31); } + ReadEndElement(); return o; } @@ -5613,6 +6021,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); @@ -5661,6 +6070,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5668,6 +6078,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations32 = 0; @@ -5690,9 +6101,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations32, ref readerCount32); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -5723,6 +6136,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata(); @@ -5744,12 +6158,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations33 = 0; @@ -5782,9 +6198,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations33, ref readerCount33); } + ReadEndElement(); return o; } @@ -5802,6 +6220,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter(); @@ -5848,6 +6267,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipelineByPropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5855,6 +6275,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations34 = 0; @@ -5938,11 +6359,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations35, ref readerCount35); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -5960,9 +6384,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations34, ref readerCount34); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -5981,6 +6407,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption(); @@ -5997,12 +6424,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":OptionName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations36 = 0; @@ -6030,9 +6459,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations36, ref readerCount36); } + ReadEndElement(); return o; } @@ -6052,6 +6483,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter(); @@ -6115,6 +6547,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -6123,6 +6556,7 @@ public object Read87_EnumMetadataEnumValue() o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations37 = 0; @@ -6206,11 +6640,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations38, ref readerCount38); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -6228,9 +6665,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations37, ref readerCount37); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); ReadEndElement(); @@ -6250,6 +6689,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.Association o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.Association(); @@ -6276,12 +6716,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Association, :SourceRole, :ResultRole"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations39 = 0; @@ -6304,9 +6746,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations39, ref readerCount39); } + ReadEndElement(); return o; } @@ -6324,6 +6768,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); @@ -6335,12 +6780,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations40 = 0; @@ -6368,9 +6815,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations40, ref readerCount40); } + ReadEndElement(); return o; } @@ -6388,6 +6837,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata(); @@ -6408,6 +6858,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -6416,6 +6867,7 @@ public object Read87_EnumMetadataEnumValue() o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations41 = 0; @@ -6458,9 +6910,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations41, ref readerCount41); } + o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); ReadEndElement(); @@ -6482,6 +6936,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery(); @@ -6493,12 +6948,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations42 = 0; @@ -6521,9 +6978,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations42, ref readerCount42); } + ReadEndElement(); return o; } @@ -6549,6 +7008,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata(); @@ -6589,6 +7049,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -6596,6 +7057,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations43 = 0; @@ -6679,11 +7141,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations44, ref readerCount44); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -6701,9 +7166,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations43, ref readerCount43); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -6722,6 +7189,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters(); @@ -6744,12 +7212,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations45 = 0; @@ -6791,11 +7261,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations46, ref readerCount46); } + ReadEndElement(); } + o.@QueryableProperties = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); } } @@ -6832,11 +7305,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations47, ref readerCount47); } + ReadEndElement(); } + o.@QueryableAssociations = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); } } @@ -6873,11 +7349,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations48, ref readerCount48); } + ReadEndElement(); } + o.@QueryOptions = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); } } @@ -6890,9 +7369,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations45, ref readerCount45); } + ReadEndElement(); return o; } @@ -6910,6 +7391,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); @@ -6958,6 +7440,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -6965,6 +7448,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations49 = 0; @@ -6987,9 +7471,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations49, ref readerCount49); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -7010,6 +7496,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata(); @@ -7053,6 +7540,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -7060,6 +7548,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations50 = 0; @@ -7082,9 +7571,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations50, ref readerCount50); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -7103,6 +7594,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata(); @@ -7114,12 +7606,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations51 = 0; @@ -7147,9 +7641,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations51, ref readerCount51); } + ReadEndElement(); return o; } @@ -7167,6 +7663,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata(); @@ -7185,12 +7682,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations52 = 0; @@ -7237,11 +7736,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations53, ref readerCount53); } + ReadEndElement(); } + o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); } } @@ -7254,9 +7756,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations52, ref readerCount52); } + ReadEndElement(); return o; } @@ -7278,6 +7782,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata(); @@ -7294,12 +7799,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations54 = 0; @@ -7322,9 +7829,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations54, ref readerCount54); } + ReadEndElement(); return o; } @@ -7346,6 +7855,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata(); @@ -7367,12 +7877,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations55 = 0; @@ -7395,9 +7907,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations55, ref readerCount55); } + ReadEndElement(); return o; } @@ -7415,6 +7929,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata(); @@ -7426,12 +7941,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations56 = 0; @@ -7464,9 +7981,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations56, ref readerCount56); } + ReadEndElement(); return o; } @@ -7484,6 +8003,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata(); @@ -7514,12 +8034,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":CmdletAdapter, :ClassName, :ClassVersion"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations57 = 0; @@ -7533,6 +8055,7 @@ public object Read87_EnumMetadataEnumValue() { o.@Version = Reader.ReadElementString(); } + paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id116_DefaultNoun && (object)Reader.NamespaceURI == (object)_id2_Item)) @@ -7540,6 +8063,7 @@ public object Read87_EnumMetadataEnumValue() { o.@DefaultNoun = Reader.ReadElementString(); } + paramsRead[1] = true; } else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id117_InstanceCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) @@ -7580,11 +8104,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations58, ref readerCount58); } + ReadEndElement(); } + o.@StaticCmdlets = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); } } @@ -7621,11 +8148,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations59, ref readerCount59); } + ReadEndElement(); } + o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); } } @@ -7638,9 +8168,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations57, ref readerCount57); } + ReadEndElement(); return o; } @@ -7658,6 +8190,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); @@ -7671,6 +8204,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -7678,6 +8212,7 @@ public object Read87_EnumMetadataEnumValue() o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations60 = 0; @@ -7709,9 +8244,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations60, ref readerCount60); } + o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); ReadEndElement(); return o; @@ -7730,6 +8267,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); @@ -7743,6 +8281,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -7750,6 +8289,7 @@ public object Read87_EnumMetadataEnumValue() o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations61 = 0; @@ -7781,9 +8321,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations61, ref readerCount61); } + o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); ReadEndElement(); return o; @@ -7802,6 +8344,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); @@ -7813,12 +8356,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations62 = 0; @@ -7846,9 +8391,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations62, ref readerCount62); } + ReadEndElement(); return o; } @@ -7866,6 +8413,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); @@ -7887,12 +8435,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations63 = 0; @@ -7907,9 +8457,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations63, ref readerCount63); } + ReadEndElement(); return o; } @@ -7927,6 +8479,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); @@ -7948,12 +8501,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations64 = 0; @@ -7968,9 +8523,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations64, ref readerCount64); } + ReadEndElement(); return o; } @@ -7988,6 +8545,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); @@ -8009,12 +8567,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations65 = 0; @@ -8029,9 +8589,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations65, ref readerCount65); } + ReadEndElement(); return o; } @@ -8049,6 +8611,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); @@ -8060,12 +8623,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations66 = 0; @@ -8093,9 +8658,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations66, ref readerCount66); } + ReadEndElement(); return o; } @@ -8113,6 +8680,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata(); @@ -8126,12 +8694,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations67 = 0; @@ -8178,11 +8748,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations68, ref readerCount68); } + ReadEndElement(); } + o.@Enums = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } } @@ -8195,9 +8768,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations67, ref readerCount67); } + ReadEndElement(); return o; } @@ -8463,6 +9038,7 @@ protected override System.Xml.Serialization.XmlSerializationReader CreateReader( { return new XmlSerializationReader1(); } + protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter() { return new XmlSerializationWriter1(); @@ -9195,7 +9771,9 @@ protected override object Deserialize(System.Xml.Serialization.XmlSerializationR internal class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation { public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReader1(); } } + public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriter1(); } } + private System.Collections.Hashtable _readMethods = null; public override System.Collections.Hashtable ReadMethods { @@ -9244,9 +9822,11 @@ public override System.Collections.Hashtable ReadMethods _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Read87_EnumMetadataEnumValue"; if (_readMethods == null) _readMethods = _tmp; } + return _readMethods; } } + private System.Collections.Hashtable _writeMethods = null; public override System.Collections.Hashtable WriteMethods { @@ -9295,9 +9875,11 @@ public override System.Collections.Hashtable WriteMethods _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Write87_EnumMetadataEnumValue"; if (_writeMethods == null) _writeMethods = _tmp; } + return _writeMethods; } } + private System.Collections.Hashtable _typedSerializers = null; public override System.Collections.Hashtable TypedSerializers { @@ -9346,9 +9928,11 @@ public override System.Collections.Hashtable TypedSerializers _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::", new WildcardablePropertyQuerySerializer()); if (_typedSerializers == null) _typedSerializers = _tmp; } + return _typedSerializers; } } + public override bool CanSerialize(System.Type type) { if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return true; @@ -9391,6 +9975,7 @@ public override bool CanSerialize(System.Type type) if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) return true; return false; } + public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) { if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return new PowerShellMetadataSerializer(); From 15aed9d3fb5ef9a4e63c0ecbf41668037bf9b9b3 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:00 -0800 Subject: [PATCH 50/81] Update CoreCLR --- ...mdlets-over-objects.objectModel.autogen.cs | 110 ++++++ ...lets-over-objects.xmlSerializer.autogen.cs | 360 ++++++++++++++++++ 2 files changed, 470 insertions(+) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index aa4290a08c9..228288fc1b2 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -37,6 +37,7 @@ public ClassMetadata Class { return this._classField; } + set { this._classField = value; @@ -51,6 +52,7 @@ public EnumMetadataEnum[] Enums { return this._enumsField; } + set { this._enumsField = value; @@ -88,6 +90,7 @@ public string Version { return this._versionField; } + set { this._versionField = value; @@ -101,6 +104,7 @@ public string DefaultNoun { return this._defaultNounField; } + set { this._defaultNounField = value; @@ -114,6 +118,7 @@ public ClassMetadataInstanceCmdlets InstanceCmdlets { return this._instanceCmdletsField; } + set { this._instanceCmdletsField = value; @@ -128,6 +133,7 @@ public StaticCmdletMetadata[] StaticCmdlets { return this._staticCmdletsField; } + set { this._staticCmdletsField = value; @@ -142,6 +148,7 @@ public ClassMetadataData[] CmdletAdapterPrivateData { return this._cmdletAdapterPrivateDataField; } + set { this._cmdletAdapterPrivateDataField = value; @@ -156,6 +163,7 @@ public string CmdletAdapter { return this._cmdletAdapterField; } + set { this._cmdletAdapterField = value; @@ -170,6 +178,7 @@ public string ClassName { return this._classNameField; } + set { this._classNameField = value; @@ -184,6 +193,7 @@ public string ClassVersion { return this._classVersionField; } + set { this._classVersionField = value; @@ -211,6 +221,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -224,6 +235,7 @@ public GetCmdletMetadata GetCmdlet { return this._getCmdletField; } + set { this._getCmdletField = value; @@ -238,6 +250,7 @@ public InstanceCmdletMetadata[] Cmdlet { return this._cmdletField; } + set { this._cmdletField = value; @@ -268,6 +281,7 @@ public PropertyMetadata[] QueryableProperties { return this._queryablePropertiesField; } + set { this._queryablePropertiesField = value; @@ -282,6 +296,7 @@ public Association[] QueryableAssociations { return this._queryableAssociationsField; } + set { this._queryableAssociationsField = value; @@ -296,6 +311,7 @@ public QueryOption[] QueryOptions { return this._queryOptionsField; } + set { this._queryOptionsField = value; @@ -310,6 +326,7 @@ public string DefaultCmdletParameterSet { return this._defaultCmdletParameterSetField; } + set { this._defaultCmdletParameterSetField = value; @@ -339,6 +356,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -357,6 +375,7 @@ public PropertyQuery[] Items { return this._itemsField; } + set { this._itemsField = value; @@ -372,6 +391,7 @@ public ItemsChoiceType[] ItemsElementName { return this._itemsElementNameField; } + set { this._itemsElementNameField = value; @@ -386,6 +406,7 @@ public string PropertyName { return this._propertyNameField; } + set { this._propertyNameField = value; @@ -412,6 +433,7 @@ public string PSType { return this._pSTypeField; } + set { this._pSTypeField = value; @@ -426,6 +448,7 @@ public string ETSType { return this._eTSTypeField; } + set { this._eTSTypeField = value; @@ -455,6 +478,7 @@ public AssociationAssociatedInstance AssociatedInstance { return this._associatedInstanceField; } + set { this._associatedInstanceField = value; @@ -469,6 +493,7 @@ public string Association1 { return this._association1Field; } + set { this._association1Field = value; @@ -483,6 +508,7 @@ public string SourceRole { return this._sourceRoleField; } + set { this._sourceRoleField = value; @@ -497,6 +523,7 @@ public string ResultRole { return this._resultRoleField; } + set { this._resultRoleField = value; @@ -522,6 +549,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -535,6 +563,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -561,6 +590,7 @@ public bool ErrorOnNoMatch { return this._errorOnNoMatchField; } + set { this._errorOnNoMatchField = value; @@ -575,6 +605,7 @@ public bool ErrorOnNoMatchSpecified { return this._errorOnNoMatchFieldSpecified; } + set { this._errorOnNoMatchFieldSpecified = value; @@ -608,6 +639,7 @@ public bool ValueFromPipeline { return this._valueFromPipelineField; } + set { this._valueFromPipelineField = value; @@ -622,6 +654,7 @@ public bool ValueFromPipelineSpecified { return this._valueFromPipelineFieldSpecified; } + set { this._valueFromPipelineFieldSpecified = value; @@ -636,6 +669,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -650,6 +684,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -664,6 +699,7 @@ public string[] CmdletParameterSets { return this._cmdletParameterSetsField; } + set { this._cmdletParameterSetsField = value; @@ -719,6 +755,7 @@ public object AllowEmptyCollection { return this._allowEmptyCollectionField; } + set { this._allowEmptyCollectionField = value; @@ -732,6 +769,7 @@ public object AllowEmptyString { return this._allowEmptyStringField; } + set { this._allowEmptyStringField = value; @@ -745,6 +783,7 @@ public object AllowNull { return this._allowNullField; } + set { this._allowNullField = value; @@ -758,6 +797,7 @@ public object ValidateNotNull { return this._validateNotNullField; } + set { this._validateNotNullField = value; @@ -771,6 +811,7 @@ public object ValidateNotNullOrEmpty { return this._validateNotNullOrEmptyField; } + set { this._validateNotNullOrEmptyField = value; @@ -784,6 +825,7 @@ public CmdletParameterMetadataValidateCount ValidateCount { return this._validateCountField; } + set { this._validateCountField = value; @@ -797,6 +839,7 @@ public CmdletParameterMetadataValidateLength ValidateLength { return this._validateLengthField; } + set { this._validateLengthField = value; @@ -810,6 +853,7 @@ public CmdletParameterMetadataValidateRange ValidateRange { return this._validateRangeField; } + set { this._validateRangeField = value; @@ -824,6 +868,7 @@ public string[] ValidateSet { return this._validateSetField; } + set { this._validateSetField = value; @@ -837,6 +882,7 @@ public ObsoleteAttributeMetadata Obsolete { return this._obsoleteField; } + set { this._obsoleteField = value; @@ -851,6 +897,7 @@ public bool IsMandatory { return this._isMandatoryField; } + set { this._isMandatoryField = value; @@ -865,6 +912,7 @@ public bool IsMandatorySpecified { return this._isMandatoryFieldSpecified; } + set { this._isMandatoryFieldSpecified = value; @@ -879,6 +927,7 @@ public string[] Aliases { return this._aliasesField; } + set { this._aliasesField = value; @@ -893,6 +942,7 @@ public string PSName { return this._pSNameField; } + set { this._pSNameField = value; @@ -907,6 +957,7 @@ public string Position { return this._positionField; } + set { this._positionField = value; @@ -933,6 +984,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -947,6 +999,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -973,6 +1026,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -987,6 +1041,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -1013,6 +1068,7 @@ public string Min { return this._minField; } + set { this._minField = value; @@ -1027,6 +1083,7 @@ public string Max { return this._maxField; } + set { this._maxField = value; @@ -1051,6 +1108,7 @@ public string Message { return this._messageField; } + set { this._messageField = value; @@ -1077,6 +1135,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -1091,6 +1150,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -1121,6 +1181,7 @@ public bool ValueFromPipeline { return this._valueFromPipelineField; } + set { this._valueFromPipelineField = value; @@ -1135,6 +1196,7 @@ public bool ValueFromPipelineSpecified { return this._valueFromPipelineFieldSpecified; } + set { this._valueFromPipelineFieldSpecified = value; @@ -1149,6 +1211,7 @@ public bool ValueFromPipelineByPropertyName { return this._valueFromPipelineByPropertyNameField; } + set { this._valueFromPipelineByPropertyNameField = value; @@ -1163,6 +1226,7 @@ public bool ValueFromPipelineByPropertyNameSpecified { return this._valueFromPipelineByPropertyNameFieldSpecified; } + set { this._valueFromPipelineByPropertyNameFieldSpecified = value; @@ -1190,6 +1254,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1203,6 +1268,7 @@ public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1217,6 +1283,7 @@ public string OptionName { return this._optionNameField; } + set { this._optionNameField = value; @@ -1242,6 +1309,7 @@ public CommonCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1255,6 +1323,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -1290,6 +1359,7 @@ public ObsoleteAttributeMetadata Obsolete { return this._obsoleteField; } + set { this._obsoleteField = value; @@ -1304,6 +1374,7 @@ public string Verb { return this._verbField; } + set { this._verbField = value; @@ -1318,6 +1389,7 @@ public string Noun { return this._nounField; } + set { this._nounField = value; @@ -1332,6 +1404,7 @@ public string[] Aliases { return this._aliasesField; } + set { this._aliasesField = value; @@ -1346,6 +1419,7 @@ public ConfirmImpact ConfirmImpact { return this._confirmImpactField; } + set { this._confirmImpactField = value; @@ -1360,6 +1434,7 @@ public bool ConfirmImpactSpecified { return this._confirmImpactFieldSpecified; } + set { this._confirmImpactFieldSpecified = value; @@ -1374,6 +1449,7 @@ public string HelpUri { return this._helpUriField; } + set { this._helpUriField = value; @@ -1418,6 +1494,7 @@ public StaticCmdletMetadataCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1432,6 +1509,7 @@ public StaticMethodMetadata[] Method { return this._methodField; } + set { this._methodField = value; @@ -1456,6 +1534,7 @@ public string DefaultCmdletParameterSet { return this._defaultCmdletParameterSetField; } + set { this._defaultCmdletParameterSetField = value; @@ -1482,6 +1561,7 @@ public StaticMethodParameterMetadata[] Parameters { return this._parametersField; } + set { this._parametersField = value; @@ -1496,6 +1576,7 @@ public string CmdletParameterSet { return this._cmdletParameterSetField; } + set { this._cmdletParameterSetField = value; @@ -1521,6 +1602,7 @@ public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1534,6 +1616,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1559,6 +1642,7 @@ public object ErrorCode { return this._errorCodeField; } + set { this._errorCodeField = value; @@ -1573,6 +1657,7 @@ public string PSName { return this._pSNameField; } + set { this._pSNameField = value; @@ -1602,6 +1687,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1616,6 +1702,7 @@ public string ParameterName { return this._parameterNameField; } + set { this._parameterNameField = value; @@ -1630,6 +1717,7 @@ public string DefaultValue { return this._defaultValueField; } + set { this._defaultValueField = value; @@ -1655,6 +1743,7 @@ public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1668,6 +1757,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1695,6 +1785,7 @@ public CommonMethodMetadataReturnValue ReturnValue { return this._returnValueField; } + set { this._returnValueField = value; @@ -1709,6 +1800,7 @@ public string MethodName { return this._methodNameField; } + set { this._methodNameField = value; @@ -1734,6 +1826,7 @@ public TypeMetadata Type { return this._typeField; } + set { this._typeField = value; @@ -1747,6 +1840,7 @@ public CmdletOutputMetadata CmdletOutputMetadata { return this._cmdletOutputMetadataField; } + set { this._cmdletOutputMetadataField = value; @@ -1771,6 +1865,7 @@ public InstanceMethodParameterMetadata[] Parameters { return this._parametersField; } + set { this._parametersField = value; @@ -1798,6 +1893,7 @@ public CommonCmdletMetadata CmdletMetadata { return this._cmdletMetadataField; } + set { this._cmdletMetadataField = value; @@ -1811,6 +1907,7 @@ public InstanceMethodMetadata Method { return this._methodField; } + set { this._methodField = value; @@ -1824,6 +1921,7 @@ public GetCmdletParameters GetCmdletParameters { return this._getCmdletParametersField; } + set { this._getCmdletParametersField = value; @@ -1848,6 +1946,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta { return this._cmdletParameterMetadataField; } + set { this._cmdletParameterMetadataField = value; @@ -1874,6 +1973,7 @@ public bool AllowGlobbing { return this._allowGlobbingField; } + set { this._allowGlobbingField = value; @@ -1888,6 +1988,7 @@ public bool AllowGlobbingSpecified { return this._allowGlobbingFieldSpecified; } + set { this._allowGlobbingFieldSpecified = value; @@ -1933,6 +2034,7 @@ public string Name { return this._nameField; } + set { this._nameField = value; @@ -1947,6 +2049,7 @@ public string Value { return this._valueField; } + set { this._valueField = value; @@ -1979,6 +2082,7 @@ public EnumMetadataEnumValue[] Value { return this._valueField; } + set { this._valueField = value; @@ -1993,6 +2097,7 @@ public string EnumName { return this._enumNameField; } + set { this._enumNameField = value; @@ -2007,6 +2112,7 @@ public string UnderlyingType { return this._underlyingTypeField; } + set { this._underlyingTypeField = value; @@ -2021,6 +2127,7 @@ public bool BitwiseFlags { return this._bitwiseFlagsField; } + set { this._bitwiseFlagsField = value; @@ -2035,6 +2142,7 @@ public bool BitwiseFlagsSpecified { return this._bitwiseFlagsFieldSpecified; } + set { this._bitwiseFlagsFieldSpecified = value; @@ -2061,6 +2169,7 @@ public string Name { return this._nameField; } + set { this._nameField = value; @@ -2075,6 +2184,7 @@ public string Value { return this._valueField; } + set { this._valueField = value; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 376c05d157d..38b4be12237 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -175,6 +175,7 @@ internal bool DecodeName { return _decodeName; } + set { _decodeName = value; @@ -189,6 +190,7 @@ protected XmlDocument Document { _d = new XmlDocument(_r.NameTable); } + return _d; } } @@ -303,6 +305,7 @@ protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullab if (isNullable) return null; return Array.CreateInstance(elementType, 0); } + if (a.Length == length) return a; Array b = Array.CreateInstance(elementType, length); Array.Copy(a, b, length); @@ -413,6 +416,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) prefix = XmlConvert.DecodeName(prefix); localName = XmlConvert.DecodeName(localName); } + if (prefix == null || prefix.Length == 0) { return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(String.Empty)); @@ -425,6 +429,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) // Namespace prefix '{0}' is not defined. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUndefinedAlias. Prefix: {0}", prefix)); } + return new XmlQualifiedName(_r.NameTable.Add(localName), ns); } } @@ -448,6 +453,7 @@ protected XmlQualifiedName GetXsiType() return null; } } + return ToXmlQualifiedName(type, false); } @@ -462,6 +468,7 @@ protected bool GetNullAttr() if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNs1999ID); } + if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false; return true; } @@ -474,6 +481,7 @@ protected bool ReadNull() _r.Skip(); return true; } + _r.ReadStartElement(); int whileIterations = 0; int readerCount = ReaderCount; @@ -482,6 +490,7 @@ protected bool ReadNull() UnknownNode(null); CheckReaderCount(ref whileIterations, ref readerCount); } + ReadEndElement(); return true; } @@ -552,6 +561,7 @@ public object Read50_PowerShellMetadata() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); } + return (object)o; } @@ -574,6 +584,7 @@ public object Read51_ClassMetadata() { UnknownNode(null, @":ClassMetadata"); } + return (object)o; } @@ -596,6 +607,7 @@ public object Read52_ClassMetadataInstanceCmdlets() { UnknownNode(null, @":ClassMetadataInstanceCmdlets"); } + return (object)o; } @@ -618,6 +630,7 @@ public object Read53_GetCmdletParameters() { UnknownNode(null, @":GetCmdletParameters"); } + return (object)o; } @@ -640,6 +653,7 @@ public object Read54_PropertyMetadata() { UnknownNode(null, @":PropertyMetadata"); } + return (object)o; } @@ -662,6 +676,7 @@ public object Read55_TypeMetadata() { UnknownNode(null, @":TypeMetadata"); } + return (object)o; } @@ -684,6 +699,7 @@ public object Read56_Association() { UnknownNode(null, @":Association"); } + return (object)o; } @@ -706,6 +722,7 @@ public object Read57_AssociationAssociatedInstance() { UnknownNode(null, @":AssociationAssociatedInstance"); } + return (object)o; } @@ -728,6 +745,7 @@ public object Read58_CmdletParameterMetadata() { UnknownNode(null, @":CmdletParameterMetadata"); } + return (object)o; } @@ -750,6 +768,7 @@ public object Read59_Item() { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); } + return (object)o; } @@ -772,6 +791,7 @@ public object Read60_Item() { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); } + return (object)o; } @@ -794,6 +814,7 @@ public object Read61_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateCount"); } + return (object)o; } @@ -816,6 +837,7 @@ public object Read62_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateLength"); } + return (object)o; } @@ -838,6 +860,7 @@ public object Read63_Item() { UnknownNode(null, @":CmdletParameterMetadataValidateRange"); } + return (object)o; } @@ -860,6 +883,7 @@ public object Read64_ObsoleteAttributeMetadata() { UnknownNode(null, @":ObsoleteAttributeMetadata"); } + return (object)o; } @@ -882,6 +906,7 @@ public object Read65_Item() { UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); } + return (object)o; } @@ -904,6 +929,7 @@ public object Read66_Item() { UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); } + return (object)o; } @@ -926,6 +952,7 @@ public object Read67_QueryOption() { UnknownNode(null, @":QueryOption"); } + return (object)o; } @@ -948,6 +975,7 @@ public object Read68_GetCmdletMetadata() { UnknownNode(null, @":GetCmdletMetadata"); } + return (object)o; } @@ -970,6 +998,7 @@ public object Read69_CommonCmdletMetadata() { UnknownNode(null, @":CommonCmdletMetadata"); } + return (object)o; } @@ -994,6 +1023,7 @@ public object Read70_ConfirmImpact() { UnknownNode(null, @":ConfirmImpact"); } + return (object)o; } @@ -1016,6 +1046,7 @@ public object Read71_StaticCmdletMetadata() { UnknownNode(null, @":StaticCmdletMetadata"); } + return (object)o; } @@ -1038,6 +1069,7 @@ public object Read72_Item() { UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); } + return (object)o; } @@ -1060,6 +1092,7 @@ public object Read73_CommonMethodMetadata() { UnknownNode(null, @":CommonMethodMetadata"); } + return (object)o; } @@ -1082,6 +1115,7 @@ public object Read74_StaticMethodMetadata() { UnknownNode(null, @":StaticMethodMetadata"); } + return (object)o; } @@ -1104,6 +1138,7 @@ public object Read75_CommonMethodParameterMetadata() { UnknownNode(null, @":CommonMethodParameterMetadata"); } + return (object)o; } @@ -1126,6 +1161,7 @@ public object Read76_StaticMethodParameterMetadata() { UnknownNode(null, @":StaticMethodParameterMetadata"); } + return (object)o; } @@ -1148,6 +1184,7 @@ public object Read77_CmdletOutputMetadata() { UnknownNode(null, @":CmdletOutputMetadata"); } + return (object)o; } @@ -1170,6 +1207,7 @@ public object Read78_Item() { UnknownNode(null, @":InstanceMethodParameterMetadata"); } + return (object)o; } @@ -1192,6 +1230,7 @@ public object Read79_Item() { UnknownNode(null, @":CommonMethodMetadataReturnValue"); } + return (object)o; } @@ -1214,6 +1253,7 @@ public object Read80_InstanceMethodMetadata() { UnknownNode(null, @":InstanceMethodMetadata"); } + return (object)o; } @@ -1236,6 +1276,7 @@ public object Read81_InstanceCmdletMetadata() { UnknownNode(null, @":InstanceCmdletMetadata"); } + return (object)o; } @@ -1258,6 +1299,7 @@ public object Read82_PropertyQuery() { UnknownNode(null, @":PropertyQuery"); } + return (object)o; } @@ -1280,6 +1322,7 @@ public object Read83_WildcardablePropertyQuery() { UnknownNode(null, @":WildcardablePropertyQuery"); } + return (object)o; } @@ -1304,6 +1347,7 @@ public object Read84_ItemsChoiceType() { UnknownNode(null, @":ItemsChoiceType"); } + return (object)o; } @@ -1326,6 +1370,7 @@ public object Read85_ClassMetadataData() { UnknownNode(null, @":ClassMetadataData"); } + return (object)o; } @@ -1348,6 +1393,7 @@ public object Read86_EnumMetadataEnum() { UnknownNode(null, @":EnumMetadataEnum"); } + return (object)o; } @@ -1370,6 +1416,7 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @":EnumMetadataEnumValue"); } + return (object)o; } @@ -1386,6 +1433,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); @@ -1407,12 +1455,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name, :Value"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations0 = 0; @@ -1427,9 +1477,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations0, ref readerCount0); } + ReadEndElement(); return o; } @@ -1447,6 +1499,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); @@ -1476,6 +1529,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -1483,6 +1537,7 @@ public object Read87_EnumMetadataEnumValue() o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations1 = 0; @@ -1504,9 +1559,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations1, ref readerCount1); } + o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); ReadEndElement(); return o; @@ -1525,6 +1582,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); @@ -1546,12 +1604,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name, :Value"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations2 = 0; @@ -1566,9 +1626,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations2, ref readerCount2); } + ReadEndElement(); return o; } @@ -1586,6 +1648,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); @@ -1602,12 +1665,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations3 = 0; @@ -1631,9 +1696,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations3, ref readerCount3); } + ReadEndElement(); return o; } @@ -1663,6 +1730,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery(); @@ -1680,12 +1748,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":AllowGlobbing"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations4 = 0; @@ -1708,9 +1778,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations4, ref readerCount4); } + ReadEndElement(); return o; } @@ -1728,6 +1800,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter(); @@ -1797,6 +1870,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -1805,6 +1879,7 @@ public object Read87_EnumMetadataEnumValue() o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations5 = 0; @@ -1888,11 +1963,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations6, ref readerCount6); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -1910,9 +1988,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations5, ref readerCount5); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); ReadEndElement(); @@ -1932,6 +2012,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata(); @@ -1948,12 +2029,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Message"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations7 = 0; @@ -1968,9 +2051,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations7, ref readerCount7); } + ReadEndElement(); return o; } @@ -1988,6 +2073,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); @@ -2009,12 +2095,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations8 = 0; @@ -2029,9 +2117,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations8, ref readerCount8); } + ReadEndElement(); return o; } @@ -2049,6 +2139,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); @@ -2070,12 +2161,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations9 = 0; @@ -2090,9 +2183,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations9, ref readerCount9); } + ReadEndElement(); return o; } @@ -2110,6 +2205,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); @@ -2131,12 +2227,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations10 = 0; @@ -2151,9 +2249,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations10, ref readerCount10); } + ReadEndElement(); return o; } @@ -2170,6 +2270,7 @@ public object Read87_EnumMetadataEnumValue() if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } + if (xsiType == null) { return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); @@ -2287,13 +2388,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations11, ref readerCount11); } + ReadEndElement(); } + a = (global::System.String[])ShrinkArray(z_0_0, cz_0_0, typeof(global::System.String), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id70_ArrayOfPropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2330,13 +2435,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations12, ref readerCount12); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id72_ArrayOfAssociation && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2373,13 +2482,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations13, ref readerCount13); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id73_ArrayOfQueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2416,13 +2529,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations14, ref readerCount14); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id23_ConfirmImpact && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2466,13 +2583,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations15, ref readerCount15); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id77_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2509,13 +2630,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations16, ref readerCount16); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id78_ArrayOfStaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2552,13 +2677,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations17, ref readerCount17); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id80_ArrayOfClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2595,13 +2724,17 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations18, ref readerCount18); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); } + return a; } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id82_ArrayOfEnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -2638,18 +2771,23 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations19, ref readerCount19); } + ReadEndElement(); } + a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } + return a; } else return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::System.Object o; o = new global::System.Object(); @@ -2661,12 +2799,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations20 = 0; @@ -2681,9 +2821,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations20, ref readerCount20); } + ReadEndElement(); return o; } @@ -2701,6 +2843,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); @@ -2730,6 +2873,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -2737,6 +2881,7 @@ public object Read87_EnumMetadataEnumValue() o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations21 = 0; @@ -2758,9 +2903,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations21, ref readerCount21); } + o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); ReadEndElement(); return o; @@ -2779,6 +2926,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); @@ -2795,12 +2943,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Name"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations22 = 0; @@ -2824,9 +2974,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations22, ref readerCount22); } + ReadEndElement(); return o; } @@ -2844,6 +2996,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata(); @@ -2857,6 +3010,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -2864,6 +3018,7 @@ public object Read87_EnumMetadataEnumValue() o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations23 = 0; @@ -2890,9 +3045,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations23, ref readerCount23); } + o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); ReadEndElement(); return o; @@ -2911,6 +3068,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata(); @@ -2934,12 +3092,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations24 = 0; @@ -2986,11 +3146,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations25, ref readerCount25); } + ReadEndElement(); } + o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); } } @@ -3003,9 +3166,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations24, ref readerCount24); } + ReadEndElement(); return o; } @@ -3023,6 +3188,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata(); @@ -3044,12 +3210,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations26 = 0; @@ -3082,9 +3250,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations26, ref readerCount26); } + ReadEndElement(); return o; } @@ -3102,6 +3272,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata(); @@ -3118,12 +3289,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PSName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations27 = 0; @@ -3146,9 +3319,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations27, ref readerCount27); } + ReadEndElement(); return o; } @@ -3166,6 +3341,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter(); @@ -3218,6 +3394,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3225,6 +3402,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations28 = 0; @@ -3308,11 +3486,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations29, ref readerCount29); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -3330,9 +3511,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations28, ref readerCount28); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -3351,6 +3534,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata(); @@ -3372,12 +3556,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PSType, :ETSType"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations30 = 0; @@ -3392,9 +3578,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations30, ref readerCount30); } + ReadEndElement(); return o; } @@ -3412,6 +3600,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); @@ -3423,12 +3612,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations31 = 0; @@ -3456,9 +3647,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations31, ref readerCount31); } + ReadEndElement(); return o; } @@ -3476,6 +3669,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); @@ -3524,6 +3718,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3531,6 +3726,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations32 = 0; @@ -3553,9 +3749,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations32, ref readerCount32); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -3586,6 +3784,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata(); @@ -3607,12 +3806,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations33 = 0; @@ -3645,9 +3846,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations33, ref readerCount33); } + ReadEndElement(); return o; } @@ -3665,6 +3868,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter(); @@ -3711,6 +3915,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipelineByPropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3718,6 +3923,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations34 = 0; @@ -3801,11 +4007,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations35, ref readerCount35); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -3823,9 +4032,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations34, ref readerCount34); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -3844,6 +4055,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption(); @@ -3860,12 +4072,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":OptionName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations36 = 0; @@ -3893,9 +4107,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations36, ref readerCount36); } + ReadEndElement(); return o; } @@ -3915,6 +4131,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter(); @@ -3978,6 +4195,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -3986,6 +4204,7 @@ public object Read87_EnumMetadataEnumValue() o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations37 = 0; @@ -4069,11 +4288,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations38, ref readerCount38); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -4091,9 +4313,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations37, ref readerCount37); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); ReadEndElement(); @@ -4113,6 +4337,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.Association o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.Association(); @@ -4139,12 +4364,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Association, :SourceRole, :ResultRole"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations39 = 0; @@ -4167,9 +4394,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations39, ref readerCount39); } + ReadEndElement(); return o; } @@ -4187,6 +4416,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); @@ -4198,12 +4428,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations40 = 0; @@ -4231,9 +4463,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations40, ref readerCount40); } + ReadEndElement(); return o; } @@ -4251,6 +4485,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata(); @@ -4271,6 +4506,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":PropertyName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -4279,6 +4515,7 @@ public object Read87_EnumMetadataEnumValue() o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations41 = 0; @@ -4321,9 +4558,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations41, ref readerCount41); } + o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); ReadEndElement(); @@ -4345,6 +4584,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery(); @@ -4356,12 +4596,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations42 = 0; @@ -4384,9 +4626,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations42, ref readerCount42); } + ReadEndElement(); return o; } @@ -4412,6 +4656,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata(); @@ -4452,6 +4697,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -4459,6 +4705,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations43 = 0; @@ -4542,11 +4789,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations44, ref readerCount44); } + ReadEndElement(); } + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); } } @@ -4564,9 +4814,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations43, ref readerCount43); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); ReadEndElement(); return o; @@ -4585,6 +4837,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters(); @@ -4607,12 +4860,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations45 = 0; @@ -4654,11 +4909,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations46, ref readerCount46); } + ReadEndElement(); } + o.@QueryableProperties = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); } } @@ -4695,11 +4953,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations47, ref readerCount47); } + ReadEndElement(); } + o.@QueryableAssociations = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); } } @@ -4736,11 +4997,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations48, ref readerCount48); } + ReadEndElement(); } + o.@QueryOptions = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); } } @@ -4753,9 +5017,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations45, ref readerCount45); } + ReadEndElement(); return o; } @@ -4773,6 +5039,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); @@ -4821,6 +5088,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -4828,6 +5096,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations49 = 0; @@ -4850,9 +5119,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations49, ref readerCount49); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -4873,6 +5144,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata(); @@ -4916,6 +5188,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -4923,6 +5196,7 @@ public object Read87_EnumMetadataEnumValue() o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations50 = 0; @@ -4945,9 +5219,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations50, ref readerCount50); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); ReadEndElement(); return o; @@ -4966,6 +5242,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata(); @@ -4977,12 +5254,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations51 = 0; @@ -5010,9 +5289,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations51, ref readerCount51); } + ReadEndElement(); return o; } @@ -5030,6 +5311,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata(); @@ -5048,12 +5330,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations52 = 0; @@ -5100,11 +5384,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations53, ref readerCount53); } + ReadEndElement(); } + o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); } } @@ -5117,9 +5404,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations52, ref readerCount52); } + ReadEndElement(); return o; } @@ -5141,6 +5430,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata(); @@ -5157,12 +5447,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":MethodName"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations54 = 0; @@ -5185,9 +5477,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations54, ref readerCount54); } + ReadEndElement(); return o; } @@ -5209,6 +5503,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata(); @@ -5230,12 +5525,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":ParameterName, :DefaultValue"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations55 = 0; @@ -5258,9 +5555,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations55, ref readerCount55); } + ReadEndElement(); return o; } @@ -5278,6 +5577,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata(); @@ -5289,12 +5589,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations56 = 0; @@ -5327,9 +5629,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations56, ref readerCount56); } + ReadEndElement(); return o; } @@ -5347,6 +5651,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata(); @@ -5377,12 +5682,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":CmdletAdapter, :ClassName, :ClassVersion"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations57 = 0; @@ -5396,6 +5703,7 @@ public object Read87_EnumMetadataEnumValue() { o.@Version = Reader.ReadElementContentAsString(); } + paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id116_DefaultNoun && (object)Reader.NamespaceURI == (object)_id2_Item)) @@ -5403,6 +5711,7 @@ public object Read87_EnumMetadataEnumValue() { o.@DefaultNoun = Reader.ReadElementContentAsString(); } + paramsRead[1] = true; } else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id117_InstanceCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) @@ -5443,11 +5752,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations58, ref readerCount58); } + ReadEndElement(); } + o.@StaticCmdlets = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); } } @@ -5484,11 +5796,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations59, ref readerCount59); } + ReadEndElement(); } + o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); } } @@ -5501,9 +5816,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations57, ref readerCount57); } + ReadEndElement(); return o; } @@ -5521,6 +5838,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); @@ -5534,6 +5852,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5541,6 +5860,7 @@ public object Read87_EnumMetadataEnumValue() o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations60 = 0; @@ -5572,9 +5892,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations60, ref readerCount60); } + o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); ReadEndElement(); return o; @@ -5593,6 +5915,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); @@ -5606,6 +5929,7 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { @@ -5613,6 +5937,7 @@ public object Read87_EnumMetadataEnumValue() o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations61 = 0; @@ -5644,9 +5969,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations61, ref readerCount61); } + o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); ReadEndElement(); return o; @@ -5665,6 +5992,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); @@ -5676,12 +6004,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations62 = 0; @@ -5709,9 +6039,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations62, ref readerCount62); } + ReadEndElement(); return o; } @@ -5729,6 +6061,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); @@ -5750,12 +6083,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations63 = 0; @@ -5770,9 +6105,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations63, ref readerCount63); } + ReadEndElement(); return o; } @@ -5790,6 +6127,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); @@ -5811,12 +6149,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations64 = 0; @@ -5831,9 +6171,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations64, ref readerCount64); } + ReadEndElement(); return o; } @@ -5851,6 +6193,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); @@ -5872,12 +6215,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o, @":Min, :Max"); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations65 = 0; @@ -5892,9 +6237,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, string.Empty); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations65, ref readerCount65); } + ReadEndElement(); return o; } @@ -5912,6 +6259,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); @@ -5923,12 +6271,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations66 = 0; @@ -5956,9 +6306,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations66, ref readerCount66); } + ReadEndElement(); return o; } @@ -5976,6 +6328,7 @@ public object Read87_EnumMetadataEnumValue() else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } + if (isNull) return null; global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o; o = new global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata(); @@ -5989,12 +6342,14 @@ public object Read87_EnumMetadataEnumValue() UnknownNode((object)o); } } + Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } + Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations67 = 0; @@ -6041,11 +6396,14 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations68, ref readerCount68); } + ReadEndElement(); } + o.@Enums = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } } @@ -6058,9 +6416,11 @@ public object Read87_EnumMetadataEnumValue() { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); } + Reader.MoveToContent(); CheckReaderCount(ref whileIterations67, ref readerCount67); } + ReadEndElement(); return o; } From 24ecf77057592e11c2be20ed012353fc07c69239 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:00 -0800 Subject: [PATCH 51/81] Update common --- .../common/BaseFormattingCommand.cs | 23 ++++++++++++++++++ .../common/BaseFormattingCommandParameters.cs | 4 ++++ .../common/BaseOutputtingCommand.cs | 13 ++++++++++ .../FormatAndOutput/common/ComplexWriter.cs | 7 ++++++ .../common/FormatGroupManager.cs | 1 + .../common/FormatMsgCtxManager.cs | 1 + .../common/FormatViewGenerator.cs | 11 +++++++++ .../common/FormatViewGenerator_Complex.cs | 15 ++++++++++++ .../common/FormatViewGenerator_List.cs | 5 ++++ .../common/FormatViewGenerator_Table.cs | 12 ++++++++++ .../common/FormatViewGenerator_Wide.cs | 2 ++ .../common/FormatViewManager.cs | 13 ++++++++++ .../FormatAndOutput/common/FormatXMLWriter.cs | 24 +++++++++++++++++++ .../common/FormattingObjectsDeserializer.cs | 14 +++++++++++ .../FormatAndOutput/common/ILineOutput.cs | 5 ++++ .../FormatAndOutput/common/ListWriter.cs | 1 + .../FormatAndOutput/common/OutputManager.cs | 1 + .../FormatAndOutput/common/TableWriter.cs | 16 +++++++++++++ 18 files changed, 168 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index 057ab045ce8..c968efe90dd 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -118,6 +118,7 @@ internal override void ProcessRecord() ProcessObject(PSObjectHelper.AsPSObject(obj)); } } + break; case EnumerableExpansion.Both: { @@ -129,12 +130,14 @@ internal override void ProcessRecord() ProcessObject(PSObjectHelper.AsPSObject(obj)); } } + break; default: { // do not enumerate at all (CoreOnly) ProcessObject(so); } + break; } } @@ -169,18 +172,22 @@ private void ProcessCoreOutOfBand(PSObject so, int count) { msg = FormatAndOut_format_xxx.IEnum_NoObjects; } + break; case 1: { msg = FormatAndOut_format_xxx.IEnum_OneObject; } + break; default: { msg = StringUtil.Format(FormatAndOut_format_xxx.IEnum_ManyObjects, count); } + break; } + SendCommentOutOfBand(msg); } @@ -274,6 +281,7 @@ private bool ShouldProcessOutOfBand { return true; } + return !_parameters.forceFormattingAlsoOnOutOfBand; } } @@ -547,8 +555,10 @@ public SwitchParameter ShowError return showErrorsAsMessages.Value; return false; } + set { showErrorsAsMessages = value; } } + internal bool? showErrorsAsMessages = null; /// @@ -564,8 +574,10 @@ public SwitchParameter DisplayError return showErrorsInFormattedOutput.Value; return false; } + set { showErrorsInFormattedOutput = value; } } + internal bool? showErrorsInFormattedOutput = null; /// @@ -576,8 +588,10 @@ public SwitchParameter DisplayError public SwitchParameter Force { get { return _forceFormattingAlsoOnOutOfBand; } + set { _forceFormattingAlsoOnOutOfBand = value; } } + private bool _forceFormattingAlsoOnOutOfBand; /// @@ -608,6 +622,7 @@ public SwitchParameter Force // NOTE: this is an exception that should never be triggered throw PSTraceSource.NewArgumentException("Expand", FormatAndOut_MshParameter.IllegalEnumerableExpansionValue); } + retVal = temp; return retVal; } @@ -731,6 +746,7 @@ internal void GetCommandLineProperties(FormattingCommandLineParameters parameter { ReportCannotSpecifyViewAndProperty(); } + parameters.viewName = this.View; } } @@ -755,8 +771,10 @@ public SwitchParameter AutoSize return _autosize.Value; return false; } + set { _autosize = value; } } + private bool? _autosize = null; /// @@ -778,8 +796,10 @@ public SwitchParameter HideTableHeaders return _hideHeaders.Value; return false; } + set { _hideHeaders = value; } } + private bool? _hideHeaders = null; /// @@ -795,8 +815,10 @@ public SwitchParameter Wrap return _multiLine.Value; return false; } + set { _multiLine = value; } } + private bool? _multiLine = null; #endregion @@ -835,6 +857,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { tableParameters.multiLine = _multiLine.Value; } + return parameters; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index d79e6891e40..340401832ee 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -190,14 +190,17 @@ internal override object Verify(object val, { ProcessEmptyStringError(originalParameterWasHashTable, invocationContext); } + PSPropertyExpression ex = new PSPropertyExpression(s); if (_noGlobbing) { if (ex.HasWildCardCharacters) ProcessGlobbingCharactersError(originalParameterWasHashTable, s, invocationContext); } + return ex; } + PSTraceSource.NewArgumentException("val"); return null; } @@ -404,6 +407,7 @@ internal override object Verify(object val, // this should never happen throw PSTraceSource.NewInvalidOperationException(); } + return LanguagePrimitives.IsTrue(val); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index f56f12e6e76..f559767b248 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -168,6 +168,7 @@ private bool ProcessObject(PSObject so) for (int k = 0; k < info.Count; k++) _ctxManager.Process(info[k]); } + return true; } @@ -270,6 +271,7 @@ private bool NeedsPreprocessing(object o) // we allow out of band data in any state ValidateCurrentFormattingState(FormattingState.InsideGroup, o); } + return false; } else if (o is FormatStartData) @@ -430,8 +432,10 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( { Diagnostics.Assert(false, "Invalid shape. This should never happen"); } + break; } + goc.Initialize(); return goc; } @@ -478,6 +482,7 @@ private void ProcessGroupStart(FormatMessagesContextManager.OutputContext c) writer.Initialize(_lo, _lo.ColumnNumber); writer.WriteObject(goc.Data.groupingEntry.formatValueList); } + goc.GroupStart(); } @@ -506,6 +511,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou { PSTraceSource.NewArgumentNullException("fed"); } + if (fed.formatEntryInfo == null) { PSTraceSource.NewArgumentNullException("fed.formatEntryInfo"); @@ -592,6 +598,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) internal LineOutput LineOutput { set { _lo = value; } + get { return _lo; } } @@ -1003,6 +1010,7 @@ internal override void Initialize() alignment[k] = tci.alignment; k++; } + this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader); } @@ -1024,6 +1032,7 @@ internal override void GroupStart() { properties[k++] = tci.label ?? tci.propertyName; } + _rowCount += this.Writer.GenerateHeader(properties, this.InnerCommand._lo); } @@ -1067,6 +1076,7 @@ internal override void ProcessPayload(FormatEntryData fed) alignment[k] = TextAlignment.Left; // hard coded default } } + this.Writer.GenerateRow(values, this.InnerCommand._lo, tre.multiLine, alignment, InnerCommand._lo.DisplayCells, generatedRows: null); _rowCount++; } @@ -1115,6 +1125,7 @@ internal static string[] GetProperties(ListViewEntry lve) { props.Add(lvf.label ?? lvf.propertyName); } + if (props.Count == 0) return null; string[] retVal = new string[props.Count]; @@ -1130,6 +1141,7 @@ internal static string[] GetValues(ListViewEntry lve) { vals.Add(lvf.formatPropertyField.propertyValue); } + if (vals.Count == 0) return null; string[] retVal = new string[vals.Count]; @@ -1278,6 +1290,7 @@ private void WriteStringBuffer() else values[k] = string.Empty; } + this.Writer.GenerateRow(values, this.InnerCommand._lo, false, null, InnerCommand._lo.DisplayCells, generatedRows: null); _buffer.Reset(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 74deb326894..df6dbf76190 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -88,19 +88,23 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) GenerateFormatEntryDisplay(feChild, currentDepth + 1); } } + continue; } + if (obj is FormatNewLine) { this.WriteToScreen(); continue; } + FormatTextField ftf = obj as FormatTextField; if (ftf != null) { this.AddToBuffer(ftf.text); continue; } + FormatPropertyField fpf = obj as FormatPropertyField; if (fpf != null) { @@ -292,6 +296,7 @@ private int ComputeRightIndentation() { val += fi.rightIndentation; } + return val; } @@ -302,6 +307,7 @@ private int ComputeLeftIndentation() { val += fi.leftIndentation; } + return val; } @@ -490,6 +496,7 @@ internal void AddLine(string s) { _addedFirstLine = true; } + _retVal.Add(s); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs index 1185a151dce..f9df3c979b4 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs @@ -70,6 +70,7 @@ internal bool UpdateGroupingKeyValue(PSObject so) { _groupingKeyDisplayName = results[0].ResolvedExpression.ToString(); } + return update; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index d9b59940d7e..1c5ba9f78b7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -117,6 +117,7 @@ internal void Process(object o) // notify for Fe, passing the Fe info, before a Pop() this.ge(ged, oc); } + _stack.Pop(); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index 10d46a731ab..49e34d7b4a2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -77,6 +77,7 @@ private void InitializeFormatErrorManager() { formatErrorPolicy.ShowErrorsAsMessages = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; } + if (parameters != null && parameters.showErrorsInFormattedOutput.HasValue) { formatErrorPolicy.ShowErrorsInFormattedOutput = parameters.showErrorsInFormattedOutput.Value; @@ -104,6 +105,7 @@ private void InitializeGroupBy() { label = labelKey as string; } + _groupingManager = new GroupingInfoManager(); _groupingManager.Initialize(groupingKeyExpression, label); return; @@ -117,6 +119,7 @@ private void InitializeGroupBy() { return; } + if (gb.startGroup == null || gb.startGroup.expression == null) { return; @@ -164,6 +167,7 @@ internal virtual FormatStartData GenerateStartData(PSObject so) { startFormat.autosizeInfo = new AutosizeInfo(); } + return startFormat; } @@ -263,6 +267,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int controlGenerator.GenerateFormatEntries(maxTreeDepth, control, firstObjectInGroup, startGroup.groupingEntry.formatValueList); } + return startGroup; } @@ -310,6 +315,7 @@ internal bool IsObjectApplicable(Collection typeNames) result = IsObjectApplicable(typesWithoutPrefix); } } + return result; } @@ -319,12 +325,14 @@ protected bool AutoSize { get { return _autosize; } } + private bool _autosize = false; protected bool RepeatHeader { get { return _repeatHeader; } } + private bool _repeatHeader = false; protected class DataBaseInfo @@ -388,6 +396,7 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS } } } + return retVal; } @@ -404,6 +413,7 @@ protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionTo { _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so); } + return retVal; } @@ -446,6 +456,7 @@ protected FormatPropertyField GenerateFormatPropertyField(List form { fpf.propertyValue = string.Empty; } + return fpf; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index 9fcba4ac8e5..c3d918b7b48 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -129,6 +129,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, ExecuteFormatControlBody(level, so, complexBody, formatValueList); return true; } + return false; } @@ -154,6 +155,7 @@ private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(Com return x; } } + if (match.BestMatch != null) { return match.BestMatch as ComplexControlEntryDefinition; @@ -171,6 +173,7 @@ private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(Com return x; } } + if (match.BestMatch != null) { return match.BestMatch as ComplexControlEntryDefinition; @@ -210,6 +213,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, fe.formatValueList.Add(ftf); continue; } + var newline = t as NewLineToken; if (newline != null) { @@ -217,8 +221,10 @@ private void ExecuteFormatTokenList(TraversalInfo level, { fe.formatValueList.Add(new FormatNewLine()); } + continue; } + FrameToken ft = t as FrameToken; if (ft != null) { @@ -281,6 +287,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { val = string.Empty; } + FieldFormattingDirective fieldFormattingDirective = null; StringFormatError formatErrorObject = null; if (cpt.control != null) @@ -303,6 +310,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, // nothing to process continue; } + fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, _enumerationLimit, formatErrorObject, _expressionFactory); @@ -316,6 +324,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } + if (formatErrorObject != null && formatErrorObject.exception != null) { _errorManager.LogStringFormatError(formatErrorObject); @@ -329,6 +338,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { continue; } + IEnumerable e = PSObjectHelper.GetEnumerable(val); if (cpt.enumerateCollection && e != null) { @@ -369,6 +379,7 @@ private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToke { _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so); } + return retVal; } @@ -390,6 +401,7 @@ internal TraversalInfo(int level, int maxDepth) } internal int Level { get { return _level; } } + internal int MaxDepth { get { return _maxDepth; } } internal TraversalInfo NextLevel @@ -619,6 +631,7 @@ private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List= 0) { if (_enumerationLimit == enumCount) @@ -626,8 +639,10 @@ private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List GetActiveTableRowDefinition(TableControlBod break; } } + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; @@ -403,6 +411,7 @@ private List GetActiveTableRowDefinition(TableControlBod break; } } + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; @@ -436,6 +445,7 @@ private List GetActiveTableRowDefinition(TableControlBod // use the override activeRowItemDefinitionList.Add(rowItem); } + col++; } @@ -472,9 +482,11 @@ private TableRowEntry GenerateTableRowEntryFromFromProperties(PSObject so, int e { directive = activeAssociationList[k].OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } + fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, this.activeAssociationList[k].ResolvedExpression, directive); tre.formatPropertyFieldList.Add(fpf); } + return tre; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs index c251d6c7dc2..6d7882df456 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -98,6 +98,7 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr return x; } } + if (match.BestMatch != null) { return match.BestMatch as WideControlEntryDefinition; @@ -115,6 +116,7 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr return x; } } + if (match.BestMatch != null) { return match.BestMatch as WideControlEntryDefinition; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 7ac0ae5d5d3..e4eeed93f85 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -30,6 +30,7 @@ internal static bool IsTypeInList(Collection typeNames) // check if the type is derived from a System.Enum // e.g. in C# // enum Foo { Red, Black, Green} + if (PSObjectHelper.PSObjectIsEnum(typeNames)) return true; @@ -111,6 +112,7 @@ internal void Initialize(TerminatingErrorContext errorContext, { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } + if (view != null) { // we got a matching view from the database @@ -151,6 +153,7 @@ internal void Initialize(TerminatingErrorContext errorContext, { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName); } + if (view != null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( @@ -162,6 +165,7 @@ internal void Initialize(TerminatingErrorContext errorContext, s_formatViewBindingTracer.WriteLine(viewFound); return; } + s_formatViewBindingTracer.WriteLine(viewNotFound); // illegal input, we have to terminate ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape); @@ -172,6 +176,7 @@ internal void Initialize(TerminatingErrorContext errorContext, { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } + if (view != null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( @@ -185,6 +190,7 @@ internal void Initialize(TerminatingErrorContext errorContext, return; } + s_formatViewBindingTracer.WriteLine(viewNotFound); // we just select properties out of the object itself _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); @@ -439,6 +445,7 @@ private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape { viewGenerator = new ComplexViewGenerator(); } + Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters); @@ -465,6 +472,7 @@ internal static bool IsPropertyLessObject(PSObject so) { return true; } + if (allProperties.Count == 3) { foreach (MshResolvedExpressionParameterAssociation property in allProperties) @@ -479,6 +487,7 @@ internal static bool IsPropertyLessObject(PSObject so) return true; } + if (allProperties.Count == 4) { foreach (MshResolvedExpressionParameterAssociation property in allProperties) @@ -494,6 +503,7 @@ internal static bool IsPropertyLessObject(PSObject so) return true; } + if (allProperties.Count == 5) { foreach (MshResolvedExpressionParameterAssociation property in allProperties) @@ -534,6 +544,7 @@ internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext er { outOfBandViewGenerator = new ListViewGenerator(); } + outOfBandViewGenerator.Initialize(errorContext, expressionFactory, db, view, null); } else @@ -667,6 +678,7 @@ internal List DrainFailedResultList() if (errorRecord != null) retVal.Add(errorRecord); } + _formattingErrorList.Clear(); return retVal; } @@ -707,6 +719,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) formattingError.formatString); errorRecord.ErrorDetails = new ErrorDetails(msg); } + return errorRecord; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index bd1d82f9249..75fee263755 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -89,6 +89,7 @@ internal void WriteToXml(IEnumerable typeDefinitions) { formatdefs.Add(viewdefinition.InstanceId, viewdefinition); } + viewList.Add(typedefinition); } } @@ -108,6 +109,7 @@ internal void WriteToXml(IEnumerable typeDefinitions) { _writer.WriteElementString("TypeName", definition.TypeName); } + _writer.WriteEndElement(/**/); var groupBy = formatdef.Control.GroupBy; @@ -119,12 +121,15 @@ internal void WriteToXml(IEnumerable typeDefinitions) { _writer.WriteElementString("Label", groupBy.Label); } + if (groupBy.CustomControl != null) { WriteCustomControl(groupBy.CustomControl); } + _writer.WriteEndElement(/**/); } + if (formatdef.Control.OutOfBand) { _writer.WriteElementString("OutOfBand", string.Empty); @@ -133,6 +138,7 @@ internal void WriteToXml(IEnumerable typeDefinitions) formatdef.Control.WriteToXml(this); _writer.WriteEndElement(/**/); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); @@ -145,6 +151,7 @@ internal void WriteTableControl(TableControl tableControl) { _writer.WriteElementString("AutoSize", string.Empty); } + if (tableControl.HideTableHeaders) { _writer.WriteElementString("HideTableHeaders", string.Empty); @@ -158,16 +165,20 @@ internal void WriteTableControl(TableControl tableControl) { _writer.WriteElementString("Label", columnheader.Label); } + if (columnheader.Width > 0) { _writer.WriteElementString("Width", columnheader.Width.ToString(CultureInfo.InvariantCulture)); } + if (columnheader.Alignment != Alignment.Undefined) { _writer.WriteElementString("Alignment", columnheader.Alignment.ToString()); } + _writer.WriteEndElement(/**/); } + _writer.WriteEndElement(/**/); _writer.WriteStartElement("TableRowEntries"); @@ -179,10 +190,12 @@ internal void WriteTableControl(TableControl tableControl) _writer.WriteStartElement("Wrap"); _writer.WriteEndElement(/**/); } + if (row.SelectedBy != null) { WriteEntrySelectedBy(row.SelectedBy); } + _writer.WriteStartElement("TableColumnItems"); foreach (TableControlColumn coldefn in row.Columns) { @@ -191,10 +204,12 @@ internal void WriteTableControl(TableControl tableControl) { _writer.WriteElementString("Alignment", coldefn.Alignment.ToString()); } + if (!string.IsNullOrEmpty(coldefn.FormatString)) { _writer.WriteElementString("FormatString", coldefn.FormatString); } + WriteDisplayEntry(coldefn.DisplayEntry); _writer.WriteEndElement(/**/); } @@ -202,6 +217,7 @@ internal void WriteTableControl(TableControl tableControl) _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); @@ -277,6 +293,7 @@ private void WriteEntrySelectedBy(EntrySelectedBy entrySelectedBy) _writer.WriteElementString("TypeName", typename); } } + if (entrySelectedBy.SelectionCondition != null) { foreach (var condition in entrySelectedBy.SelectionCondition) @@ -286,6 +303,7 @@ private void WriteEntrySelectedBy(EntrySelectedBy entrySelectedBy) _writer.WriteEndElement(/**/); } } + _writer.WriteEndElement(/**/); } } @@ -317,10 +335,12 @@ internal void WriteWideControl(WideControl wideControl) { _writer.WriteElementString("FormatString", entry.FormatString); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); @@ -354,9 +374,11 @@ internal void WriteCustomControl(CustomControl customControl) { WriteCustomItem(item); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); } @@ -370,6 +392,7 @@ internal void WriteCustomItem(CustomItemBase item) { _writer.WriteElementString("NewLine", string.Empty); } + return; } @@ -426,6 +449,7 @@ internal void WriteCustomItem(CustomItemBase item) { WriteCustomItem(frameItem); } + _writer.WriteEndElement(/**/); _writer.WriteEndElement(/**/); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index 93606da509d..76d33b1aca1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -54,6 +54,7 @@ fid is GroupEndData || { return false; } + string classId = GetProperty(so, FormatInfoData.classidProperty) as string; if (classId == null) @@ -224,14 +225,17 @@ internal FormatInfoData DeserializeMemberObject(PSObject so, string property) errorRecord.ErrorDetails = new ErrorDetails(msg); this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } + return DeserializeObject(PSObject.AsPSObject(memberRaw)); } + internal FormatInfoData DeserializeMandatoryMemberObject(PSObject so, string property) { FormatInfoData fid = DeserializeMemberObject(so, property); VerifyDataNotNull(fid, property); return fid; } + private object DeserializeMemberVariable(PSObject so, string property, System.Type t, bool cannotBeNull) { object objRaw = GetProperty(so, property); @@ -251,6 +255,7 @@ private object DeserializeMemberVariable(PSObject so, string property, System.Ty errorRecord.ErrorDetails = new ErrorDetails(msg); this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } + return objRaw; } @@ -285,6 +290,7 @@ internal int DeserializeIntMemberVariable(PSObject so, string property) { return (int)DeserializeMemberVariable(so, property, typeof(int), true /* cannotBeNull */); } + internal bool DeserializeBoolMemberVariable(PSObject so, string property) { return (bool)DeserializeMemberVariable(so, property, typeof(bool), true /* cannotBeNull */); @@ -403,6 +409,7 @@ internal static FormatInfoData CreateInstance(PSObject so, FormatObjectDeseriali errorRecord.ErrorDetails = new ErrorDetails(msg); deserializer.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } + FormatInfoData fid = CreateInstance(classId, deserializer); return fid; } @@ -416,6 +423,7 @@ private static FormatInfoData CreateInstance(string clsid, FormatObjectDeseriali CreateInstanceError(PSTraceSource.NewArgumentException("clsid"), clsid, deserializer); return null; } + try { FormatInfoData fid = ctor(); @@ -456,6 +464,7 @@ private static FormatInfoData CreateInstance(string clsid, FormatObjectDeseriali + e.GetType().FullName); throw; } + return null; } @@ -489,12 +498,14 @@ private static void ReadListHelper(IEnumerable en, List lst, FormatObjectDese lst.Add(entry); } } + internal static void ReadList(PSObject so, string property, List lst, FormatObjectDeserializer deserializer) { if (lst == null) { throw PSTraceSource.NewArgumentNullException("lst"); } + object memberRaw = FormatObjectDeserializer.GetProperty(so, property); ReadListHelper(PSObjectHelper.GetEnumerable(memberRaw), lst, deserializer); } @@ -547,6 +558,7 @@ internal override void Deserialize(PSObject so, FormatObjectDeserializer deseria this.autosizeInfo = (AutosizeInfo)deserializer.DeserializeMemberObject(so, "autosizeInfo"); } } + internal sealed partial class FormatEntryData : PacketInfoData { internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) @@ -667,6 +679,7 @@ internal override void Deserialize(PSObject so, FormatObjectDeserializer deseria this.alignment = deserializer.DeserializeIntMemberVariable(so, "alignment"); } } + internal sealed partial class FormatEntry : FormatValue { internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) @@ -676,6 +689,7 @@ internal override void Deserialize(PSObject so, FormatObjectDeserializer deseria this.frameInfo = (FrameInfo)deserializer.DeserializeMemberObject(so, "frameInfo"); } } + internal sealed partial class FrameInfo : FormatInfoData { internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 35f6bf998dd..f925ae9ad7e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -26,6 +26,7 @@ internal virtual int Length(string str) { return Length(str, 0); } + internal virtual int Length(string str, int offset) { return str.Length - offset; @@ -37,6 +38,7 @@ internal virtual int GetHeadSplitLength(string str, int displayCells) { return GetHeadSplitLength(str, 0, displayCells); } + internal virtual int GetHeadSplitLength(string str, int offset, int displayCells) { int len = str.Length - offset; @@ -47,6 +49,7 @@ internal virtual int GetTailSplitLength(string str, int displayCells) { return GetTailSplitLength(str, 0, displayCells); } + internal virtual int GetTailSplitLength(string str, int offset, int displayCells) { int len = str.Length - offset; @@ -99,6 +102,7 @@ protected int GetSplitLengthInternalHelper(string str, int offset, int displayCe k = (head) ? (k + 1) : (k - 1); } + return charactersAdded; } #endregion @@ -186,6 +190,7 @@ internal void StopProcessing() { _isStopping = true; } + private bool _isStopping; internal void CheckStopProcessing() diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index cb29f8974dc..2de56219e6f 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -100,6 +100,7 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC _propertyLabels[k] += Separator; } + _propertyLabelsDisplayLength += Separator.Length; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index 040ec8c810d..b0e1ddbb62c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -104,6 +104,7 @@ internal override void StopProcessing() { _lo.StopProcessing(); } + _isStopped = true; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index a47b18e5f4e..e0682a8a029 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -376,6 +376,7 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, sb.Append(scArray[col][row]); } } + rows[row] = sb.ToString(); } @@ -395,6 +396,7 @@ private StringCollection GenerateMultiLineRowField(string val, int k, int alignm sc[col] = GenerateRowField(sc[col], _si.columnInfo[k].width, alignment, dc, addPadding); } } + return sc; } @@ -439,6 +441,7 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display sb.Append(ResetConsoleVt100Code); } } + return sb.ToString(); } @@ -461,6 +464,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis { s = StringUtil.Padding(padCount) + s; } + break; case TextAlignment.Center: @@ -475,6 +479,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s += StringUtil.Padding(padRight); } } + break; default: @@ -485,6 +490,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s += StringUtil.Padding(padCount); } } + break; } } @@ -506,6 +512,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s = s.Substring(s.Length - tailCount); s = PSObjectHelper.Ellipsis + s; } + break; case TextAlignment.Center: @@ -514,6 +521,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s = s.Substring(0, dc.GetHeadSplitLength(s, truncationDisplayLength)); s += PSObjectHelper.Ellipsis; } + break; default: @@ -523,6 +531,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s = s.Substring(0, dc.GetHeadSplitLength(s, truncationDisplayLength)); s += PSObjectHelper.Ellipsis; } + break; } } @@ -539,6 +548,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis int tailCount = dc.GetTailSplitLength(s, len); s = s.Substring(s.Length - tailCount, tailCount); } + break; case TextAlignment.Center: @@ -546,6 +556,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis // get from "abcdef" to "a" s = s.Substring(0, dc.GetHeadSplitLength(s, len)); } + break; default: @@ -554,6 +565,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis // get from "abcdef" to "a" s = s.Substring(0, dc.GetHeadSplitLength(s, len)); } + break; } } @@ -567,12 +579,14 @@ private static string GenerateRowField(string val, int width, int alignment, Dis { return s; } + switch (alignment) { case TextAlignment.Right: { s = " " + s; } + break; case TextAlignment.Center: @@ -582,6 +596,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s += " "; } } + break; default: @@ -592,6 +607,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis s += " "; } } + break; } From 67324c1def979937a494b656b4e40f699ba46fd1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:01 -0800 Subject: [PATCH 52/81] Update DefaultFormatters --- .../DotNetTypes_format_ps1xml.cs | 19 +++++++++++++++++++ .../DefaultFormatters/HelpV3_format_ps1xml.cs | 2 ++ .../PowerShellCore_format_ps1xml.cs | 13 +++++++++++++ .../Registry_format_ps1xml.cs | 1 + 4 files changed, 35 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs index b5deb6b4892..b1472ee100a 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs @@ -877,6 +877,7 @@ private static IEnumerable ViewsOf_Microsoft_Management_In $sourceName = $_.PSComputerName; if($sourceName -eq ""."") {$sourceName = $env:COMPUTERNAME;} + return $sourceName; ") .AddPropertyColumn("Address") @@ -907,26 +908,35 @@ private static IEnumerable ViewsOf_System_Management_Manag $eventType = $_.EventType; if($_.EventType -eq 100) {$eventType = ""BEGIN_SYSTEM_CHANGE"";} + if($_.EventType -eq 101) {$eventType = ""END_SYSTEM_CHANGE"";} + if($_.EventType -eq 102) {$eventType = ""BEGIN_NESTED_SYSTEM_CHANGE"";} + if($_.EventType -eq 103) {$eventType = ""END_NESTED_SYSTEM_CHANGE"";} + return $eventType; ") .AddScriptBlockColumn(@" $RestorePointType = $_.RestorePointType; if($_.RestorePointType -eq 0) { $RestorePointType = ""APPLICATION_INSTALL"";} + if($_.RestorePointType -eq 1) { $RestorePointType = ""APPLICATION_UNINSTALL"";} + if($_.RestorePointType -eq 10) { $RestorePointType = ""DEVICE_DRIVER_INSTALL"";} + if($_.RestorePointType -eq 12) { $RestorePointType = ""MODIFY_SETTINGS"";} + if($_.RestorePointType -eq 13) { $RestorePointType = ""CANCELLED_OPERATION"";} + return $RestorePointType; ") .EndRowDefinition() @@ -952,26 +962,35 @@ private static IEnumerable ViewsOf_Microsoft_Management_In $eventType = $_.EventType; if($_.EventType -eq 100) {$eventType = ""BEGIN_SYSTEM_CHANGE"";} + if($_.EventType -eq 101) {$eventType = ""END_SYSTEM_CHANGE"";} + if($_.EventType -eq 102) {$eventType = ""BEGIN_NESTED_SYSTEM_CHANGE"";} + if($_.EventType -eq 103) {$eventType = ""END_NESTED_SYSTEM_CHANGE"";} + return $eventType; ") .AddScriptBlockColumn(@" $RestorePointType = $_.RestorePointType; if($_.RestorePointType -eq 0) { $RestorePointType = ""APPLICATION_INSTALL"";} + if($_.RestorePointType -eq 1) { $RestorePointType = ""APPLICATION_UNINSTALL"";} + if($_.RestorePointType -eq 10) { $RestorePointType = ""DEVICE_DRIVER_INSTALL"";} + if($_.RestorePointType -eq 12) { $RestorePointType = ""MODIFY_SETTINGS"";} + if($_.RestorePointType -eq 13) { $RestorePointType = ""CANCELLED_OPERATION"";} + return $RestorePointType; ") .EndRowDefinition() diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs index d1d5a16477b..bf3205a8372 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs @@ -100,9 +100,11 @@ internal static IEnumerable GetFormatData() .AddScriptBlockExpressionBinding(@"function GetParam { if(-not $_.Parameters) { return $null } + $_.Parameters.Parameter | ForEach-Object { if($_.type) { $param = ""[$($_.type.name)] `$$($_.name), "" } else { $param = ""[object] `$$($_.name), "" } + $params += $param } diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 6293c65e558..a71c9770080 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -25,6 +25,7 @@ internal static IEnumerable GetFormatData() .AddScriptBlockExpressionBinding(@" $header = "" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"" if($_.Path) { $header = "" "" + [Microsoft.PowerShell.Commands.UtilityResources]::FormatHexPathPrefix + $_.Path + ""`r`n`r`n"" + $header } + $header ") .EndFrame() @@ -738,14 +739,17 @@ private static IEnumerable ViewsOf_System_Management_Autom { $myinv.MyCommand.Path + "" : "" } + break } + ([System.Management.Automation.CommandTypes]::Script) { if ($myinv.MyCommand.ScriptBlock) { $myinv.MyCommand.ScriptBlock.ToString() + "" : "" } + break } default @@ -761,6 +765,7 @@ private static IEnumerable ViewsOf_System_Management_Autom { $myinv.InvocationName + "" : "" } + break } } @@ -796,6 +801,7 @@ private static IEnumerable ViewsOf_System_Management_Autom $indent = 4 $errorCategoryMsg = & { Set-StrictMode -Version 1; $_.ErrorCategory_Message } + if ($null -ne $errorCategoryMsg) { $indentString = ""+ CategoryInfo : "" + $_.ErrorCategory_Message @@ -804,12 +810,14 @@ private static IEnumerable ViewsOf_System_Management_Autom { $indentString = ""+ CategoryInfo : "" + $_.CategoryInfo } + $posmsg += ""`n"" + $indentString $indentString = ""+ FullyQualifiedErrorId : "" + $_.FullyQualifiedErrorId $posmsg += ""`n"" + $indentString $originInfo = & { Set-StrictMode -Version 1; $_.OriginInfo } + if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) { $indentString = ""+ PSComputerName : "" + $originInfo.PSComputerName @@ -1213,10 +1221,12 @@ private static IEnumerable ViewsOf_ModuleInfoGrouping(Cust { $editions = @('Desktop') } + foreach ($edition in $editions) { $result += $edition.Substring(0,4) } + ($result | Sort-Object) -join ','") .AddScriptBlockColumn("$_.ExportedCommands.Keys") .EndRowDefinition() @@ -1299,12 +1309,14 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co $result = $_.Content $result = $result.Substring(0, [Math]::Min($result.Length, 200) ) if($result.Length -eq 200) { $result += ""`u{2026}"" } + $result ", label: "Content") .AddItemScriptBlock(@" $result = $_.RawContent $result = $result.Substring(0, [Math]::Min($result.Length, 200) ) if($result.Length -eq 200) { $result += ""`u{2026}"" } + $result ", label: "RawContent") .AddItemProperty(@"Headers") @@ -1329,6 +1341,7 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co $result = $_.RawContent $result = $result.Substring(0, [Math]::Min($result.Length, 200) ) if($result.Length -eq 200) { $result += ""`u{2026}"" } + $result ", label: "RawContent") .AddItemProperty(@"Headers") diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs index 0d067e419c7..52a5cd8e4b1 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs @@ -46,6 +46,7 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co Format-List | Out-String | Sort).Trim() $result = $result.Substring(0, [Math]::Min($result.Length, 5000) ) if($result.Length -eq 5000) { $result += ""`u{2026}"" } + $result ") .EndRowDefinition() From e7feed4c126736693b853588bbe51f9cdb3a1453 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:01 -0800 Subject: [PATCH 53/81] Update out-console --- .../out-console/ConsoleLineOutput.cs | 14 ++++++++++++++ .../FormatAndOutput/out-console/OutConsole.cs | 2 ++ 2 files changed, 16 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index c6ed4bd3712..efc87b5bab8 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -33,6 +33,7 @@ internal override int Length(string str, int offset) { len += this.Length(str[k]); } + return len; } @@ -47,6 +48,7 @@ internal override int GetHeadSplitLength(string str, int offset, int displayCell { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } + internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); @@ -62,8 +64,10 @@ internal string GenerateTestString(string str) { sb.Append('_'); } + sb.Append(ch); } + return sb.ToString(); } @@ -94,8 +98,10 @@ internal override int Length(string str, int offset) //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } + return string.IsNullOrEmpty(str) ? 0 : str.Length - offset; } + internal override int Length(string str) { try @@ -107,8 +113,10 @@ internal override int Length(string str) //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } + return string.IsNullOrEmpty(str) ? 0 : str.Length; } + internal override int Length(char character) { try @@ -120,6 +128,7 @@ internal override int Length(char character) //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } + return 1; } @@ -127,6 +136,7 @@ internal override int GetHeadSplitLength(string str, int offset, int displayCell { return GetSplitLengthInternalHelper(str, offset, displayCells, true); } + internal override int GetTailSplitLength(string str, int offset, int displayCells) { return GetSplitLengthInternalHelper(str, offset, displayCells, false); @@ -173,6 +183,7 @@ internal override int ColumnNumber //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } + return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber; } } @@ -198,6 +209,7 @@ internal override int RowNumber //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } + return _fallbackRawConsoleRowNumber; } } @@ -396,12 +408,14 @@ private void LineWrittenEvent() // reset the counter, since we are starting a new page _linesWritten = 0; } + break; case PromptHandler.PromptResponse.NextLine: { // roll back the counter by one, since we allow one more line _linesWritten--; } + break; case PromptHandler.PromptResponse.Quit: // 1021203-2005/05/09-JonN diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 4941689a433..d75d6daa0b2 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -135,6 +135,7 @@ protected override void EndProcessing() { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Add(item); } + _outVarResults = null; } @@ -196,6 +197,7 @@ public OutHostCommand() public SwitchParameter Paging { get { return _paging; } + set { _paging = value; } } From 2d7222799dae19b1cc681f89abefa7ad03b82f29 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:01 -0800 Subject: [PATCH 54/81] Update out-textInterface --- .../FormatAndOutput/out-textInterface/OutTextInterface.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs index d8e2ec02198..b28da726e89 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs @@ -25,6 +25,7 @@ public class OutLineOutputCommand : FrontEndCommandBase public object LineOutput { get { return _lineOutput; } + set { _lineOutput = value; } } @@ -52,6 +53,7 @@ protected override void BeginProcessing() { ProcessWrongTypeLineOutput(_lineOutput); } + ((OutCommandInner)this.implementation).LineOutput = lo; base.BeginProcessing(); From 8baf40d8cb4635229ae425ed41e390773930f58e Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:02 -0800 Subject: [PATCH 55/81] Update DisplayDatabase --- .../common/DisplayDatabase/XmlLoaderBase.cs | 4 ++ .../common/DisplayDatabase/commands.cs | 3 + .../DisplayDatabase/displayDescriptionData.cs | 13 +++++ .../displayDescriptionData_Complex.cs | 4 ++ .../displayDescriptionData_List.cs | 2 + .../displayDescriptionData_Table.cs | 4 ++ .../displayDescriptionData_Wide.cs | 1 + .../displayResourceManagerCache.cs | 4 ++ .../common/DisplayDatabase/typeDataManager.cs | 3 + .../common/DisplayDatabase/typeDataQuery.cs | 25 ++++++++ .../DisplayDatabase/typeDataXmlLoader.cs | 58 +++++++++++++++++++ .../typeDataXmlLoader_Complex.cs | 16 +++++ .../DisplayDatabase/typeDataXmlLoader_List.cs | 8 +++ .../typeDataXmlLoader_Table.cs | 10 ++++ .../typeDataXmlLoader_Views.cs | 6 ++ .../DisplayDatabase/typeDataXmlLoader_Wide.cs | 8 +++ 16 files changed, 169 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index e51bdc29e6f..3ad868c7425 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -424,6 +424,7 @@ internal bool MatchAttributeName(XmlAttribute a, string s) ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s)); return true; } + return false; } @@ -607,6 +608,7 @@ protected string ComputeCurrentXPath() path.Insert(1, sf.node.Name); } } + return path.Length > 0 ? path.ToString() : null; } @@ -677,10 +679,12 @@ protected void SetDatabaseLoadingInfo(XmlFileLoadInfo info) _loadingInfo.fileDirectory = info.fileDirectory; _loadingInfo.filePath = info.filePath; } + protected void SetLoadingInfoIsFullyTrusted(bool isFullyTrusted) { _loadingInfo.isFullyTrusted = isFullyTrusted; } + protected void SetLoadingInfoIsProductCode(bool isProductCode) { _loadingInfo.isProductCode = isProductCode; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs index 865af22db51..53bb79f5f3b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs @@ -20,16 +20,19 @@ internal static bool Convert(string expansionString, out EnumerableExpansion exp expansion = EnumerableExpansion.CoreOnly; return true; } + if (String.Equals(expansionString, EnumOnlyString, StringComparison.OrdinalIgnoreCase)) { expansion = EnumerableExpansion.EnumOnly; return true; } + if (String.Equals(expansionString, BothString, StringComparison.OrdinalIgnoreCase)) { expansion = EnumerableExpansion.Both; return true; } + return false; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index 4b1478925ff..e63c71fef67 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -109,6 +109,7 @@ internal bool MultilineTables _multilineTables = value; } } + get { if (_multilineTables.HasValue) @@ -116,6 +117,7 @@ internal bool MultilineTables return false; } } + private bool? _multilineTables; internal FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); @@ -137,6 +139,7 @@ internal bool ShowErrorsAsMessages _showErrorsAsMessages = value; } } + get { if (_showErrorsAsMessages.HasValue) @@ -144,6 +147,7 @@ internal bool ShowErrorsAsMessages return false; } } + private bool? _showErrorsAsMessages; /// @@ -159,6 +163,7 @@ internal bool ShowErrorsInFormattedOutput _showErrorsInFormattedOutput = value; } } + get { if (_showErrorsInFormattedOutput.HasValue) @@ -166,6 +171,7 @@ internal bool ShowErrorsInFormattedOutput return false; } } + private bool? _showErrorsInFormattedOutput; /// @@ -192,6 +198,7 @@ internal int PropertyCountForTable _propertyCountForTable = value; } } + get { if (_propertyCountForTable.HasValue) @@ -199,6 +206,7 @@ internal int PropertyCountForTable return 4; } } + private int? _propertyCountForTable; internal List formatShapeSelectionOnTypeList = new List(); @@ -370,18 +378,22 @@ internal static string GetControlShapeName(ControlBase control) { return FormatShape.Table.ToString(); } + if (control is ListControlBody) { return FormatShape.List.ToString(); } + if (control is WideControlBody) { return FormatShape.Wide.ToString(); } + if (control is ComplexControlBody) { return FormatShape.Complex.ToString(); } + return string.Empty; } @@ -848,6 +860,7 @@ internal static EntrySelectedBy Get(IEnumerable entrySelectedByType, IEn if (result.TypeNames.Count > 0) isEmpty = false; } + if (entrySelectedByCondition != null) { result.SelectionCondition = new List(entrySelectedByCondition); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index 5c049e7167e..e6fdf90a873 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -202,10 +202,12 @@ internal static CustomItemBase Create(FormatToken token) { frame.FirstLineHanging = (uint)-firstLine; } + foreach (var frameItemToken in frameToken.itemDefinition.formatTokenList) { frame.CustomItems.Add(CustomItemBase.Create(frameItemToken)); } + return frame; } @@ -446,6 +448,7 @@ public CustomEntryBuilder EndFrame() { throw PSTraceSource.NewInvalidOperationException(); } + _entryStack.Pop(); return this; } @@ -457,6 +460,7 @@ public CustomControlBuilder EndEntry() { throw PSTraceSource.NewInvalidOperationException(); } + _entryStack.Pop(); return _controlBuilder; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index eec2379bf69..cbfafa65d1c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -230,6 +230,7 @@ internal ListControlEntry(ListControlEntryDefinition entrydefn) { EntrySelectedBy = EntrySelectedBy.Get(entrydefn.appliesTo.referenceList); } + foreach (ListControlItemDefinition itemdefn in entrydefn.itemDefinitionList) { Items.Add(new ListControlEntryItem(itemdefn)); @@ -317,6 +318,7 @@ internal ListControlEntryItem(ListControlItemDefinition definition) { Label = definition.label.text; } + FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; if (fpt != null) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index 13be4995d45..eb80ba95ced 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -336,6 +336,7 @@ internal TableControlColumnHeader(TableColumnHeaderDefinition colheaderdefinitio { Label = colheaderdefinition.label.text; } + Alignment = (Alignment)colheaderdefinition.alignment; Width = colheaderdefinition.width; } @@ -442,6 +443,7 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() { SelectedBy = EntrySelectedBy.Get(rowdefinition.appliesTo.referenceList); } + foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList) { FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken; @@ -592,11 +594,13 @@ public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerab { row.SelectedBy.TypeNames = new List(entrySelectedByType); } + if (entrySelectedByCondition != null) { row.SelectedBy.SelectionCondition = new List(entrySelectedByCondition); } } + _table.Rows.Add(row); return new TableRowDefinitionBuilder(this, row); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 3e4ed05b2bb..7898e725ede 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -163,6 +163,7 @@ public WideControl(IEnumerable wideEntries, uint columns) { this.Entries.Add(entryItem); } + this.Columns = columns; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 4f0e2ea0f05..8370292ac90 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -12,6 +12,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class DisplayResourceManagerCache { internal enum LoadingResult { NoError, AssemblyNotFound, ResourceNotFound, StringNotFound } + internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath }; internal string GetTextTokenString(TextToken tt) @@ -22,6 +23,7 @@ internal string GetTextTokenString(TextToken tt) if (resString != null) return resString; } + return tt.text; } @@ -109,6 +111,7 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo Diagnostics.Assert(false, "ResourceManagerCache.GetResourceString unexpected exception " + e.GetType().FullName); throw; } + return null; } @@ -128,6 +131,7 @@ private Assembly LoadAssemblyFromResourceReference(StringResourceReference resou foundInGac = false; // it always be false, since we return already loaded assemblies return _assemblyNameResolver.ResolveAssemblyName(resourceReference.assemblyName); } + private sealed class AssemblyLoadResult { internal Assembly a; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index be89b343461..de5243f78a8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -182,6 +182,7 @@ internal void AddFormatData(IEnumerable formatData, bool return; } } + lock (_formatFileList) { foreach (string formatFile in _formatFileList) @@ -191,6 +192,7 @@ internal void AddFormatData(IEnumerable formatData, bool filesToLoad.Add(fileToLoad); } } + if (!shouldPrepend) { foreach (ExtendedTypeDefinition typeDefinition in formatData) @@ -353,6 +355,7 @@ internal bool LoadFromFile( } } } + return success; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 3316761067a..28519c1288d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -24,6 +24,7 @@ internal static bool Evaluate(PSObject obj, PSPropertyExpression ex, out PSPrope expressionResult = res[0]; return false; } + return LanguagePrimitives.IsTrue(res[0].Result); } } @@ -40,6 +41,7 @@ internal TypeMatchItem(object obj, AppliesTo a) Item = obj; AppliesTo = a; } + internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject) { Item = obj; @@ -48,7 +50,9 @@ internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject) } internal object Item { get; } + internal AppliesTo AppliesTo { get; } + internal PSObject CurrentObject { get; } } @@ -78,6 +82,7 @@ internal static void SetTracer(PSTraceSource t) { s_activeTracer = t; } + internal static void ResetTracer() { s_activeTracer = s_classTracer; @@ -112,6 +117,7 @@ internal bool PerfectMatch(TypeMatchItem item) _bestMatchIndex = match; _bestMatchItem = item; } + return _bestMatchIndex == BestMatchIndexPerfect; } @@ -158,6 +164,7 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex); } } + if (currentMatch == BestMatchIndexPerfect) return currentMatch; @@ -184,8 +191,10 @@ private int ComputeBestMatchInGroup(TypeGroupDefinition tgd, PSObject currentObj { best = currentMatch; } + k++; } + return best; } @@ -201,10 +210,12 @@ private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyEx { return k; } + if (k == 0 && !_useInheritance) break; k++; } + return BestMatchIndexUndefined; } @@ -219,6 +230,7 @@ private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) { _failedResultsList.Add(expressionResult); } + return retVal; } @@ -258,6 +270,7 @@ internal static void SetTracer(PSTraceSource t) { s_activeTracer = t; } + internal static void ResetTracer() { s_activeTracer = s_classTracer; @@ -274,6 +287,7 @@ internal static EnumerableExpansion GetEnumerableExpansionFromType(PSPropertyExp return expansionDirective.enumerableExpansion; } } + if (match.BestMatch != null) { return ((EnumerableExpansionDirective)(match.BestMatch)).enumerableExpansion; @@ -304,6 +318,7 @@ internal static FormatShape GetShapeFromType(PSPropertyExpressionFactory express return shapeSelOnType.formatShape; } } + if (match.BestMatch != null) { return ((FormatShapeSelectionOnType)(match.BestMatch)).formatShape; @@ -360,6 +375,7 @@ internal static ViewDefinition GetViewByShapeAndType(PSPropertyExpressionFactory Diagnostics.Assert(false, "unknown shape: this should never happen unless a new shape is added"); return null; } + return GetView(expressionFactory, db, t, typeNames, viewName); } @@ -406,6 +422,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact ControlBase.GetControlShapeName(vd.mainControl), (vd != null ? vd.name : string.Empty)); continue; } + if (IsOutOfBandView(vd)) { ActiveTracer.WriteLine( @@ -413,6 +430,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } + if (vd.appliesTo == null) { ActiveTracer.WriteLine( @@ -445,6 +463,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact { TypeMatch.ResetTracer(); } + TraceHelper(vd, false); } @@ -486,6 +505,7 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} GROUP: {2}", ControlBase.GetControlShapeName(vd.mainControl), vd.name, tgr.name); } + ActiveTracer.WriteLine(sb.ToString()); } } @@ -498,6 +518,7 @@ private static ViewDefinition GetBestMatch(TypeMatch match) { TraceHelper(bestMatchedVD, true); } + return bestMatchedVD; } @@ -517,6 +538,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } + if (vd.appliesTo == null) { ActiveTracer.WriteLine( @@ -524,6 +546,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } + try { TypeMatch.SetTracer(ActiveTracer); @@ -537,6 +560,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express { TypeMatch.ResetTracer(); } + TraceHelper(vd, false); } // this is the best match we had @@ -647,6 +671,7 @@ private static ControlBody ResolveControlReferenceInList(ControlReference contro if (String.Compare(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase) == 0) return x.controlBody; } + return null; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 18d26fc483a..54b4fd3479b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -18,6 +18,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class XmlFileLoadInfo { internal XmlFileLoadInfo() { } + internal XmlFileLoadInfo(string dir, string path, ConcurrentBag errors, string psSnapinName) { fileDirectory = dir; @@ -25,6 +26,7 @@ internal XmlFileLoadInfo(string dir, string path, ConcurrentBag errors, this.errors = errors; this.psSnapinName = psSnapinName; } + internal string fileDirectory = null; internal string filePath = null; internal ConcurrentBag errors; @@ -250,9 +252,11 @@ internal bool LoadXmlFile( catch (Exception e) // will rethrow { //Error in file {0}: {1} + this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message)); throw; } + if (this.HasErrors) { return false; @@ -309,10 +313,12 @@ internal bool LoadFormattingData( catch (Exception e) // will rethrow { //Error in formatting data "{0}": {1} + this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFormattingData, typeDefinition.TypeName, e.Message), typeDefinition.TypeName); throw; } + if (this.HasErrors) { return false; @@ -366,6 +372,7 @@ private void LoadData(XmlDocument doc, TypeInfoDataBase db) { ProcessDuplicateNode(n); } + typeGroupsFound = true; LoadTypeGroups(db, n); } @@ -375,6 +382,7 @@ private void LoadData(XmlDocument doc, TypeInfoDataBase db) { ProcessDuplicateNode(n); } + viewDefinitionsFound = true; LoadViewDefinitions(db, n); } @@ -384,6 +392,7 @@ private void LoadData(XmlDocument doc, TypeInfoDataBase db) { ProcessDuplicateNode(n); } + controlDefinitionsFound = true; LoadControlDefinitions(n, db.formatControlDefinitionHolder.controlDefinitionList); } @@ -506,6 +515,7 @@ private ViewDefinition LoadViewFromObjectModel(List typeNames, FormatVie { view.groupBy.startGroup.labelTextToken = new TextToken { text = control.GroupBy.Label }; } + if (control.GroupBy.CustomControl != null) { view.groupBy.startGroup.control = LoadCustomControlFromObjectModel(control.GroupBy.CustomControl, viewIndex, firstTypeName); @@ -670,6 +680,7 @@ private void LoadColumnEntriesFromObjectModel(TableRowDefinition trd, List
LoadEnumerableExpansionDirectiveList( this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.EnumerableExpansionNode)); return null; // fatal error } + retVal.Add(eed); } else @@ -1239,6 +1262,7 @@ private List LoadEnumerableExpansionDirectiveList( } } } + return retVal; } @@ -1278,6 +1302,7 @@ private EnumerableExpansionDirective LoadEnumerableExpansionDirective(XmlNode di { return null; //fatal } + bool success = EnumerableExpansionConversion.Convert(s, out eed.enumerableExpansion); if (!success) { @@ -1291,6 +1316,7 @@ private EnumerableExpansionDirective LoadEnumerableExpansionDirective(XmlNode di this.ProcessUnknownNode(n); } } + return eed; } } @@ -1466,6 +1492,7 @@ private TypeReference LoadTypeReference(XmlNode n) tr.name = val; return tr; } + return null; } @@ -1479,6 +1506,7 @@ private TypeGroupReference LoadTypeGroupReference(XmlNode n) tgr.name = val; return tgr; } + return null; } @@ -1505,6 +1533,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi this.ProcessDuplicateAlternateNode(n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); return null; } + typeGroupFound = true; TypeGroupReference tgr = LoadTypeGroupReference(n); if (tgr != null) @@ -1523,6 +1552,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi this.ProcessDuplicateAlternateNode(n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); return null; } + typeFound = true; TypeReference tr = LoadTypeReference(n); if (tr != null) @@ -1541,6 +1571,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi this.ProcessDuplicateNode(n); return null; // fatal error } + expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return null; // fatal error @@ -1573,6 +1604,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi { return null; // fatal error } + return retVal; } // failure: expression is mandatory @@ -1610,6 +1642,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) this.ProcessDuplicateNode(n); return null; // fatal error } + expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return null; // fatal error @@ -1621,6 +1654,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } + controlFound = true; if (!controlMatch.ProcessNode(n)) return null; // fatal error @@ -1632,6 +1666,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } + labelFound = true; labelTextToken = LoadLabel(n); @@ -1661,6 +1696,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ControlLabelWithoutExpression, ComputeCurrentXPath(), FilePath)); return null; // fatal error } + if (controlFound) { groupBy.startGroup.control = controlMatch.Control; @@ -1679,6 +1715,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) { return null; // fatal error } + groupBy.startGroup.expression = expression; return groupBy; } @@ -1706,6 +1743,7 @@ private TextToken LoadTextToken(XmlNode n) { return null; } + if (tt.resource != null) { // inner text is optional @@ -1783,11 +1821,13 @@ private StringResourceReference LoadResourceAttributes(XmlAttributeCollection at ReportMissingAttribute(XmlTags.AssemblyNameAttribute); return null; } + if (resource.baseName == null) { ReportMissingAttribute(XmlTags.BaseNameAttribute); return null; } + if (resource.resourceId == null) { ReportMissingAttribute(XmlTags.ResourceIdAttribute); @@ -1824,17 +1864,20 @@ private void ReportStringResourceFailure(StringResourceReference resource, { assemblyDisplayName = resource.assemblyLocation; } + break; case DisplayResourceManagerCache.AssemblyBindingStatus.FoundInGac: { //"(Global Assembly Cache) {0}" assemblyDisplayName = StringUtil.Format(FormatAndOutXmlLoadingStrings.AssemblyInGAC, resource.assemblyName); } + break; default: { assemblyDisplayName = resource.assemblyName; } + break; } @@ -1846,12 +1889,14 @@ private void ReportStringResourceFailure(StringResourceReference resource, //Error at XPath {0} in file {1}: Assembly {2} is not found. msg = StringUtil.Format(FormatAndOutXmlLoadingStrings.AssemblyNotFound, ComputeCurrentXPath(), FilePath, assemblyDisplayName); } + break; case DisplayResourceManagerCache.LoadingResult.ResourceNotFound: { //Error at XPath {0} in file {1}: Resource {2} in assembly {3} is not found. msg = StringUtil.Format(FormatAndOutXmlLoadingStrings.ResourceNotFound, ComputeCurrentXPath(), FilePath, resource.baseName, assemblyDisplayName); } + break; case DisplayResourceManagerCache.LoadingResult.StringNotFound: { @@ -1859,8 +1904,10 @@ private void ReportStringResourceFailure(StringResourceReference resource, msg = StringUtil.Format(FormatAndOutXmlLoadingStrings.StringResourceNotFound, ComputeCurrentXPath(), FilePath, resource.resourceId, resource.baseName, assemblyDisplayName); } + break; } + this.ReportError(msg); } @@ -1890,6 +1937,7 @@ internal bool VerifyScriptBlock(string scriptBlockText) Diagnostics.Assert(false, "TypeInfoBaseLoader.VerifyScriptBlock unexpected exception " + e.GetType().FullName); throw; } + return true; } @@ -1902,6 +1950,7 @@ internal ExpressionNodeMatch(TypeInfoDataBaseLoader loader) { _loader = loader; } + internal bool MatchNode(XmlNode n) { return _loader.MatchNodeName(n, XmlTags.PropertyNameNode) || _loader.MatchNodeName(n, XmlTags.ScriptBlockNode); @@ -1929,6 +1978,7 @@ internal bool ProcessNode(XmlNode n) _fatalError = true; return false; // fatal error } + return true; } else if (_loader.MatchNodeName(n, XmlTags.ScriptBlockNode)) @@ -1958,6 +2008,7 @@ internal bool ProcessNode(XmlNode n) _fatalError = true; return false; // fatal error } + return true; } // this should never happen if the API is used correctly @@ -1980,6 +2031,7 @@ internal ExpressionToken GenerateExpressionToken() _loader.ReportMissingNodes(new string[] { XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode }); return null; } + return _token; } @@ -2021,6 +2073,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u _loader.ProcessDuplicateNode(n); return false; // fatal error } + expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return false; // fatal error @@ -2049,6 +2102,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u _loader.ProcessDuplicateNode(n); return false; // fatal error } + textNodeFound = true; textToken = _loader.LoadText(n); if (textToken == null) @@ -2087,6 +2141,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u { _formatString = formatString; } + _expression = expression; } else @@ -2111,7 +2166,9 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u } internal string FormatString { get { return _formatString; } } + internal TextToken TextToken { get { return _textToken; } } + internal ExpressionToken Expression { get { return _expression; } } private string _formatString; @@ -2153,6 +2210,7 @@ internal bool ProcessNode(XmlNode n) { return false; } + ControlReference controlRef = new ControlReference(); controlRef.name = name; controlRef.controlType = typeof(ComplexControlBody); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs index 45788280ec2..6122de3d60c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs @@ -52,6 +52,7 @@ private ComplexControlBody LoadComplexControl(XmlNode controlNode) this.ReportMissingNode(XmlTags.ComplexEntriesNode); return null; // fatal error } + return complexBody; } } @@ -99,6 +100,7 @@ private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, Comple this.ProcessUnknownNode(n); } } + if (complexBody.defaultEntry == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. @@ -138,6 +140,7 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinition(XmlNode this.ProcessDuplicateNode(n); return null; //fatal } + bodyNodeFound = true; cced.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n); } @@ -259,6 +262,7 @@ private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase this.ProcessDuplicateNode(n); return false; // fatal error } + expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return false; // fatal error @@ -282,6 +286,7 @@ private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase this.ProcessDuplicateNode(n); return false; } + itemSelectionConditionNodeFound = true; condition = LoadItemSelectionCondition(n); if (condition == null) @@ -367,6 +372,7 @@ private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } + complexControlFound = true; if (!controlMatch.ProcessNode(n)) return null; // fatal error @@ -378,6 +384,7 @@ private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; // fatal error } + fieldControlFound = true; fieldControlBody = new FieldControlBody(); fieldControlBody.fieldFormattingDirective.formatString = GetMandatoryInnerText(n); @@ -426,6 +433,7 @@ private NewLineToken LoadNewLine(XmlNode newLineNode, int index) { return null; } + NewLineToken nlt = new NewLineToken(); return nlt; @@ -458,6 +466,7 @@ private int LoadIntegerValue(XmlNode node, out bool success) { return retVal; } + string val = this.GetMandatoryInnerText(node); if (val == null) @@ -492,6 +501,7 @@ private int LoadPositiveOrZeroIntegerValue(XmlNode node, out bool success) this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectNaturalNumber, ComputeCurrentXPath(), FilePath)); success = false; } + return val; } } @@ -550,6 +560,7 @@ private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; } + firstLineIndentFound = true; frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success); @@ -563,6 +574,7 @@ private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; } + firstLineHangingFound = true; frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success); @@ -578,6 +590,7 @@ private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) this.ProcessDuplicateNode(n); return null; //fatal } + itemNodeFound = true; frame.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n); } @@ -592,12 +605,14 @@ private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) this.ProcessDuplicateAlternateNode(XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; // fatal error } + if (frame.itemDefinition.formatTokenList == null) { //MissingNode=Error at XPath {0} in file {1}: Missing Node {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, XmlTags.ComplexItemNode)); return null; } + return frame; } } @@ -610,6 +625,7 @@ private bool ReadBooleanNode(XmlNode collectionElement, out bool val) { return false; } + string s = collectionElement.InnerText; if (string.IsNullOrEmpty(s)) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs index 61c9fc9672d..c86d2ff01e1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs @@ -51,6 +51,7 @@ private ListControlBody LoadListControl(XmlNode controlNode) this.ReportMissingNode(XmlTags.ListEntriesNode); return null; // fatal error } + return listBody; } } @@ -98,6 +99,7 @@ private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody this.ProcessUnknownNode(n); } } + if (listBody.optionalEntryList == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. @@ -177,6 +179,7 @@ private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, Xml lved.itemDefinitionList = null; return; //fatal } + lved.itemDefinitionList.Add(lvid); } else @@ -195,6 +198,7 @@ private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, Xml } } } + private ListControlItemDefinition LoadListControlItemDefinition(XmlNode propertyEntryNode) { using (this.StackFrame(propertyEntryNode)) @@ -222,6 +226,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property this.ProcessDuplicateNode(n); return null; // fatal error } + itemSelectionConditionNodeFound = true; condition = LoadItemSelectionCondition(n); if (condition == null) @@ -236,6 +241,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property this.ProcessDuplicateNode(n); return null; // fatal error } + labelNodeFound = true; labelToken = LoadLabel(n); if (labelToken == null) @@ -270,6 +276,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property fpt.fieldFormattingDirective.formatString = match.FormatString; lvid.formatTokenList.Add(fpt); } + return lvid; } } @@ -290,6 +297,7 @@ private ExpressionToken LoadItemSelectionCondition(XmlNode itemNode) this.ProcessDuplicateNode(n); return null; // fatal error } + expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index 5722ae457d0..d7bf74de66d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -47,12 +47,14 @@ private ControlBase LoadTableControl(XmlNode controlNode) this.ProcessDuplicateNode(n); return null; // fatal error } + autosizeNodeFound = true; bool tempVal; if (!this.ReadBooleanNode(n, out tempVal)) { return null; // fatal error } + tableBody.autosize = tempVal; } else if (MatchNodeName(n, XmlTags.TableHeadersNode)) @@ -135,6 +137,7 @@ private ControlBase LoadTableControl(XmlNode controlNode) return null; // fatal error } + k++; } } @@ -240,6 +243,7 @@ private TableColumnHeaderDefinition LoadColumnHeaderDefinition(XmlNode columnHea this.ProcessUnknownNode(n); } } + return chd; } } @@ -257,6 +261,7 @@ private bool ReadPositiveIntegerValue(XmlNode n, out int val) this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectPositiveInteger, ComputeCurrentXPath(), FilePath)); return false; } + return true; } @@ -287,6 +292,7 @@ private bool LoadAlignmentValue(XmlNode n, out int alignmentValue) this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidAlignmentValue, ComputeCurrentXPath(), FilePath, alignmentString)); return false; // fatal error } + return true; } @@ -333,6 +339,7 @@ private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntrie this.ProcessUnknownNode(n); } } + if (tableBody.defaultDefinition == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. @@ -372,6 +379,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde this.ProcessDuplicateNode(n); return null; //fatal } + LoadColumnEntries(n, trd); if (trd.rowItemDefinitionList == null) { @@ -385,6 +393,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde this.ProcessDuplicateNode(n); return null; //fatal } + multiLineFound = true; if (!this.ReadBooleanNode(n, out trd.multiLine)) { @@ -396,6 +405,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde this.ProcessUnknownNode(n); } } + return trd; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index cde33e4a85a..ec8cb393b20 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -83,6 +83,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) ProcessDuplicateNode(n); return null; } + mainControlFound = true; view.mainControl = LoadTableControl(n); } @@ -93,6 +94,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) ProcessDuplicateNode(n); return null; } + mainControlFound = true; view.mainControl = LoadListControl(n); } @@ -104,6 +106,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) ProcessDuplicateNode(n); return null; } + mainControlFound = true; view.mainControl = LoadWideControl(n); } @@ -114,6 +117,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) ProcessDuplicateNode(n); return null; } + mainControlFound = true; view.mainControl = LoadComplexControl(n); } @@ -166,6 +170,7 @@ private bool LoadMainControlDependentData(List unprocessedNodes, ViewDe { return false; } + if (!(view.mainControl is ComplexControlBody) && !(view.mainControl is ListControlBody)) { //Error at XPath {0} in file {1}: Out Of Band views can only have CustomControl or ListControl. @@ -189,6 +194,7 @@ private bool LoadMainControlDependentData(List unprocessedNodes, ViewDe ProcessUnknownNode(n); } } + return true; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs index 116353e2307..0b8d35eca25 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs @@ -34,12 +34,14 @@ private WideControlBody LoadWideControl(XmlNode controlNode) this.ProcessDuplicateAlternateNode(n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } + autosizeNodeFound = true; bool tempVal; if (!this.ReadBooleanNode(n, out tempVal)) { return null; // fatal error } + wideBody.autosize = tempVal; } else if (MatchNodeName(n, XmlTags.ColumnNumberNode)) @@ -49,6 +51,7 @@ private WideControlBody LoadWideControl(XmlNode controlNode) this.ProcessDuplicateAlternateNode(n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } + columnsNodeFound = true; if (!ReadPositiveIntegerValue(n, out wideBody.columns)) @@ -85,11 +88,13 @@ private WideControlBody LoadWideControl(XmlNode controlNode) this.ProcessDuplicateAlternateNode(XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } + if (!wideViewEntriesFound) { this.ReportMissingNode(XmlTags.WideEntriesNode); return null; // fatal error } + return wideBody; } } @@ -136,6 +141,7 @@ private void LoadWideControlEntries(XmlNode wideControlEntriesNode, WideControlB this.ProcessUnknownNode(n); } } + if (wideBody.defaultEntryDefinition == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. @@ -195,6 +201,7 @@ private WideControlEntryDefinition LoadWideControlEntry(XmlNode wideControlEntry this.ReportMissingNode(XmlTags.WideItemNode); return null; //fatal error } + return wved; } } @@ -233,6 +240,7 @@ private List LoadPropertyEntry(XmlNode propertyEntryNode) fpt.fieldFormattingDirective.formatString = match.FormatString; formatTokenList.Add(fpt); } + return formatTokenList; } } From f5f05d871795b727df7ea8671b5f2553275effc1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:02 -0800 Subject: [PATCH 56/81] Update Utilities --- .../FormatAndOutput/common/Utilities/MshObjectUtil.cs | 10 ++++++++++ .../FormatAndOutput/common/Utilities/MshParameter.cs | 5 +++++ .../common/Utilities/MshParameterAssociation.cs | 2 ++ .../FormatAndOutput/common/Utilities/Mshexpression.cs | 6 ++++++ 4 files changed, 23 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index e895f84aa50..f263ff672ba 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -304,6 +304,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex { throw new PipelineStoppedException(); } + if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) @@ -311,6 +312,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex sb.Append(Ellipsis); break; } + enumCount++; } @@ -318,6 +320,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex { sb.Append(", "); } + sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) first = false; @@ -331,6 +334,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex { throw new PipelineStoppedException(); } + if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) @@ -338,6 +342,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex sb.Append(Ellipsis); break; } + enumCount++; } @@ -345,12 +350,14 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex { sb.Append(", "); } + sb.Append(GetObjectName(x, expressionFactory)); if (first) first = false; } } } + sb.Append("}"); return sb.ToString(); } @@ -367,6 +374,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } + return string.Empty; } } @@ -466,6 +474,7 @@ private static List GetDefaultPropertySet(PSMemberSet stan retVal.Add(new PSPropertyExpression(prop)); } } + return retVal; } } @@ -553,6 +562,7 @@ internal static string GetExpressionDisplayValue( { return string.Empty; } + return PSObjectHelper.FormatField(directive, result.Result, enumerationLimit, formatErrorObject, expressionFactory); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index 1c27af3c1dd..e675dd25f6e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -359,6 +359,7 @@ private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invo // bad type error ProcessIllegalHashTableKeyValue(invocationContext, currentStringKey, e.Value.GetType(), def.AllowedTypes); } + retVal.Add(def.KeyName, e.Value); } @@ -421,6 +422,7 @@ private static void ProcessUnknownParameterType(TerminatingErrorContext invocati msg = StringUtil.Format(FormatAndOut_MshParameter.NullParameterTypeError, allowedTypesList); } + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyUnknownType", msg); } @@ -497,6 +499,7 @@ private static string CatenateTypeArray(Type[] arr) { strings[k] = arr[k].FullName; } + return CatenateStringArray(strings); } @@ -510,8 +513,10 @@ internal static string CatenateStringArray(string[] arr) { sb.Append(", "); } + sb.Append(arr[k]); } + sb.Append("}"); return sb.ToString(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index 033dfd4d3b8..451dc094130 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -142,6 +142,7 @@ private static List GetPropertyNamesFromView(PSObject source, PSMemberVi { retVal.Add(member.Name); } + return retVal; } @@ -165,6 +166,7 @@ internal static List ExpandAll(PSObje retVal.Add(new MshResolvedExpressionParameterAssociation(null, expr)); } } + return retVal; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index f4841a843bc..abd825b00b8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -74,6 +74,7 @@ public PSPropertyExpression(string s, bool isResolved) { throw PSTraceSource.NewArgumentNullException("s"); } + _stringValue = s; _isResolved = isResolved; } @@ -89,6 +90,7 @@ public PSPropertyExpression(ScriptBlock scriptBlock) { throw PSTraceSource.NewArgumentNullException("scriptBlock"); } + Script = scriptBlock; } @@ -180,11 +182,13 @@ public List ResolveNames(PSObject target, bool expand) // to attempt the binding whether it's in there or not. x = new PSDynamicMember(_stringValue); } + List temp = new List(); if (x != null) { temp.Add(x); } + members = temp; } @@ -322,6 +326,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) classScope: (Type) null, @static: false)); } + result = _getValueDynamicSite.Target.Invoke(_getValueDynamicSite, target); } @@ -348,6 +353,7 @@ private PSObject IfHashtableWrapAsPSCustomObject(PSObject target) { target = (PSObject)(LanguagePrimitives.ConvertPSObjectToType(targetAsHash, typeof(PSObject), false, null, true)); } + return target; } From 0e3a4c73b11826b3b63512c8f2c09740e18a19f3 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:02 -0800 Subject: [PATCH 57/81] Update COM --- src/System.Management.Automation/engine/COM/ComInvoker.cs | 3 +++ src/System.Management.Automation/engine/COM/ComMethod.cs | 1 + src/System.Management.Automation/engine/COM/ComProperty.cs | 5 +++++ src/System.Management.Automation/engine/COM/ComTypeInfo.cs | 4 ++++ src/System.Management.Automation/engine/COM/ComUtil.cs | 5 +++++ 5 files changed, 18 insertions(+) diff --git a/src/System.Management.Automation/engine/COM/ComInvoker.cs b/src/System.Management.Automation/engine/COM/ComInvoker.cs index d1428c802d3..a3d326e4bde 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -241,6 +241,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ { Marshal.FreeBSTR(info.bstrSource); } + if (info.bstrHelpFile != IntPtr.Zero) { Marshal.FreeBSTR(info.bstrHelpFile); @@ -280,6 +281,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ { VariantClear(variantArgArray + s_variantSize * i); } + Marshal.FreeCoTaskMem(variantArgArray); } @@ -296,6 +298,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ { VariantClear(tmpVariants + s_variantSize * i); } + Marshal.FreeCoTaskMem(tmpVariants); } } diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index c727cdd8563..ea2c61dc64c 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -127,6 +127,7 @@ internal object InvokeMethod(PSMethod method, object[] arguments) method.Name, arguments.Length, ce.Message); } } + return null; } } diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 70d2b556bfb..27b7e9c8625 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -262,6 +262,7 @@ internal void SetValue(Object target, Object setValue, Object[] arguments) { finalArguments[i] = newarguments[i]; } + finalArguments[newarguments.Length] = Adapter.PropertySetAndMethodArgumentConvertTo(setValue, Type, CultureInfo.InvariantCulture); try @@ -310,6 +311,7 @@ internal void UpdateFuncDesc(COM.FUNCDESC desc, int index) { IsParameterized = true; } + break; case COM.INVOKEKIND.INVOKE_PROPERTYPUT: @@ -320,6 +322,7 @@ internal void UpdateFuncDesc(COM.FUNCDESC desc, int index) { IsParameterized = true; } + break; case COM.INVOKEKIND.INVOKE_PROPERTYPUTREF: @@ -329,6 +332,7 @@ internal void UpdateFuncDesc(COM.FUNCDESC desc, int index) { IsParameterized = true; } + break; } } @@ -366,6 +370,7 @@ public override string ToString() { builder.Append("{get} "); } + if (_hasSetter) { builder.Append("{set} "); diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index ba35cc769b9..a2a56bfcf9a 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -165,9 +165,11 @@ internal static ComTypeInfo GetDispatchTypeInfo(object comObject) //We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface. typeinfo = GetDispatchTypeInfoFromCoClassTypeInfo(typeinfo); } + result = new ComTypeInfo(typeinfo); } } + return result; } @@ -256,6 +258,7 @@ internal static COM.ITypeInfo GetDispatchTypeInfoFromCustomInterfaceTypeInfo(COM throw; } } + return dispinfo; } @@ -298,6 +301,7 @@ internal static COM.ITypeInfo GetDispatchTypeInfoFromCoClassTypeInfo(COM.ITypeIn } } } + return null; } } diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index af38ed12f1e..dd1cc8bcb39 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -91,6 +91,7 @@ internal static string GetMethodSignatureFromFuncDesc(COM.ITypeInfo typeinfo, CO } } } + builder.Append(")"); return builder.ToString(); @@ -131,6 +132,7 @@ private static string GetStringFromCustomType(COM.ITypeInfo typeinfo, IntPtr ref custtypeinfo.GetDocumentation(-1, out strName, out strDoc, out id, out strHelp); return strName; } + return "UnknownCustomtype"; } @@ -270,6 +272,7 @@ private static ComMethodInformation GetMethodInformation(COM.FUNCDESC funcdesc, break; } } + return new ComMethodInformation(false, hasOptional, parameters, returntype, funcdesc.memid, funcdesc.invkind); } @@ -284,6 +287,7 @@ internal static ParameterInformation[] GetParameterInformation(COM.FUNCDESC func Diagnostics.Assert(cParams > 0, "skipLastParameter is only true for property setters where there is at least one parameter"); cParams--; } + ParameterInformation[] parameters = new ParameterInformation[cParams]; IntPtr ElementDescriptionArrayPtr = funcdesc.lprgelemdescParam; @@ -351,6 +355,7 @@ internal static ComMethodInformation[] GetMethodInformationArray(COM.ITypeInfo t returnValue[count++] = ComUtil.GetMethodInformation(funcdesc, skipLastParameters); typeInfo.ReleaseFuncDesc(pFuncDesc); } + return returnValue; } } From 11244223cd1a4a82c3fa0c28dd8a1371d57f4d9e Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:04 -0800 Subject: [PATCH 58/81] Update ComInterop --- .../engine/ComInterop/ComBinder.cs | 1 + .../engine/ComInterop/ComBinderHelpers.cs | 1 + .../engine/ComInterop/ComInvokeAction.cs | 1 + .../engine/ComInterop/ComInvokeBinder.cs | 6 +++++ .../engine/ComInterop/ComMethodDesc.cs | 1 + .../engine/ComInterop/ComRuntimeHelpers.cs | 25 +++++++++++++++++++ .../engine/ComInterop/ComTypeClassDesc.cs | 3 +++ .../engine/ComInterop/ComTypeDesc.cs | 5 ++++ .../ComInterop/DispCallableMetaObject.cs | 1 + .../engine/ComInterop/ExcepInfo.cs | 1 + .../engine/ComInterop/Helpers.cs | 1 + .../engine/ComInterop/IDispatchComObject.cs | 8 ++++++ .../engine/ComInterop/TypeUtils.cs | 19 ++++++++++++++ .../engine/ComInterop/VarEnumSelector.cs | 4 +++ .../engine/ComInterop/Variant.cs | 22 ++++++++++++++++ .../engine/ComInterop/VariantArray.cs | 1 + .../engine/ComInterop/VariantBuilder.cs | 2 ++ 17 files changed, 102 insertions(+) diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs index 1ed522a9ade..cb8fc8e8978 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs @@ -62,6 +62,7 @@ public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject in result.Restrictions ); } + return true; } else diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs index 4a5cbf7105d..af35c44a24d 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs @@ -133,6 +133,7 @@ internal static BindingRestrictions GetTypeRestrictionForDynamicMetaObject(Dynam //If the meta object holds a null value, create an instance restriction for checking null return BindingRestrictions.GetInstanceRestriction(obj.Expression, null); } + return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.LimitType); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs index 3be7fdbd528..b40e5fe43eb 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs @@ -81,6 +81,7 @@ public override Expression Bind(object[] args, ReadOnlyCollection(); } + _sourceItfs.AddLast(itfName); } else @@ -67,6 +69,7 @@ private void AddInterface(ComTypes.ITypeInfo itfTypeInfo, bool isSourceItf) { _itfs = new LinkedList(); } + _itfs.AddLast(itfName); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index 78a57c49426..4ccff52b85e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -27,6 +27,7 @@ internal ComTypeDesc(ITypeInfo typeInfo, ComType memberType, ComTypeLibDesc type { ComRuntimeHelpers.GetInfoFromType(typeInfo, out _typeName, out _documentation); } + TypeLib = typeLibDesc; } @@ -84,6 +85,7 @@ internal bool TryGetFunc(string name, out ComMethodDesc method) method = Funcs[name] as ComMethodDesc; return true; } + method = null; return false; } @@ -105,6 +107,7 @@ internal bool TryGetPut(string name, out ComMethodDesc method) method = Puts[name] as ComMethodDesc; return true; } + method = null; return false; } @@ -126,9 +129,11 @@ internal bool TryGetPutRef(string name, out ComMethodDesc method) method = _putRefs[name] as ComMethodDesc; return true; } + method = null; return false; } + internal void AddPutRef(string name, ComMethodDesc method) { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs index 43d6ea67bc9..d83025aca0e 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs @@ -52,6 +52,7 @@ private DynamicMetaObject BindGetOrInvoke(DynamicMetaObject[] args, CallInfo cal bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(method, ref args, temps, initTemps); return BindComInvoke(method, args, callInfo, isByRef, temps, initTemps); } + return null; } diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index 95a2285bf80..1db1b1cd50e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -101,6 +101,7 @@ internal Exception GetException() { helpLink += "#" + _dwHelpContext; } + exception.HelpLink = helpLink; return exception; diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 353a89fe74b..908c5a18c2a 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -18,6 +18,7 @@ internal static Expression Convert(Expression expression, Type type) { return expression; } + return Expression.Convert(expression, type); } } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index 8f7b4c85070..f8d25849514 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -283,6 +283,7 @@ internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method { method = putref; } + return true; } else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) @@ -458,6 +459,7 @@ private void EnsureScanDefinedEvents() _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } + _comTypeDesc.Events = events; } } @@ -480,6 +482,7 @@ private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref D { continue; } + if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { continue; @@ -641,8 +644,10 @@ private void EnsureScanDefinedMethods() { setItem = method; } + continue; } + if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0) { // If there is a getter for this put, use that ReturnType as the @@ -659,6 +664,7 @@ private void EnsureScanDefinedMethods() { setItem = method; } + continue; } @@ -674,6 +680,7 @@ private void EnsureScanDefinedMethods() { ((ComMethodDesc)puts[name]).InputType = method.ReturnType; } + if (putrefs.ContainsKey(name)) { ((ComMethodDesc)putrefs[name]).InputType = method.ReturnType; @@ -709,6 +716,7 @@ private void EnsureScanDefinedMethods() _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } + _comTypeDesc.Funcs = funcs; _comTypeDesc.Puts = puts; _comTypeDesc.PutRefs = putrefs; diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index 1a4a949b804..078da6759b4 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -21,6 +21,7 @@ internal static Type GetNonNullableType(Type type) { return type.GetGenericArguments()[0]; } + return type; } @@ -38,10 +39,12 @@ internal static bool AreReferenceAssignable(Type dest, Type src) { return true; } + if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { return true; } + return false; } //CONFORMING @@ -51,14 +54,17 @@ internal static bool AreAssignable(Type dest, Type src) { return true; } + if (dest.IsAssignableFrom(src)) { return true; } + if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { return true; } + if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) @@ -67,6 +73,7 @@ internal static bool AreAssignable(Type dest, Type src) { return true; } + return false; } @@ -98,6 +105,7 @@ internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type c { return method; } + MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); if (method != null) @@ -114,6 +122,7 @@ internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type c return method; } } + return null; } @@ -131,6 +140,7 @@ internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typ continue; return mi; } + return null; } @@ -160,6 +170,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Byte: switch (tcDest) @@ -175,6 +186,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Int16: switch (tcDest) @@ -186,6 +198,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.UInt16: switch (tcDest) @@ -199,6 +212,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Int32: switch (tcDest) @@ -209,6 +223,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.UInt32: switch (tcDest) @@ -220,6 +235,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Int64: case TypeCode.UInt64: @@ -230,6 +246,7 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Char: switch (tcDest) @@ -244,10 +261,12 @@ private static bool IsImplicitNumericConversion(Type source, Type destination) case TypeCode.Decimal: return true; } + return false; case TypeCode.Single: return (tcDest == TypeCode.Double); } + return false; } diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index dfde14837d8..fca79d76ee4 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -223,6 +223,7 @@ private static List GetConversionsToComPrimitiveTypeFamilies(Type argum } } } + return compatibleComTypes; } @@ -249,6 +250,7 @@ private static void CheckForAmbiguousMatch(Type argumentType, List comp { typeNames += ", "; } + typeNames += typeName; } @@ -509,6 +511,7 @@ private static ArgBuilder GetByValArgBuilder(Type elementType, ref VarEnum eleme return new ConvertibleArgBuilder(); } } + return GetSimpleArgBuilder(elementType, elementVarEnum); } @@ -555,6 +558,7 @@ private static SimpleArgBuilder GetSimpleArgBuilder(Type elementType, VarEnum el { argBuilder = new ConvertArgBuilder(elementType, marshalType); } + break; } diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.cs b/src/System.Management.Automation/engine/ComInterop/Variant.cs index ab223317fe5..dcd3cc1347e 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.cs @@ -274,6 +274,7 @@ public VarEnum VariantType { return (VarEnum)_typeUnion._vt; } + set { _typeUnion._vt = (ushort)value; @@ -340,6 +341,7 @@ public SByte AsI1 Debug.Assert(VariantType == VarEnum.VT_I1); return _typeUnion._unionTypes._i1; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -363,6 +365,7 @@ public Int16 AsI2 Debug.Assert(VariantType == VarEnum.VT_I2); return _typeUnion._unionTypes._i2; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -386,6 +389,7 @@ public Int32 AsI4 Debug.Assert(VariantType == VarEnum.VT_I4); return _typeUnion._unionTypes._i4; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -409,6 +413,7 @@ public Int64 AsI8 Debug.Assert(VariantType == VarEnum.VT_I8); return _typeUnion._unionTypes._i8; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -432,6 +437,7 @@ public Byte AsUi1 Debug.Assert(VariantType == VarEnum.VT_UI1); return _typeUnion._unionTypes._ui1; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -455,6 +461,7 @@ public UInt16 AsUi2 Debug.Assert(VariantType == VarEnum.VT_UI2); return _typeUnion._unionTypes._ui2; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -478,6 +485,7 @@ public UInt32 AsUi4 Debug.Assert(VariantType == VarEnum.VT_UI4); return _typeUnion._unionTypes._ui4; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -501,6 +509,7 @@ public UInt64 AsUi8 Debug.Assert(VariantType == VarEnum.VT_UI8); return _typeUnion._unionTypes._ui8; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -524,6 +533,7 @@ public IntPtr AsInt Debug.Assert(VariantType == VarEnum.VT_INT); return _typeUnion._unionTypes._int; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -547,6 +557,7 @@ public UIntPtr AsUint Debug.Assert(VariantType == VarEnum.VT_UINT); return _typeUnion._unionTypes._uint; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -570,6 +581,7 @@ public Boolean AsBool Debug.Assert(VariantType == VarEnum.VT_BOOL); return _typeUnion._unionTypes._bool != 0; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -593,6 +605,7 @@ public Int32 AsError Debug.Assert(VariantType == VarEnum.VT_ERROR); return _typeUnion._unionTypes._error; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -616,6 +629,7 @@ public Single AsR4 Debug.Assert(VariantType == VarEnum.VT_R4); return _typeUnion._unionTypes._r4; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -639,6 +653,7 @@ public Double AsR8 Debug.Assert(VariantType == VarEnum.VT_R8); return _typeUnion._unionTypes._r8; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -665,6 +680,7 @@ public Decimal AsDecimal v._typeUnion._vt = 0; return v._decimal; } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -690,6 +706,7 @@ public Decimal AsCy Debug.Assert(VariantType == VarEnum.VT_CY); return Decimal.FromOACurrency(_typeUnion._unionTypes._cy); } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -713,6 +730,7 @@ public DateTime AsDate Debug.Assert(VariantType == VarEnum.VT_DATE); return DateTime.FromOADate(_typeUnion._unionTypes._date); } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -743,6 +761,7 @@ public string AsBstr return null; } } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -776,6 +795,7 @@ public Object AsUnknown return null; } } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -809,6 +829,7 @@ public Object AsDispatch return null; } } + set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise @@ -882,6 +903,7 @@ public void SetAsByrefVariantIndirect(ref Variant value) _typeUnion._unionTypes._byref = UnsafeMethods.ConvertIntPtrByrefToPtr(ref value._typeUnion._unionTypes._byref); break; } + VariantType = (value.VariantType | VarEnum.VT_BYREF); } diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index a1c8bf0e04f..d8c0a90384b 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -100,6 +100,7 @@ private static Type CreateCustomType(int size) { type.DefineField("Element" + i, T, FieldAttributes.Public); } + return type.CreateType(); } } diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index 958c6739542..a07f9b2b95b 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -134,6 +134,7 @@ internal Expression Clear() Debug.Assert(TempVariable != null); return Expression.Call(TempVariable, typeof(Variant).GetMethod("Clear")); } + return null; } @@ -164,6 +165,7 @@ internal Expression UpdateFromReturn(Expression parameter) { return null; } + return Expression.Assign( parameter, Helpers.Convert( From 3e07f3b536351166ea236f8cf2f76ddce674dd0f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:05 -0800 Subject: [PATCH 59/81] Update CommandCompletion --- .../CommandCompletion/CommandCompletion.cs | 10 ++ .../CommandCompletion/CompletionAnalysis.cs | 37 +++++ .../CommandCompletion/CompletionCompleters.cs | 142 ++++++++++++++++++ .../CommandCompletion/CompletionResult.cs | 4 + .../PseudoParameterBinder.cs | 16 ++ 5 files changed, 209 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index d5357001af8..c19e34fa685 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -554,6 +554,7 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr break; } } + SessionStateScope scopeToRestore = null; if (tupleForFrameToSkipPast != null) { @@ -564,11 +565,13 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr { scope = scope.Parent; } + if (scope != null) { context.EngineSessionState.CurrentScope = scope.Parent; } } + try { */ @@ -664,8 +667,10 @@ private static List InvokeLegacyTabExpansion(PowerShell powers oldResultStr = quote + oldResultStr + quote; } } + completionResult = new CompletionResult(oldResultStr); } + results.Add(completionResult); } } @@ -716,6 +721,7 @@ private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSp { return s_cmdletTabRegex.IsMatch(lastWord); } + if (cmdletParts.Length == 2) { isSnapinSpecified = PSSnapInInfo.IsPSSnapinIdValid(cmdletParts[0]); @@ -724,6 +730,7 @@ private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSp return s_cmdletTabRegex.IsMatch(cmdletParts[1]); } } + return false; } @@ -854,6 +861,7 @@ private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); previousMatched = false; } + i++; } } @@ -989,6 +997,7 @@ private static IEnumerable CombineMatchSets(List= 0 && value < _sentence.Length + 1, "value out of range"); diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 7fa1ec51773..87d6ff428bd 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -99,6 +99,7 @@ internal CompletionContext CreateCompletionContext(PowerShell powerShell) var typeInferenceContext = new TypeInferenceContext(powerShell); return InitializeCompletionContext(typeInferenceContext); } + internal CompletionContext CreateCompletionContext(TypeInferenceContext typeInferenceContext) { return InitializeCompletionContext(typeInferenceContext); @@ -136,6 +137,7 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI { typeInferenceContext.CurrentTypeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(asts.Last()); } + ExecutionContext executionContext = typeInferenceContext.ExecutionContext; return new CompletionContext @@ -255,6 +257,7 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To { errorStatement = last as ErrorStatementAst; if (errorStatement != null) { break; } + last = last.Parent; } @@ -273,6 +276,7 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To return true; } } + break; default: @@ -313,6 +317,7 @@ internal List GetResults(PowerShell powerShell, out int replac previousLanguageMode = completionContext.ExecutionContext.LanguageMode; completionContext.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } + return GetResultHelper(completionContext, out replacementIndex, out replacementLength, false); } finally @@ -394,6 +399,7 @@ internal List GetResultHelper(CompletionContext completionCont { result = CompletionCompleters.CompleteCommandParameter(completionContext); } + break; case TokenKind.Dot: @@ -438,6 +444,7 @@ internal List GetResultHelper(CompletionContext completionCont select new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)).ToList(); } } + break; case TokenKind.Comma: @@ -465,6 +472,7 @@ internal List GetResultHelper(CompletionContext completionCont bool unused; result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); } + break; case TokenKind.AtCurly: // Handle scenarios such as 'Sort-Object @{' and 'gci | Format-Table @{' @@ -481,6 +489,7 @@ internal List GetResultHelper(CompletionContext completionCont replacementIndex += 1; replacementLength = 0; } + break; case TokenKind.Number: @@ -496,6 +505,7 @@ internal List GetResultHelper(CompletionContext completionCont replacementIndex = completionContext.ReplacementIndex; replacementLength = completionContext.ReplacementLength; } + break; case TokenKind.Redirection: @@ -507,6 +517,7 @@ internal List GetResultHelper(CompletionContext completionCont completionContext.ReplacementLength = replacementLength = 0; result = new List(CompletionCompleters.CompleteFilename(completionContext)); } + break; case TokenKind.Minus: @@ -524,6 +535,7 @@ internal List GetResultHelper(CompletionContext completionCont result = CompletionCompleters.CompleteStatementFlags(statementKind, completionContext.WordToComplete); break; } + break; case TokenKind.DynamicKeyword: @@ -569,6 +581,7 @@ internal List GetResultHelper(CompletionContext completionCont bool unused; result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); } + break; } default: @@ -591,6 +604,7 @@ internal List GetResultHelper(CompletionContext completionCont replacementIndex = -1; replacementLength = -1; } + break; } } @@ -616,6 +630,7 @@ internal List GetResultHelper(CompletionContext completionCont // isLineContinuationBeforeCursor = completionContext.TokenBeforeCursor.Kind == TokenKind.LineContinuation; } + bool skipAutoCompleteForCommandCall = isCursorLineEmpty && !isLineContinuationBeforeCursor; bool lastAstIsExpressionAst = lastAst is ExpressionAst; if (!isQuotedString && @@ -733,6 +748,7 @@ internal List GetResultHelper(CompletionContext completionCont result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); } + break; default: break; @@ -870,6 +886,7 @@ private List GetResultForHashtable(CompletionContext completio } } } + hashTableAst = tempHashtableAst; if (hashTableAst != null) { @@ -877,6 +894,7 @@ private List GetResultForHashtable(CompletionContext completio completionContext.ReplacementLength = 0; return CompletionCompleters.CompleteHashtableKey(completionContext, hashTableAst); } + return null; } @@ -920,6 +938,7 @@ internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition if (typeName != null) return typeName; } + return null; } @@ -944,6 +963,7 @@ private static string GetFirstLineSubString(string stringToComplete, out bool ha hasNewLine = true; } } + return stringToComplete; } @@ -960,6 +980,7 @@ private Tuple GetHashEntryContainsCursor( keyValuePairWithCursor = kvp; break; } + if (!isCursorInString) { // @@ -1000,6 +1021,7 @@ private Tuple GetHashEntryContainsCursor( } } } + return keyValuePairWithCursor; } @@ -1078,6 +1100,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( { replacementIndex = completionContext.CursorPosition.Offset - replacementLength; } + completionContext.ReplacementIndex = replacementIndex; string matchString = stringToComplete + "*"; wildcardPattern = WildcardPattern.Get(matchString, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); @@ -1094,6 +1117,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( // Fallback to all allowed values matchedResults = orderedValues; } + foreach (var value in matchedResults) { string completionText = isCursorInString ? value : stringQuote + value + stringQuote; @@ -1137,6 +1161,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( } } } + var matchedResults = allResources.Where(r => wildcardPattern.IsMatch(r)); if (matchedResults == null || !matchedResults.Any()) { @@ -1163,6 +1188,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( } } } + return result; } @@ -1170,6 +1196,7 @@ private List GetResultForString(CompletionContext completionCo { // When it's the content of a quoted string, we only handle variable/member completion if (isQuotedString) { return null; } + var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); @@ -1299,6 +1326,7 @@ private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( { configureAst = Ast.GetAncestorAst(configureAst.Parent); } + return configureAst; } @@ -1368,6 +1396,7 @@ private List GetResultForIdentifierInConfiguration( { results = new List(); } + results.Add(new CompletionResult( keyword.Keyword, keyword.Keyword, @@ -1441,6 +1470,7 @@ private List GetResultForIdentifier(CompletionContext completi } } } + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); if (result != null) return result; @@ -1476,6 +1506,7 @@ private List GetResultForIdentifier(CompletionContext completi replacementIndex = cursorAst.Extent.StartScriptPosition.Offset; replacementLength += cursorAst.Extent.Text.Length; } + return result; } else @@ -1567,6 +1598,7 @@ private List GetResultForIdentifier(CompletionContext completi { result.AddRange(keywordResult); } + return result; } @@ -1579,12 +1611,14 @@ private List GetResultForIdentifier(CompletionContext completi if (isSingleDash) { if (isQuotedString) { return result; } + var res = CompletionCompleters.CompleteCommandParameter(completionContext); if (res.Count != 0) { return res; } } + return CompletionCompleters.CompleteCommandArgument(completionContext); } @@ -1653,6 +1687,7 @@ private List GetResultForIdentifier(CompletionContext completi replacementIndex += tokenAtCursorText.Length; replacementLength = 0; } + return result; } } @@ -1766,8 +1801,10 @@ private List GetResultForAttributeArgument(CompletionContext c property.PropertyType.ToString() + " " + property.Name)); } } + return result; } + return null; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index e6b7e4c3e96..141eaf25998 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -132,6 +132,7 @@ private static List CompleteCommand(CompletionContext context, { lastAst = lastAst.Parent; } + lastAst.Visit(findFunctionsVisitor); WildcardPattern commandNamePattern = WildcardPattern.Get(commandName, WildcardOptions.IgnoreCase); @@ -222,6 +223,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj name = name.Replace("`", "``"); name = name.Replace("$", "`$"); } + name = quoteInUse + name + quoteInUse; } else @@ -238,6 +240,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj { name = "& " + name; } + return new CompletionResult(name, listItem, CompletionResultType.Command, syntax); } @@ -260,6 +263,7 @@ internal static List MakeCommandsUnique(IEnumerable { // Skip the private commands if (commandInfo.Visibility == SessionStateEntryVisibility.Private) { continue; } + name = commandInfo.Name; if (includeModulePrefix && !string.IsNullOrEmpty(commandInfo.ModuleName)) { @@ -328,6 +332,7 @@ internal static List MakeCommandsUnique(IEnumerable } } } + results.Add(GetCommandNameCompletionResult(completionName, commandList[0], addAmpersandIfNecessary, quote)); // For the other commands that are hidden, we need to disambiguate, @@ -368,6 +373,7 @@ internal static List MakeCommandsUnique(IEnumerable } } } + results.Add(GetCommandNameCompletionResult(completionName, keyValuePair.Value, addAmpersandIfNecessary, quote)); } } @@ -495,11 +501,13 @@ internal static List CompleteCommandParameter(CompletionContex result.Add(new CompletionResult("-" + parameterName, parameterName, CompletionResultType.ParameterName, tooltip)); } } + if (result.Count > 0) { context.ReplacementLength = context.WordToComplete.Length; context.ReplacementIndex = lastAst.Extent.StartOffset; } + return result; } @@ -598,6 +606,7 @@ private static List GetParameterCompletionResults(string param bindingInfo.UnboundParameters, withColon); } + return result; } @@ -612,6 +621,7 @@ private static List GetParameterCompletionResults(string param bindingInfo.BoundParameters.Values, withColon); } + return result; } @@ -634,6 +644,7 @@ private static List GetParameterCompletionResults(string param return result; } } + break; case AstParameterArgumentType.Fake: { @@ -643,6 +654,7 @@ private static List GetParameterCompletionResults(string param matchedParameterName = entry.Key; } } + break; case AstParameterArgumentType.Switch: { @@ -652,6 +664,7 @@ private static List GetParameterCompletionResults(string param matchedParameterName = entry.Key; } } + break; case AstParameterArgumentType.AstArray: case AstParameterArgumentType.PipeObject: @@ -737,6 +750,7 @@ private static List GetParameterCompletionResults( } } } + if (showToUser) { string completionText = "-" + name + colonSuffix; @@ -762,6 +776,7 @@ where pattern.IsMatch(alias) { result.AddRange(commonParamResult); } + return result; } @@ -1028,6 +1043,7 @@ internal static List CompleteCommandArgument(CompletionContext result = GetArgumentCompletionResultsWithFailedPseudoBinding(context, argLocation, commandAst); break; } + parsedArgumentsProvidesMatch = true; } } @@ -1145,6 +1161,7 @@ internal static List CompleteCommandArgument(CompletionContext fileCompletionResults.AddRange(cmdletCompletionResults); } } + return fileCompletionResults; } finally @@ -1181,6 +1198,7 @@ internal static List CompleteCommandArgument(CompletionContext result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)); } + return result; } } @@ -1318,6 +1336,7 @@ internal static string ConcatenateStringPathArguments(CommandElementAst stringAs default: break; } + return quote + constantPathAst.Value + partialPath + quote; } else @@ -1452,6 +1471,7 @@ private static List GetArgumentCompletionResultsWithSuccessful MergedCompiledCommandParameter parameter = bindingInfo.BoundParameters[param]; ProcessParameter(bindingInfo.CommandName, commandAst, context, result, parameter, bindingInfo.BoundArguments); } + return result; } else if (!lastPositionalGetBound) @@ -1751,11 +1771,13 @@ private static void ProcessParameter( { realEntry = CodeGeneration.EscapeSingleQuotedStringContent(entry); } + completionText = quote + realEntry + quote; } result.Add(new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); } + result.Add(CompletionResult.Null); return; } @@ -1789,6 +1811,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType AstPair astPair = (AstPair)astParameterArgumentPair; argumentAst = astPair.Argument; } + break; case AstParameterArgumentType.PipeObject: @@ -1809,6 +1832,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType } } } + break; default: @@ -1849,11 +1873,13 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType { yield return new PSTypeName(pso.TypeNames[0]); } + if (!(pso.BaseObject is PSCustomObject)) { yield return new PSTypeName(pso.BaseObject.GetType()); } } + yield break; } } @@ -1929,6 +1955,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr break; } } + break; } default: @@ -2025,6 +2052,7 @@ private static void NativeCommandArgumentCompletion( NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result); break; } + if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var moduleNames = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Module"); @@ -2040,6 +2068,7 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result); } + break; } @@ -2070,6 +2099,7 @@ private static void NativeCommandArgumentCompletion( if (commandResults != null) result.AddRange(commandResults); } + break; } case "Clear-EventLog": @@ -2216,6 +2246,7 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionMemberName(context, result, commandAst); } + break; } case "Group-Object": @@ -2231,6 +2262,7 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionMemberName(context, result, commandAst); } + break; } case "Select-Object": @@ -2241,6 +2273,7 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionMemberName(context, result, commandAst); } + break; } @@ -2250,6 +2283,7 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionTypeName(context, result); } + break; } @@ -2294,8 +2328,10 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) { result[boundArgument.Key] = value; } + continue; } + var switchPair = boundArgument.Value as SwitchPair; if (switchPair != null) { @@ -2309,6 +2345,7 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) } } } + return result; } @@ -2496,6 +2533,7 @@ private static void NativeCompletionCimCommands( } } } + result.Add(CompletionResult.Null); } } @@ -2534,6 +2572,7 @@ private static IEnumerable NativeCompletionCimAssociationResultClassName cimClass = cimClass.CimSuperClass; } } + resultClassNames.Sort(StringComparer.OrdinalIgnoreCase); return resultClassNames.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); @@ -2610,10 +2649,12 @@ private static void NativeCompletionCimMethodName( { tooltipText.Append(", "); } + if (outParameter) { tooltipText.Append("[out] "); } + tooltipText.Append(CimInstanceAdapter.CimTypeToTypeNameDisplayString(methodParameter.CimType)); tooltipText.Append(" "); tooltipText.Append(methodParameter.Name); @@ -2623,6 +2664,7 @@ private static void NativeCompletionCimMethodName( continue; } } + tooltipText.Append(")"); localResults.Add(new CompletionResult(methodName, methodName, CompletionResultType.Method, tooltipText.ToString())); @@ -2647,6 +2689,7 @@ private static IEnumerable NativeCompletionCimClassName_GetClassNames(st result.Add(className); } } + return result; } @@ -2852,6 +2895,7 @@ private static void NativeCompletionEventLogCommands(CompletionContext context, { logName += "*"; } + var pattern = WildcardPattern.Get(logName, WildcardOptions.IgnoreCase); var powerShellExecutionHelper = context.Helper; @@ -2902,6 +2946,7 @@ private static void NativeCompletionJobCommands(CompletionContext context, strin { wordToComplete += "*"; } + var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); var paramIsName = paramName.Equals("Name", StringComparison.OrdinalIgnoreCase); @@ -2988,6 +3033,7 @@ private static void NativeCompletionScheduledJobCommands(CompletionContext conte { wordToComplete += "*"; } + var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); var powerShellExecutionHelper = context.Helper; @@ -3734,11 +3780,13 @@ private static void NativeCompletionMemberName(CompletionContext context, List 1) && wordToComplete[wordToComplete.Length - 1] == wordToComplete[0]; wordToComplete = wordToComplete.Substring(1, wordToComplete.Length - (endQuoted ? 2 : 1)); } + if (wordToComplete.IndexOf('[') != -1) { var cursor = (InternalScriptPosition)context.CursorPosition; @@ -3779,6 +3828,7 @@ private static void NativeCompletionTypeName(CompletionContext context, List abc return GenerateArgumentLocation(prevArg, position); } + position++; } + prevArg = arg; } + break; case AstParameterArgumentType.Fake: case AstParameterArgumentType.Switch: @@ -3896,8 +3951,10 @@ private static ArgumentLocation FindTargetArgumentLocation(Collection CompleteFilename(CompletionContext { shareFullPath = quote + shareFullPath + quote; } + results.Add(new CompletionResult(shareFullPath, shareFullPath, CompletionResultType.ProviderContainer, shareFullPath)); } } @@ -4116,6 +4176,7 @@ internal static IEnumerable CompleteFilename(CompletionContext { executionContext.LocationGlobber.GetProviderPath(wordToComplete, out provider); } + isFileSystem = provider != null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); @@ -4368,6 +4429,7 @@ internal static IEnumerable CompleteFilename(CompletionContext { tooltip = PSObject.Base(tooltips[0]) as string; } + if (string.IsNullOrEmpty(listItemText)) { // For provider items that don't have PSChildName values, such as variable::error @@ -4442,6 +4504,7 @@ internal static List GetFileShares(string machine, bool ignoreHidden) shares.Add(shareInfo.netname); } } + return shares; #endif } @@ -4508,6 +4571,7 @@ internal static List CompleteVariable(CompletionContext contex findVariablesVisitor.Top = parent; parent.Visit(findVariablesVisitor); } + parent = parent.Parent; } @@ -4566,6 +4630,7 @@ internal static List CompleteVariable(CompletionContext contex { tooltip = ast.Extent.Text; } + break; } @@ -4577,11 +4642,13 @@ internal static List CompleteVariable(CompletionContext contex { tooltip = StringUtil.Format("[{0}]${1}", discoveredType.Name, userPath); } + break; } ast = ast.Parent; } + AddUniqueVariable(hashedResults, results, completedName, userPath, tooltip); } } @@ -4746,6 +4813,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var { VariableSources.Add(new Tuple(variableExpressionAst.VariablePath.UserPath, variableExpressionAst)); } + return AstVisitAction.Continue; } @@ -4806,6 +4874,7 @@ private static SortedSet BuildSpecialVariablesCache() result.Add((string)member.GetValue(null)); } } + return result; } @@ -4920,12 +4989,14 @@ internal static List CompleteMember(CompletionContext context, { memberNameCandidateAst = lastAstAsMemberExpr.Member; } + targetExpr = lastAstAsMemberExpr.Expression; } else { memberNameCandidateAst = lastAst; } + var memberNameAst = memberNameCandidateAst as StringConstantExpressionAst; var memberName = "*"; @@ -4954,6 +5025,7 @@ internal static List CompleteMember(CompletionContext context, break; } } + var nextToLastAst = commandAst.CommandElements[i - 1]; var nextToLastExtent = nextToLastAst.Extent; var lastExtent = lastAst.Extent; @@ -5187,6 +5259,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP + " { " + (propertyInfo.GetGetMethod() != null ? "get; " : string.Empty) + (propertyInfo.GetSetMethod() != null ? "set; " : string.Empty) + "}"; } + var fieldInfo = member as FieldInfo; if (fieldInfo != null) { @@ -5367,9 +5440,11 @@ internal string ShortTypeName ? FullTypeName.Substring(lastPlusIndex + 1) : FullTypeName.Substring(lastDotIndex + 1); } + return _shortTypeName; } } + private string _shortTypeName; /// @@ -5384,9 +5459,11 @@ internal string Namespace int lastDotIndex = FullTypeName.LastIndexOf('.'); _namespace = FullTypeName.Substring(0, lastDotIndex); } + return _namespace; } } + private string _namespace; /// @@ -5435,9 +5512,11 @@ private int GenericArgumentCount var argCount = FullTypeName.Substring(backtick + 1); _genericArgumentCount = LanguagePrimitives.ConvertTo(argCount); } + return _genericArgumentCount; } } + private int _genericArgumentCount = 0; /// @@ -5472,6 +5551,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string ? "T" : string.Format(CultureInfo.InvariantCulture, "T{0}", i + 1)); } + tooltip.Append(']'); return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip.ToString()); @@ -5561,6 +5641,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string if (i != 0) tooltip.Append(", "); tooltip.Append(genericParameters[i].Name); } + tooltip.Append(']'); return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip.ToString()); @@ -5582,6 +5663,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string { listItemText = listItemText.Substring(dotIndex + 1); } + return new CompletionResult(prefix + Namespace + suffix, listItemText, CompletionResultType.Namespace, "Namespace " + Namespace); } @@ -5655,6 +5737,7 @@ private static TypeCompletionMapping[][] InitializeTypeCache() entry = new TypeCompletionMapping { Key = shortTypeName }; entries.Add(shortTypeName, entry); } + entry.Completions.Add(typeCompletionInstance); } @@ -5771,6 +5854,7 @@ private static void HandleType(Dictionary entryCa typeCompletionBase = actualType != null ? (TypeCompletionBase)new GenericTypeCompletion { Type = actualType } + : new GenericTypeCompletionInStringFormat { FullTypeName = fullTypeName }; // Remove the backtick, we only want 1 generic in our results for types like Func or Action. @@ -5781,6 +5865,7 @@ private static void HandleType(Dictionary entryCa { typeCompletionBase = actualType != null ? (TypeCompletionBase)new TypeCompletion { Type = actualType } + : new TypeCompletionInStringFormat { FullTypeName = fullTypeName }; } @@ -5803,6 +5888,7 @@ private static void HandleType(Dictionary entryCa entry = new TypeCompletionMapping { Key = shortTypeName }; entryCache.Add(shortTypeName, entry); } + entry.Completions.Add(typeCompletionBase); } } @@ -5827,6 +5913,7 @@ internal static List CompleteNamespace(CompletionContext conte results.Add(completion.GetCompletionResult(entry.Key, prefix, suffix)); } } + results.Sort((c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } @@ -6145,6 +6232,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( } } } + return results; } @@ -6203,6 +6291,7 @@ internal static List CompleteHashtableKey(CompletionContext co { ast = ast.Parent; } + if (ast is CommandParameterAst) { ast = ast.Parent; @@ -6228,8 +6317,10 @@ internal static List CompleteHashtableKey(CompletionContext co parameterName = boundArg.Key; break; } + continue; } + var astArrayPair = boundArg.Value as AstArrayPair; if (astArrayPair != null) { @@ -6238,6 +6329,7 @@ internal static List CompleteHashtableKey(CompletionContext co parameterName = boundArg.Key; break; } + continue; } } @@ -6310,6 +6402,7 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand // Expand the string if its type is DoubleQuoted or BareWord var constType = expandableStringAst.StringConstantType; if (constType == StringConstantType.DoubleQuotedHereString) { return false; } + Diagnostics.Assert( constType == StringConstantType.BareWord || (constType == StringConstantType.DoubleQuoted && expandableStringAst.Extent.Text[0].IsDoubleQuote()), @@ -6368,6 +6461,7 @@ internal static string CombineVariableWithPartialPath(VariableExpressionAst vari { } } + return null; } @@ -6410,6 +6504,7 @@ internal static bool IsSplattedVariable(Ast targetExpr) // It's splatted variable, member expansion is not useful return true; } + return false; } @@ -6447,12 +6542,14 @@ internal static void CompleteMemberHelper( { return; } + members = PSObject.dotNetStaticAdapter.BaseGetMembers(type); } else { members = PSObject.AsPSObject(value).Members; } + var sortedMembers = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _, members); foreach (var member in sortedMembers) @@ -6490,6 +6587,7 @@ internal static void CompleteMemberHelper( { newTooltip.Append(overload.Trim() + ")\r\n"); } + newTooltip.Remove(newTooltip.Length - 3, 3); tooltip = newTooltip.ToString(); } @@ -6659,6 +6757,7 @@ internal static bool IsAmpersandNeeded(CompletionContext context, bool defaultCh defaultChoice = !defaultChoice; } } + return defaultChoice; } @@ -6763,52 +6862,94 @@ internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionCo } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } + public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } + public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } + public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } + public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return false; } + public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return false; } + public object VisitAttribute(AttributeAst attributeAst) { return false; } + public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return false; } + public object VisitParameter(ParameterAst parameterAst) { return false; } + public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return false; } + public object VisitIfStatement(IfStatementAst ifStmtAst) { return false; } + public object VisitTrap(TrapStatementAst trapStatementAst) { return false; } + public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return false; } + public object VisitDataStatement(DataStatementAst dataStatementAst) { return false; } + public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return false; } + public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return false; } + public object VisitForStatement(ForStatementAst forStatementAst) { return false; } + public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return false; } + public object VisitCatchClause(CatchClauseAst catchClauseAst) { return false; } + public object VisitTryStatement(TryStatementAst tryStatementAst) { return false; } + public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return false; } + public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return false; } + public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return false; } + public object VisitExitStatement(ExitStatementAst exitStatementAst) { return false; } + public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return false; } + public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } + public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } // REVIEW: we could relax this to allow specific commands public object VisitCommand(CommandAst commandAst) { return false; } + public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return false; } + public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return false; } + public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return false; } + public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return false; } + public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { return false; } + public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return false; } + public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return false; } + public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return false; } + public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) { return false; } + public object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { return false; } + public object VisitPropertyMember(PropertyMemberAst propertyMemberAst) { return false; } + public object VisitFunctionMember(FunctionMemberAst functionMemberAst) { return false; } + public object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) { return false; } + public object VisitUsingStatement(UsingStatementAst usingStatementAst) { return false; } + public object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) { return configurationDefinitionAst.Body.Accept(this); } + public object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordStatementAst) { return false; @@ -6898,6 +7039,7 @@ public object VisitHashtable(HashtableAst hashtableAst) if (!(bool)keyValuePair.Item2.Accept(this)) return false; } + return true; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 4b964a34532..67f7c131ef5 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -98,6 +98,7 @@ public string CompletionText { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } + return _completionText; } } @@ -113,6 +114,7 @@ public string ListItemText { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } + return _listItemText; } } @@ -128,6 +130,7 @@ public CompletionResultType ResultType { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } + return _resultType; } } @@ -143,6 +146,7 @@ public string ToolTip { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } + return _toolTip; } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 7feacdd8376..7f35608fd8c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -341,6 +341,7 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv s_bindCommandRunspace = RunspaceFactory.CreateRunspace(minimalState); s_bindCommandRunspace.Open(); } + Runspace.DefaultRunspace = s_bindCommandRunspace; // Static binding always does argument binding (not argument or parameter completion). pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentBinding); @@ -354,6 +355,7 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv return new StaticBindingResult(commandAst, pseudoBinding); } + [ThreadStatic] static Runspace s_bindCommandRunspace = null; } @@ -593,6 +595,7 @@ private void AddDuplicateParameterBindingException(CommandParameterAst duplicate BindingExceptions.Add(duplicateParameter.ParameterName, new StaticBindingError(duplicateParameter, bindingException)); } } + private PseudoBindingInfo _bindingInfo = null; private void CreateBindingResultForSyntacticBind(CommandAst commandAst) @@ -727,6 +730,7 @@ internal ParameterBindingResult() public Object ConstantValue { get { return _constantValue; } + internal set { if (value != null) @@ -735,6 +739,7 @@ internal set } } } + private object _constantValue; /// @@ -742,6 +747,7 @@ internal set public CommandElementAst Value { get { return _value; } + internal set { _value = value; @@ -753,6 +759,7 @@ internal set } } } + private CommandElementAst _value; } @@ -968,6 +975,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip previousLanguageMode = executionContext.LanguageMode; executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } + _bindingEffective = PrepareCommandElements(executionContext); } finally @@ -986,6 +994,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip { _pipelineInputType = pipeArgumentType; } + _bindingEffective = ParseParameterArguments(paramAstAtCursor); if (_bindingEffective) @@ -1325,6 +1334,7 @@ private bool PrepareCommandElements(ExecutionContext context) _pipelineInputType = typeof(object); break; } + preCmdBaseAst = cmdBase; } } @@ -1341,6 +1351,7 @@ private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string { ast = ast.Parent; } + ast.Visit(exportVisitor); CommandProcessorBase commandProcessor = null; @@ -1366,6 +1377,7 @@ private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string commandProcessor = CommandDiscovery.CreateCommandProcessorForScript(scriptBlock, context, true, context.EngineSessionState); } } + return commandProcessor; } @@ -1830,6 +1842,7 @@ private static bool IsTypeEquivalent(Type argType, Type paramType) { result = true; } + return result; } @@ -1849,6 +1862,7 @@ private static AstParameterArgumentPair GetNextPositionalArgument( result = argument; break; } + nonPositionalArguments.Add(argument); } @@ -1905,6 +1919,7 @@ private Collection BindRemainingParameters(Collection< _boundArguments.Add(parameterName, new AstArrayPair(parameterName, argList)); unboundArguments.Clear(); } + result = true; break; } @@ -1962,6 +1977,7 @@ private void BindPipelineParameters() { _boundArguments.Add(parameterName, new PipeObjectPair(parameterName, _pipelineInputType)); } + result = true; break; } From bf321a9b911439dde6e26770401ecfbc05ca404d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:05 -0800 Subject: [PATCH 60/81] Update debugger --- .../engine/debugger/Breakpoint.cs | 2 ++ .../engine/debugger/debugger.cs | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index ae76ffa677d..db4eb93380e 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -209,6 +209,7 @@ internal bool Trigger(InvocationInfo invocationInfo) { return (Script == null || Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase)); } + return false; } } @@ -519,6 +520,7 @@ internal override void RemoveSelf(ScriptDebugger debugger) } } } + debugger.RemoveLineBreakpoint(this); } } diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 7f92b428284..78ed3993bf8 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -435,6 +435,7 @@ internal bool IsDebugHandlerSubscribed internal virtual UnhandledBreakpointProcessingMode UnhandledBreakpointMode { get { throw new PSNotImplementedException(); } + set { throw new PSNotImplementedException(); } } @@ -524,6 +525,7 @@ protected bool IsDebuggerBreakpointUpdatedEventSubscribed() protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessingEventArgs args) { if (args == null) { throw new PSArgumentNullException("args"); } + StartRunspaceDebugProcessing.SafeInvoke(this, args); } @@ -531,6 +533,7 @@ protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessi protected void RaiseRunspaceProcessingCompletedEvent(ProcessRunspaceDebugEndEventArgs args) { if (args == null) { throw new PSArgumentNullException("args"); } + RunspaceDebugProcessingCompleted.SafeInvoke(this, args); } @@ -911,6 +914,7 @@ private bool IsLocalSession _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); } + return _isLocalSession.Value; } } @@ -1163,6 +1167,7 @@ internal VariableBreakpoint AddVariableBreakpoint(VariableBreakpoint breakpoint) breakpoints = new List(); _variableBreakpoints.Add(breakpoint.Variable, breakpoints); } + breakpoints.Add(breakpoint); return breakpoint; } @@ -1361,6 +1366,7 @@ internal List GetBoundBreakpoints(IScriptExtent[] sequencePoints { return tuple.Item1; } + return null; } @@ -1491,6 +1497,7 @@ private void UpdateBreakpoints(FunctionContext functionContext) { // Check pending breakpoints to see if any apply to this script. if (string.IsNullOrEmpty(functionContext._file)) { return; } + bool havePendingBreakpoint = false; foreach (var item in _pendingBreakpoints) { @@ -1500,6 +1507,7 @@ private void UpdateBreakpoints(FunctionContext functionContext) break; } } + if (havePendingBreakpoint) { SetPendingBreakpoints(functionContext); @@ -1844,6 +1852,7 @@ private void ResumeExecution(DebuggerResumeAction action) // breakpoints in the current frame, but otherwise just go.) goto case DebuggerResumeAction.Continue; } + break; case DebuggerResumeAction.StepOver: @@ -1890,6 +1899,7 @@ private bool WaitForDebugStopSubscriber() Diagnostics.Assert(false, "The _preserveDebugStop event handle should always be in the signaled state at this point."); return false; } + _preserveDebugStopEvent.Reset(); // Wait indefinitely for a signal event. @@ -1927,6 +1937,7 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) breakpoint.BreakpointBitArray = null; _pendingBreakpoints.Add(breakpoint); } + boundBreakpoints.Clear(); } @@ -1953,6 +1964,7 @@ private void SetPendingBreakpoints(FunctionContext functionContext) { Diagnostics.Assert(false, "If the script block is still alive, the entry should not be collected."); } + Diagnostics.Assert(tuple.Item1 == functionContext._boundBreakpoints, "What's up?"); foreach (var breakpoint in _pendingBreakpoints) @@ -2217,6 +2229,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { _psDebuggerCommand.SetIsNested(true); } + _psDebuggerCommand.Runspace = localRunspace; _psDebuggerCommand.Commands = command; foreach (var cmd in _psDebuggerCommand.Commands.Commands) @@ -2509,6 +2522,7 @@ internal override UnhandledBreakpointProcessingMode UnhandledBreakpointMode { return (_preserveUnhandledDebugStopEvent) ? UnhandledBreakpointProcessingMode.Wait : UnhandledBreakpointProcessingMode.Ignore; } + set { switch (value) @@ -2855,6 +2869,7 @@ private void SetRunningJobListToStep(bool enableStepping) { runningJobs = _runningJobs.Values.ToArray(); } + foreach (var item in runningJobs) { try @@ -2872,6 +2887,7 @@ private void SetRunspaceListToStep(bool enableStepping) { runspaceList = _runningRunspaces.Values.ToArray(); } + foreach (var item in runspaceList) { try @@ -3448,6 +3464,7 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent // Get nested debugger runspace info. NestedRunspaceDebugger nestedDebugger = senderDebugger as NestedRunspaceDebugger; if (nestedDebugger == null) { return; } + PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; // If this is a workflow debugger then ensure that there is a current active @@ -3702,6 +3719,7 @@ private void WaitForDebugComplete() { _runspaceDebugCompleteEvent.Reset(); } + _runspaceDebugCompleteEvent.Wait(); } @@ -3720,6 +3738,7 @@ public void Dispose() { runningJobs = _runningJobs.Values.ToArray(); } + foreach (var item in runningJobs) { Job job = item.Job; @@ -3776,6 +3795,7 @@ internal void DisableTracing() SetInternalDebugMode(InternalDebugMode.Disabled); } } + private bool _savedIgnoreScriptDebug = false; internal void Trace(string messageId, string resourceString, params object[] args) @@ -3792,6 +3812,7 @@ internal void Trace(string messageId, string resourceString, params object[] arg { message = StringUtil.Format(resourceString, args); } + if (String.IsNullOrEmpty(message)) { message = "Could not load text for msh script tracing message id '" + messageId + "'"; @@ -3852,6 +3873,7 @@ internal void TraceVariableSet(string varName, object value) { valAsString = valAsString.Substring(0, msgLength) + PSObjectHelper.Ellipsis; } + Trace("TraceVariableAssignment", ParserStrings.TraceVariableAssignment, varName, valAsString); } @@ -4480,6 +4502,7 @@ private InvocationInfo CreateInvocationInfoFromParent( StatementAst callingStatement = _parentScriptBlockAst.Find( ast => { return ((ast is StatementAst) && (ast.Extent.StartLineNumber == callingLineNumber)); } + , true) as StatementAst; if (callingStatement != null) @@ -4734,6 +4757,7 @@ public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInf { DebuggerCommand dbgCommand = DoProcessCommand(host, command, invocationInfo, output); if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction != null)) { _lastCommand = dbgCommand; } + return dbgCommand; } @@ -4764,6 +4788,7 @@ public DebuggerCommand ProcessBasicCommand(string command) if (_commandTable.TryGetValue(command, out debuggerCommand)) { if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction != null)) { _lastCommand = debuggerCommand; } + return debuggerCommand; } @@ -4784,8 +4809,10 @@ private DebuggerCommand DoProcessCommand(PSHost host, string command, Invocation { DisplayScript(host, output, invocationInfo, _lastLineDisplayed + 1, DefaultListLineCount); } + return _listCommand; } + command = _lastCommand.Command; } @@ -4885,6 +4912,7 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); return; } + if (start <= 0 || start > _lines.Length) { WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); From dea69ad43174f5f86cbdac4fd7ec26c377ae6d53 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:05 -0800 Subject: [PATCH 61/81] Update ExperimentalFeature --- .../engine/ExperimentalFeature/ExperimentalFeature.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 86d25b94026..79554d4d7b0 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -151,6 +151,7 @@ private static ReadOnlyBag ProcessEnabledFeatures(string[] enabledFeatur LogError(PSEventId.ExperimentalFeature_InvalidName, name, message); } } + return new ReadOnlyBag(new HashSet(list, StringComparer.OrdinalIgnoreCase)); } @@ -228,6 +229,7 @@ internal static ExperimentAction GetActionToTake(string experimentName, Experime { action = (action == ExperimentAction.Hide) ? ExperimentAction.Show : ExperimentAction.Hide; } + return action; } @@ -334,9 +336,11 @@ private ExperimentAction EffectiveAction { _effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName, ExperimentAction); } + return _effectiveAction; } } + private ExperimentAction _effectiveAction = ExperimentAction.None; } } From 8758eeafc5a06fe9e3d2f281f36dab740312daae Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:06 -0800 Subject: [PATCH 62/81] Update hostifaces --- .../engine/hostifaces/ChoiceDescription.cs | 1 + .../engine/hostifaces/Command.cs | 14 +++++++ .../engine/hostifaces/Connection.cs | 18 +++++++++ .../engine/hostifaces/ConnectionBase.cs | 13 +++++++ .../engine/hostifaces/FieldDescription.cs | 5 +++ .../engine/hostifaces/History.cs | 30 +++++++++++++++ .../engine/hostifaces/HostUtilities.cs | 4 ++ .../engine/hostifaces/InformationalRecord.cs | 3 ++ .../engine/hostifaces/InternalHost.cs | 5 +++ .../InternalHostRawUserInterface.cs | 13 +++++++ .../hostifaces/InternalHostUserInterface.cs | 9 +++++ .../engine/hostifaces/ListModifier.cs | 5 +++ .../engine/hostifaces/LocalConnection.cs | 11 ++++++ .../engine/hostifaces/LocalPipeline.cs | 11 ++++++ .../engine/hostifaces/MshHost.cs | 1 + .../hostifaces/MshHostRawUserInterface.cs | 27 ++++++++++++++ .../engine/hostifaces/MshHostUserInterface.cs | 12 ++++++ .../hostifaces/NativeCultureResolver.cs | 1 + .../engine/hostifaces/PSCommand.cs | 12 ++++++ .../engine/hostifaces/PSDataCollection.cs | 23 ++++++++++++ .../engine/hostifaces/Parameter.cs | 3 ++ .../engine/hostifaces/Pipeline.cs | 2 + .../engine/hostifaces/PowerShell.cs | 37 +++++++++++++++++++ .../hostifaces/PowerShellProcessInstance.cs | 2 + .../engine/hostifaces/RunspaceInvoke.cs | 4 ++ .../engine/hostifaces/RunspacePool.cs | 2 + .../engine/hostifaces/RunspacePoolInternal.cs | 2 + .../internalHostuserInterfacesecurity.cs | 1 + .../engine/hostifaces/pipelinebase.cs | 3 ++ 29 files changed, 274 insertions(+) diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index a99f95f6820..09152c832d5 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -127,6 +127,7 @@ class ChoiceDescription return this.helpMessage; } + set { if (value == null) diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 67eb4ee8bf4..6e6f31b9031 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -225,6 +225,7 @@ public PipelineResultTypes MergeUnclaimedPreviousCommandResults { return _mergeUnclaimedPreviousCommandResults; } + set { if (value == PipelineResultTypes.None) @@ -262,6 +263,7 @@ internal enum MergeType Debug = 3, Information = 4 } + internal const int MaxMergeType = (int)(MergeType.Information + 1); /// @@ -299,6 +301,7 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR { MergeInstructions[i] = PipelineResultTypes.None; } + return; } @@ -307,10 +310,12 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR { throw PSTraceSource.NewArgumentException("myResult", RunspaceStrings.InvalidMyResultError); } + if (myResult == PipelineResultTypes.Error && toResult != PipelineResultTypes.Output) { throw PSTraceSource.NewArgumentException("toResult", RunspaceStrings.InvalidValueToResultError); } + if (toResult != PipelineResultTypes.Output && toResult != PipelineResultTypes.Null) { throw PSTraceSource.NewArgumentException("toResult", RunspaceStrings.InvalidValueToResult); @@ -328,18 +333,22 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR { MergeInstructions[(int)MergeType.Error] = toResult; } + if (myResult == PipelineResultTypes.Warning || myResult == PipelineResultTypes.All) { MergeInstructions[(int)MergeType.Warning] = toResult; } + if (myResult == PipelineResultTypes.Verbose || myResult == PipelineResultTypes.All) { MergeInstructions[(int)MergeType.Verbose] = toResult; } + if (myResult == PipelineResultTypes.Debug || myResult == PipelineResultTypes.All) { MergeInstructions[(int)MergeType.Debug] = toResult; } + if (myResult == PipelineResultTypes.Information || myResult == PipelineResultTypes.All) { MergeInstructions[(int)MergeType.Information] = toResult; @@ -592,18 +601,22 @@ internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject) { command.MergeInstructions[(int)MergeType.Error] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeError); } + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeWarning] != null) { command.MergeInstructions[(int)MergeType.Warning] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeWarning); } + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeVerbose] != null) { command.MergeInstructions[(int)MergeType.Verbose] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeVerbose); } + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeDebug] != null) { command.MergeInstructions[(int)MergeType.Debug] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeDebug); } + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeInformation] != null) { command.MergeInstructions[(int)MergeType.Information] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeInformation); @@ -702,6 +715,7 @@ internal PSObject ToPSObjectForRemoting(Version psRPVersion) { parametersAsListOfPSObjects.Add(parameter.ToPSObjectForRemoting()); } + commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.Parameters, parametersAsListOfPSObjects)); return commandAsPSObject; diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 71bd341263a..f234bd62a51 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -334,6 +334,7 @@ internal RunspaceStateEventArgs(RunspaceStateInfo runspaceStateInfo) { throw PSTraceSource.NewArgumentNullException("runspaceStateInfo"); } + RunspaceStateInfo = runspaceStateInfo; } @@ -505,6 +506,7 @@ public static Runspace DefaultRunspace { return t_threadSpecificDefaultRunspace; } + set { if (value == null || !value.RunspaceIsRemote) @@ -539,6 +541,7 @@ internal static Runspace PrimaryRunspace } } } + private static Runspace s_primaryRunspace; /// @@ -607,6 +610,7 @@ public ApartmentState ApartmentState this.apartmentState = value; } } + private ApartmentState apartmentState = Runspace.DefaultApartmentState; #endif @@ -798,6 +802,7 @@ internal static ReadOnlyDictionary> RunspaceDiction } } } + private static SortedDictionary> s_runspaceDictionary; private static object s_syncObject; @@ -883,6 +888,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise // Otherwise no change. } + break; case RunspaceAvailability.Available: @@ -896,6 +902,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise this.RunspaceAvailability = Runspaces.RunspaceAvailability.None; break; } + break; case RunspaceAvailability.AvailableForNestedCommand: @@ -913,6 +920,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise default: break; // no change in the availability } + break; case RunspaceAvailability.Busy: @@ -928,6 +936,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise { this.RunspaceAvailability = RunspaceAvailability.None; } + break; case PipelineState.Stopping: @@ -1020,6 +1029,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise } } } + break; case PipelineState.Running: // this can happen if a nested pipeline is created without entering a nested prompt @@ -1028,6 +1038,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise default: break; // no change in the availability } + break; default: @@ -1132,11 +1143,13 @@ protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool rais this.RunspaceAvailability = (remoteCommand == null && GetCurrentlyRunningPipeline() == null) ? RunspaceAvailability.Available : RunspaceAvailability.Busy; } + break; default: break; // no change in the availability } + break; case RunspaceAvailability.Available: @@ -1155,6 +1168,7 @@ protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool rais default: break; // no change in the availability } + break; default: @@ -1496,6 +1510,7 @@ internal PowerShell PopRunningPowerShell() if (count > 0) { if (count == 1) { _baseRunningPowerShell = null; } + return _runningPowerShells.Pop(); } } @@ -1685,6 +1700,7 @@ public virtual void SetVariable(string name, object value) { throw PSTraceSource.NewArgumentNullException("name"); } + _runspace.SetVariable(name, value); } @@ -1717,6 +1733,7 @@ public virtual object GetVariable(string name) { return null; } + return _runspace.GetVariable(name); } @@ -1780,6 +1797,7 @@ public virtual DriveManagementIntrinsics Drive public virtual PSLanguageMode LanguageMode { get { return _runspace.LanguageMode; } + set { _runspace.LanguageMode = value; } } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index bd0b61da520..db8005987d9 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -42,6 +42,7 @@ protected RunspaceBase(PSHost host) { throw PSTraceSource.NewArgumentNullException("host"); } + InitialSessionState = InitialSessionState.CreateDefault(); Host = host; } @@ -67,6 +68,7 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState) { throw PSTraceSource.NewArgumentNullException("host"); } + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException("initialSessionState"); @@ -107,6 +109,7 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, boo { throw PSTraceSource.NewArgumentNullException("host"); } + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException("initialSessionState"); @@ -121,6 +124,7 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, boo { InitialSessionState = initialSessionState.Clone(); } + this.ThreadOptions = initialSessionState.ThreadOptions; #if !CORECLR // No ApartmentState In CoreCLR @@ -170,8 +174,10 @@ public override RunspaceStateInfo RunspaceStateInfo public override RunspaceAvailability RunspaceAvailability { get { return _runspaceAvailability; } + protected set { _runspaceAvailability = value; } } + private RunspaceAvailability _runspaceAvailability = RunspaceAvailability.None; /// @@ -402,6 +408,7 @@ private void CoreClose(bool syncCall) { WaitForFinishofPipelines(); } + return; } @@ -980,11 +987,13 @@ internal bool RunActionIfNoRunningPipelinesWithThreadCheck(Action action) shouldRunAction = true; } } + if (shouldRunAction) { action(); ranit = true; } + return ranit; } @@ -996,6 +1005,7 @@ internal override Pipeline GetCurrentlyRunningPipeline() { return _currentlyRunningPipeline; } + private Pipeline _currentlyRunningPipeline = null; /// @@ -1341,8 +1351,10 @@ public PSLanguageMode LanguageMode ); throw e; } + return DoLanguageMode; } + set { if (RunspaceState != RunspaceState.Opened) @@ -1356,6 +1368,7 @@ public PSLanguageMode LanguageMode ); throw e; } + DoLanguageMode = value; } } diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 5ce76ee7cfe..5e51c44e551 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -199,6 +199,7 @@ public string Name return label; } + set { if (value == null) @@ -231,6 +232,7 @@ public string Name return helpMessage; } + set { if (value == null) @@ -254,6 +256,7 @@ public string Name { return isMandatory; } + set { isMandatory = value; @@ -375,6 +378,7 @@ internal bool ModifiedByRemotingProtocol { return modifiedByRemotingProtocol; } + set { modifiedByRemotingProtocol = value; @@ -395,6 +399,7 @@ internal bool IsFromRemoteHost { return isFromRemoteHost; } + set { isFromRemoteHost = value; diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 030882e6fbd..0a593e6a3b3 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -400,6 +400,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) if (_countEntriesAdded > _capacity) index = SmallestID; } + for (long i = count - 1; i >= 0;) { if (index > _countEntriesAdded) break; @@ -430,6 +431,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) break; } } + if (index < 1) break; if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || (_buffer[GetIndexFromId(index)].Cleared == true)) @@ -443,6 +445,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) } } } + HistoryInfo[] entries = new HistoryInfo[entriesList.Count]; entriesList.CopyTo(entries); return entries; @@ -465,14 +468,17 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } + if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } + if (count > _countEntriesAdded || count == -1) { count = _countEntriesInBuffer; } + List cmdlist = new List(); long SmallestID = 1; //if buffersize is changes,Get the smallest entry that's not cleared in the buffer @@ -488,6 +494,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S if (_countEntriesAdded > _capacity) id = SmallestID; } + for (long i = 0; i <= count - 1;) { if (id > _countEntriesAdded) break; @@ -495,6 +502,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S { cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++; } + id++; } } @@ -512,11 +520,13 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S break; } } + if (id < 1) break; if (_buffer[GetIndexFromId(id)].Cleared == false && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim())) { cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++; } + id--; } } @@ -531,6 +541,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S } } } + HistoryInfo[] entries = new HistoryInfo[cmdlist.Count]; cmdlist.CopyTo(entries); return entries; @@ -566,6 +577,7 @@ internal void ClearEntry(long id) entry.Cleared = true; _countEntriesInBuffer--; } + return; } } @@ -627,6 +639,7 @@ private HistoryInfo CoreGetEntry(long id) { throw PSTraceSource.NewArgumentOutOfRangeException("id", id); } + if (_countEntriesInBuffer == 0) return null; if (id > _countEntriesAdded) @@ -664,6 +677,7 @@ private long SmallestIDinBuffer() if (minID > _buffer[i].Id) minID = _buffer[i].Id; } + return minID; } @@ -830,6 +844,7 @@ public long[] Id { return _id; } + set { _id = value; @@ -857,6 +872,7 @@ public int Count { return _count; } + set { _countParameterSpecified = true; @@ -942,6 +958,7 @@ protected override void ProcessRecord() { _count = history.Buffercapacity(); } + HistoryInfo[] entries = history.GetEntries(0, _count, true); for (long i = entries.Length - 1; i >= 0; i--) WriteObject(entries[i]); @@ -980,6 +997,7 @@ public string Id { return _id; } + set { if (_id != null) @@ -987,6 +1005,7 @@ public string Id //Id has been set already. _multipleIdProvided = true; } + _id = value; } } @@ -1102,6 +1121,7 @@ protected override void EndProcessing() { WriteObject(results, true); } + pipeline.RemoveFromInvokeHistoryEntryList(entry); } finally @@ -1173,6 +1193,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) break; } } + if (entry == null) { Exception ex = @@ -1241,6 +1262,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) } } } + return entry; } @@ -1314,6 +1336,7 @@ public class AddHistoryCommand : PSCmdlet public SwitchParameter Passthru { get { return _passthru; } + set { _passthru = value; } } @@ -1424,6 +1447,7 @@ void ProcessRecord() { break; } + executionStatus = (PipelineState)baseObject; if (executionStatus < PipelineState.NotStarted || executionStatus > PipelineState.Failed) { @@ -1566,6 +1590,7 @@ public int[] Id { return _id; } + set { _id = value; @@ -1591,6 +1616,7 @@ public string[] CommandLine { return _commandline; } + set { _commandline = value; @@ -1614,6 +1640,7 @@ public int Count { return _count; } + set { _countParameterSpecified = true; @@ -1642,6 +1669,7 @@ public SwitchParameter Newest { return _newest; } + set { _newest = value; @@ -1789,6 +1817,7 @@ private void ClearHistoryByID() { return; } + ClearHistoryEntries(0, -1, null, _newest); } else @@ -1898,6 +1927,7 @@ private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParam ) ); } + _entries = _history.GetEntries(id, count, newest); } else diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index fc9b6b894fb..1c7dc7ed6ee 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -148,6 +148,7 @@ internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfi { continue; } + command = new PSCommand(); command.AddCommand(profilePath, false); commands.Add(command); @@ -485,6 +486,7 @@ internal static string RemoveGuidFromMessage(string message, out bool matchPatte message = message.Remove(0, partToRemove.Length); matchPattern = true; } + return message; } @@ -502,6 +504,7 @@ internal static string RemoveIdentifierInfoFromMessage(string message, out bool message = message.Remove(0, partToRemove.Length); matchPattern = true; } + return message; } @@ -912,6 +915,7 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace // Local runspace. Make a nested PowerShell object as needed. ps.SetIsNested(runspace.GetCurrentlyRunningPipeline() != null); } + using (ps) { ps.Commands = command; diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index ca44d7e9536..f56349eaea4 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -58,6 +58,7 @@ public string Message { return _message; } + set { _message = value; } } @@ -116,6 +117,7 @@ internal bool SerializeExtendedInfo { return _serializeExtendedInfo; } + set { _serializeExtendedInfo = value; @@ -213,6 +215,7 @@ public string FullyQualifiedWarningId return _fullyQualifiedWarningId ?? string.Empty; } } + private string _fullyQualifiedWarningId; } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index 201e2da2315..341522405c8 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -129,6 +129,7 @@ public override System.Guid InstanceId } #pragma warning restore 56503 } + return _idResult; } } @@ -349,6 +350,7 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) { commandInfoProperty.Value = oldCommandInfo; } + if (stackTraceProperty != null) { stackTraceProperty.Value = oldStackTrace; @@ -400,6 +402,7 @@ public override void ExitNestedPrompt() { ExitNestedPromptHelper(); } + ExitNestedPromptException enpe = new ExitNestedPromptException(); throw enpe; } @@ -450,6 +453,7 @@ private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession() { throw new PSNotImplementedException(); } + return host; } @@ -535,6 +539,7 @@ internal void RevertHostRef() { // nothing to revert if Host reference is not set. if (!IsHostRefSet) { return; } + _externalHostRef.Revert(); _internalUIRef.Revert(); } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index 986efe75ac9..73bbf373b2a 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -58,6 +58,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -93,6 +94,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -128,6 +130,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -163,6 +166,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -198,6 +202,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -233,6 +238,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -268,6 +274,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -350,6 +357,7 @@ public override { ThrowNotInteractive(); } + KeyInfo result = new KeyInfo(); try { @@ -364,6 +372,7 @@ public override { throw; } + lpl.Stopper.Stop(); } @@ -440,6 +449,7 @@ public override return result; } + set { if (_externalRawUI == null) @@ -568,6 +578,7 @@ public override int LengthInBufferCells(string str) { ThrowNotInteractive(); } + return _externalRawUI.LengthInBufferCells(str); } @@ -589,6 +600,7 @@ public override int LengthInBufferCells(string str, int offset) { ThrowNotInteractive(); } + return _externalRawUI.LengthInBufferCells(str, offset); } @@ -608,6 +620,7 @@ public override { ThrowNotInteractive(); } + return _externalRawUI.LengthInBufferCells(character); } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 4364bfe0b5d..d31d483de8e 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -29,6 +29,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh { throw PSTraceSource.NewArgumentNullException("parentHost"); } + _parent = parentHost; PSHostRawUserInterface rawui = null; @@ -112,6 +113,7 @@ public override { throw; } + lpl.Stopper.Stop(); } @@ -150,6 +152,7 @@ public override { throw; } + lpl.Stopper.Stop(); } @@ -397,6 +400,7 @@ internal void WriteDebugInfoBuffers(DebugRecord record) { WriteDebugLineHelper(message); } + break; case ActionPreference.Stop: WriteDebugLineHelper(message); @@ -755,6 +759,7 @@ public override { throw; } + lpl.Stopper.Stop(); } @@ -797,6 +802,7 @@ public override { throw; } + lpl.Stopper.Stop(); } @@ -861,6 +867,7 @@ public Collection PromptForChoice(string caption, { throw; } + lpl.Stopper.Stop(); } @@ -969,6 +976,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, "{0}{1}", prepend, defaultStr)); prepend = ","; } + string defaultChoicesStr = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) @@ -1014,6 +1022,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, // allow for no choice selection. break; } + int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 399334e1b2c..1b5f5477f99 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -150,6 +150,7 @@ public Collection Add { get { return _itemsToAdd; } } + private Collection _itemsToAdd; /// @@ -159,6 +160,7 @@ public Collection Remove { get { return _itemsToRemove; } } + private Collection _itemsToRemove; /// @@ -168,6 +170,7 @@ public Collection Replace { get { return _replacementItems; } } + private Collection _replacementItems; /// @@ -195,6 +198,7 @@ public void ApplyTo(IList collectionToUpdate) { collectionToUpdate.Remove(PSObject.Base(obj)); } + foreach (object obj in _itemsToAdd) { collectionToUpdate.Add(PSObject.Base(obj)); @@ -220,6 +224,7 @@ public void ApplyTo(object collectionToUpdate) { throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed); } + ApplyTo(list); } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 1907ee38c2e..a1afc3fa3ec 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -169,6 +169,7 @@ public override PSThreadOptions ThreadOptions } } } + private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// @@ -293,6 +294,7 @@ internal TranscriptionData TranscriptionData return _transcriptionData; } } + private TranscriptionData _transcriptionData = null; private JobRepository _jobRepository; @@ -544,6 +546,7 @@ private static Hashtable GetDebugPreferenceCache(Runspace runspace) debugPreferenceCache = psObjects[0].BaseObject as Hashtable; } } + return debugPreferenceCache; } @@ -563,6 +566,7 @@ private static DebugPreference GetProcessSpecificDebugPreference(object debugPre processDebugPreference = LanguagePrimitives.ConvertTo(debugPreferencePsObject); } } + return processDebugPreference; } @@ -907,6 +911,7 @@ private void DoCloseHelper() allRunspacesClosed = false; break; } + var localRunspace = r as LocalRunspace; if (localRunspace != null && localRunspace.Host is IHostProvidesTelemetryData) { @@ -914,6 +919,7 @@ private void DoCloseHelper() break; } } + if (allRunspacesClosed && !hostProvidesExitTelemetry) { TelemetryAPI.ReportExitTelemetry(null); @@ -945,6 +951,7 @@ private void CloseOrDisconnectAllRemoteRunspaces(Func> getR IThrottleOperation operation = new CloseOrDisconnectRunspaceOperationHelper(remoteRunspace); throttleManager.AddOperation(operation); } + throttleManager.EndSubmitOperations(); remoteRunspaceCloseCompleted.WaitOne(); @@ -957,6 +964,7 @@ private void CloseOrDisconnectAllRemoteRunspaces(Func> getR private void StopOrDisconnectAllJobs() { if (JobRepository.Jobs.Count == 0) { return; } + List disconnectRunspaces = new List(); using (ManualResetEvent jobsStopCompleted = new ManualResetEvent(false)) @@ -1096,6 +1104,7 @@ protected override PSLanguageMode DoLanguageMode return _engine.Context.SessionState.LanguageMode; } + set { if (_disposed) @@ -1207,6 +1216,7 @@ protected override void Dispose(bool disposing) { return; } + lock (SyncRoot) { if (_disposed) @@ -1549,6 +1559,7 @@ public PSDataCollection ErrorRecords { get { return _errors; } } + private PSDataCollection _errors; #region Serialization diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index e09d280d7fd..4f79d146b54 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -219,6 +219,7 @@ protected override void StartPipelineExecution() SetupInvokeThread(invokeThread.Worker, true); invokeThread.Start(invokeThreadProcDelegate); } + break; } @@ -242,6 +243,7 @@ protected override void StartPipelineExecution() Thread.CurrentThread.CurrentCulture = oldCurrentCulture; Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture; } + break; } @@ -344,6 +346,7 @@ private FlowControlException InvokeHelper() SetHadErrors(true); Runspace.ExecutionContext.AppendDollarError(ex); } + throw; } @@ -903,6 +906,7 @@ private PipelineProcessor CreatePipelineProcessor() commandProcessorBase.RedirectShellErrorOutputPipe = this.RedirectShellErrorOutputPipe; pipelineProcessor.Add(commandProcessorBase); } + return pipelineProcessor; } catch (RuntimeException) @@ -1036,6 +1040,7 @@ void AddHistoryEntryFromAddHistoryCmdlet() { return; } + if (AddToHistory) { _historyIdForThisPipeline = LocalRunspace.History.AddEntry(InstanceId, HistoryString, PipelineState, _pipelineStartTime, DateTime.Now, false); @@ -1082,6 +1087,7 @@ internal static System.Management.Automation.ExecutionContext GetExecutionContex { return null; } + return runspace.ExecutionContext; } @@ -1334,6 +1340,7 @@ internal bool IsStopping { return _stopping; } + set { _stopping = value; @@ -1350,6 +1357,7 @@ internal void Push(PipelineProcessor item) { throw PSTraceSource.NewArgumentNullException("item"); } + lock (_syncRoot) { if (_stopping) @@ -1357,8 +1365,10 @@ internal void Push(PipelineProcessor item) PipelineStoppedException e = new PipelineStoppedException(); throw e; } + _stack.Push(item); } + item.LocalPipeline = _localPipeline; } @@ -1402,6 +1412,7 @@ internal void Stop() { return; } + _stopping = true; copyStack = _stack.ToArray(); diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index dc4f9d4407b..7f6950ea0a8 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -294,6 +294,7 @@ public virtual PSObject PrivateData public virtual bool DebuggerEnabled { get { return false; } + set { throw new PSNotImplementedException(); } } } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 1552016c27e..357c302f34a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -32,6 +32,7 @@ struct Coordinates public int X { get { return x; } + set { x = value; } } @@ -41,6 +42,7 @@ public int X public int Y { get { return y; } + set { y = value; } } @@ -222,6 +224,7 @@ struct Size public int Width { get { return width; } + set { width = value; } } @@ -231,6 +234,7 @@ public int Width public int Height { get { return height; } + set { height = value; } } @@ -516,6 +520,7 @@ struct KeyInfo public int VirtualKeyCode { get { return virtualKeyCode; } + set { virtualKeyCode = value; } } @@ -526,6 +531,7 @@ public int VirtualKeyCode public char Character { get { return character; } + set { character = value; } } @@ -536,6 +542,7 @@ public char Character public ControlKeyStates ControlKeyState { get { return controlKeyState; } + set { controlKeyState = value; } } @@ -546,6 +553,7 @@ public ControlKeyStates ControlKeyState public bool KeyDown { get { return keyDown; } + set { keyDown = value; } } @@ -723,6 +731,7 @@ struct Rectangle public int Left { get { return left; } + set { left = value; } } @@ -733,6 +742,7 @@ public int Left public int Top { get { return top; } + set { top = value; } } @@ -743,6 +753,7 @@ public int Top public int Right { get { return right; } + set { right = value; } } @@ -753,6 +764,7 @@ public int Right public int Bottom { get { return bottom; } + set { bottom = value; } } @@ -784,6 +796,7 @@ public int Bottom // "right" and "left" are not localizable throw PSTraceSource.NewArgumentException("right", MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "right", "left"); } + if (bottom < top) { // "bottom" and "top" are not localizable @@ -991,6 +1004,7 @@ struct BufferCell public char Character { get { return character; } + set { character = value; } } @@ -1004,6 +1018,7 @@ public char Character public ConsoleColor ForegroundColor { get { return foregroundColor; } + set { foregroundColor = value; } } @@ -1014,6 +1029,7 @@ public ConsoleColor ForegroundColor public ConsoleColor BackgroundColor { get { return backgroundColor; } + set { backgroundColor = value; } } @@ -1024,6 +1040,7 @@ public ConsoleColor BackgroundColor public BufferCellType BufferCellType { get { return bufferCellType; } + set { bufferCellType = value; } } @@ -1164,6 +1181,7 @@ public static { return !(first == second); } + private const string StringsBaseName = "MshHostRawUserInterfaceStrings"; } @@ -1704,6 +1722,7 @@ string source { throw PSTraceSource.NewArgumentNullException("source"); } + return source.Length; } @@ -1790,6 +1809,7 @@ char source { throw PSTraceSource.NewArgumentNullException("contents"); } + byte[][] charLengths = new byte[contents.Length][]; int maxStringLengthInBufferCells = 0; for (int i = 0; i < contents.Length; i++) @@ -1798,6 +1818,7 @@ char source { continue; } + int lengthInBufferCells = 0; charLengths[i] = new byte[contents[i].Length]; for (int j = 0; j < contents[i].Length; j++) @@ -1805,15 +1826,18 @@ char source charLengths[i][j] = (byte)LengthInBufferCells(contents[i][j]); lengthInBufferCells += charLengths[i][j]; } + if (maxStringLengthInBufferCells < lengthInBufferCells) { maxStringLengthInBufferCells = lengthInBufferCells; } } + if (maxStringLengthInBufferCells <= 0) { throw PSTraceSource.NewArgumentException("contents", MshHostRawUserInterfaceStrings.AllNullOrEmptyStringsErrorTemplate); } + BufferCell[,] results = new BufferCell[contents.Length, maxStringLengthInBufferCells]; for (int i = 0; i < contents.Length; i++) { @@ -1840,6 +1864,7 @@ char source resultJ++; } } + return results; #pragma warning restore 56506 } @@ -1933,6 +1958,7 @@ char source contents.ForegroundColor, contents.BackgroundColor, BufferCellType.Trailing); } + if (normalizedWidth < width) { buffer[i, normalizedWidth] = contents; @@ -1940,6 +1966,7 @@ char source } } } + return buffer; } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 32fe3abd86c..271e62e3fb2 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -266,6 +266,7 @@ private TranscriptionData TranscriptionData return temporaryTranscriptionData; } } + private TranscriptionData _volatileTranscriptionData; /// @@ -401,6 +402,7 @@ public TranscribeOnlyCookie(PSHostUserInterface ui) _ui=ui; Interlocked.Increment(ref _ui._transcribeOnlyCount); } + public void Dispose() { if (!_disposed) @@ -410,6 +412,7 @@ public void Dispose() GC.SuppressFinalize(this); } } + ~TranscribeOnlyCookie() => Dispose(); } @@ -544,6 +547,7 @@ private void LogTranscriptFooter(TranscriptionOption stoppedTranscript) { stoppedTranscript.OutputToLog.Add(message); } + TranscribeCommandComplete(null); } catch (Exception) @@ -720,10 +724,12 @@ private void FlushPendingOutput() transcript.Path); throw new ArgumentException(errorMessage); } + if(!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } + if(!File.Exists(transcript.Path)) { File.Create(transcript.Path).Dispose(); @@ -938,6 +944,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio return systemTranscript; } + internal static TranscriptionOption systemTranscript = null; private static Object s_systemTranscriptLock = new Object(); @@ -1068,6 +1075,7 @@ internal string Path Encoding = Utils.GetEncoding(value); } } + private string _path; /// @@ -1122,6 +1130,7 @@ internal void FlushContentToDisk() new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), this.Encoding); } + _contentWriter.AutoFlush = true; } @@ -1134,6 +1143,7 @@ internal void FlushContentToDisk() OutputBeingLogged.Clear(); } } + private StreamWriter _contentWriter = null; /// @@ -1163,6 +1173,7 @@ public void Dispose() _disposed = true; } + private bool _disposed = false; } @@ -1232,6 +1243,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch splitLabel.Append(choices[i].Label.Substring(andPos + 1)); hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.Substring(andPos + 1, 1).Trim()); } + hotkeysAndPlainLabels[1, i] = splitLabel.ToString().Trim(); } else diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs index 8d87e5632d7..0a10284ac78 100644 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs @@ -142,6 +142,7 @@ private VistaCultureInfo ImmediateParent Array.Resize(ref fallbacksForTheParent, currentIndex); } } + _parentCI = new VistaCultureInfo(parentCulture, fallbacksForTheParent); } } diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 1c3a15edf48..3681630b5ec 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -90,6 +90,7 @@ public PSCommand AddCommand(string command) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); @@ -133,6 +134,7 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); @@ -174,6 +176,7 @@ public PSCommand AddScript(string script) { throw PSTraceSource.NewArgumentNullException("script"); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); @@ -218,6 +221,7 @@ public PSCommand AddScript(string script, bool useLocalScope) { throw PSTraceSource.NewArgumentNullException("script"); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); @@ -255,6 +259,7 @@ public PSCommand AddCommand(Command command) { throw PSTraceSource.NewArgumentNullException("command"); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); @@ -301,10 +306,12 @@ public PSCommand AddParameter(string parameterName, object value) throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); } + _currentCommand.Parameters.Add(parameterName, value); return this; } @@ -341,10 +348,12 @@ public PSCommand AddParameter(string parameterName) throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); } + _currentCommand.Parameters.Add(parameterName, true); return this; } @@ -381,10 +390,12 @@ public PSCommand AddArgument(object value) throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } + if (_owner != null) { _owner.AssertChangesAreAccepted(); } + _currentCommand.Parameters.Add(null, value); return this; } @@ -443,6 +454,7 @@ internal PowerShell Owner { return _owner; } + set { _owner = value; diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 13c9d289eff..055bf24d485 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -297,6 +297,7 @@ public static implicit operator PSDataCollection(object[] arrayToConvert) psdc.Add(LanguagePrimitives.ConvertTo(ae)); } } + psdc.Complete(); return psdc; } @@ -391,6 +392,7 @@ public bool IsOpen public int DataAddedCount { get { return _dataAddedFrequency; } + set { bool raiseDataAdded = false; @@ -435,6 +437,7 @@ public bool SerializeInput _serializeInput = value; } } + private bool _serializeInput = false; /// @@ -459,6 +462,7 @@ internal Guid SourceId return _sourceGuid; } } + set { lock (SyncObject) @@ -481,6 +485,7 @@ internal bool ReleaseOnEnumeration return _releaseOnEnumeration; } } + set { lock (SyncObject) @@ -502,6 +507,7 @@ internal bool IsEnumerated return _isEnumerated; } } + set { lock (SyncObject) @@ -559,6 +565,7 @@ public void Complete() tempCompleted(this, EventArgs.Empty); } } + if (raiseDataAdded) { RaiseDataAddedEvent(_lastPsInstanceId, _lastIndex); @@ -584,6 +591,7 @@ public bool BlockingEnumerator return _blockingEnumerator; } } + set { lock (SyncObject) @@ -648,6 +656,7 @@ public T this[int index] return _data[index]; } } + set { lock (SyncObject) @@ -662,6 +671,7 @@ public T this[int index] { value = (T)(Object)GetSerializedObject(value); } + _data[index] = value; } } @@ -730,6 +740,7 @@ public void RemoveAt(int index) throw PSTraceSource.NewArgumentOutOfRangeException("index", index, PSDataBufferStrings.IndexOutOfRange, 0, _data.Count - 1); } + RemoveItem(index); } } @@ -1051,6 +1062,7 @@ object IList.this[int index] { return this[index]; } + set { PSDataCollection.VerifyValueType(value); @@ -1320,6 +1332,7 @@ internal WaitHandle WaitHandle } } } + return _readWaitHandle; } } @@ -1596,6 +1609,7 @@ private int InternalIndexOf(T item) return index; } } + return -1; } @@ -1701,6 +1715,7 @@ internal int RefCount { return _refCount; } + set { lock (SyncObject) @@ -1776,6 +1791,7 @@ protected void Dispose(bool disposing) { return; } + _isDisposed = true; } @@ -1932,6 +1948,7 @@ public bool MoveNext(bool block) { _collToEnumerate[_index] = default(W); } + _index++; return true; } @@ -2025,11 +2042,13 @@ internal PSInformationalBuffers(Guid psInstanceId) internal PSDataCollection Progress { get { return progress; } + set { progress = value; } } + internal PSDataCollection progress; /// @@ -2039,11 +2058,13 @@ internal PSDataCollection Progress internal PSDataCollection Verbose { get { return verbose; } + set { verbose = value; } } + internal PSDataCollection verbose; /// @@ -2053,11 +2074,13 @@ internal PSDataCollection Verbose internal PSDataCollection Debug { get { return debug; } + set { debug = value; } } + internal PSDataCollection debug; /// diff --git a/src/System.Management.Automation/engine/hostifaces/Parameter.cs b/src/System.Management.Automation/engine/hostifaces/Parameter.cs index d71b0f83945..e5adfb37743 100644 --- a/src/System.Management.Automation/engine/hostifaces/Parameter.cs +++ b/src/System.Management.Automation/engine/hostifaces/Parameter.cs @@ -59,6 +59,7 @@ public CommandParameter(string name, object value) { Name = null; } + Value = value; } @@ -110,6 +111,7 @@ internal static CommandParameter FromCommandParameterInternal(CommandParameterIn { return new CommandParameter(name, internalParameter.ArgumentValue); } + if (name != null) // either a switch parameter or first part of parameter+argument { return new CommandParameter(name); @@ -156,6 +158,7 @@ internal static CommandParameterInternal ToCommandParameterInternal(CommandParam spaceAfterParameter = true; endPosition--; } + Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it"); // now make sure that parameterText doesn't have whitespace at the end, diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index 05a0af4b3d6..ae541b9d7bd 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -341,6 +341,7 @@ internal Pipeline(Runspace runspace, CommandCollection command) internal virtual bool IsChild { get { return false; } + set { } } @@ -398,6 +399,7 @@ public virtual bool HadErrors { get { return _hadErrors; } } + private bool _hadErrors; internal void SetHadErrors(bool status) diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index ff577bc2566..1f4aaffab7b 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -353,12 +353,14 @@ public PSHost Host { return _host; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Host"); } + _host = value; } } @@ -660,6 +662,7 @@ internal PowerShell(ConnectCommandInfo connectCmdInfo, object rsConnection) { _runspacePool = (RunspacePool)rsConnection; } + Dbg.Assert(_runspacePool != null, "Invalid rsConnection parameter>"); RemotePowerShell = new ClientRemotePowerShell(this, _runspacePool.RemoteRunspacePoolInternal); } @@ -831,6 +834,7 @@ public static PowerShell Create(RunspaceMode runspace) { throw new InvalidOperationException(PowerShellStrings.NoDefaultRunspaceForPSCreate); } + result = new PowerShell(new PSCommand(), null, Runspace.DefaultRunspace); result.IsChild = true; result.IsNested = true; @@ -1129,6 +1133,7 @@ public PowerShell AddCommand(CommandInfo commandInfo) { throw PSTraceSource.NewArgumentNullException("commandInfo"); } + Command cmd = new Command(commandInfo); _psCommand.AddCommand(cmd); return this; @@ -1426,6 +1431,7 @@ public PSCommand Commands { throw PSTraceSource.NewArgumentNullException("Command"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1468,6 +1474,7 @@ internal PSDataCollection ErrorBuffer { throw PSTraceSource.NewArgumentNullException("Error"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1502,6 +1509,7 @@ internal PSDataCollection ProgressBuffer { throw PSTraceSource.NewArgumentNullException("Progress"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1535,6 +1543,7 @@ internal PSDataCollection VerboseBuffer { throw PSTraceSource.NewArgumentNullException("Verbose"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1568,6 +1577,7 @@ internal PSDataCollection DebugBuffer { throw PSTraceSource.NewArgumentNullException("Debug"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1604,6 +1614,7 @@ internal PSDataCollection WarningBuffer { throw PSTraceSource.NewArgumentNullException("Warning"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1640,6 +1651,7 @@ internal PSDataCollection InformationBuffer { throw PSTraceSource.NewArgumentNullException("Information"); } + lock (_syncObject) { AssertChangesAreAccepted(); @@ -1798,6 +1810,7 @@ private void SetRunspace(Runspace runspace, bool owner) RemotePowerShell.Clear(); RemotePowerShell.Dispose(); } + RemotePowerShell = new ClientRemotePowerShell(this, remoteRunspace.RunspacePool.RemoteRunspacePoolInternal); } @@ -1859,9 +1872,11 @@ public RunspacePool RunspacePool RemotePowerShell.Clear(); RemotePowerShell.Dispose(); } + RemotePowerShell = new ClientRemotePowerShell(this, _runspacePool.RemoteRunspacePoolInternal); } + _runspace = null; } } @@ -1979,6 +1994,7 @@ public IAsyncResult ConnectAsync( OutputBuffer = new PSDataCollection(); OutputBufferOwner = true; } + streamToUse = OutputBuffer; ObjectStreamBase outputStream = new PSDataCollectionStream(InstanceId, streamToUse); @@ -2052,6 +2068,7 @@ public IAsyncResult ConnectAsync( { throw poolException.ToInvalidRunspaceStateException(); } + throw; } @@ -2169,8 +2186,10 @@ internal void InvokeWithDebugger( { settings = new PSInvocationSettings(); } + settings.AddToHistory = true; } + Invoke(input, output, settings); } } @@ -2770,6 +2789,7 @@ public void Invoke(PSDataCollection input, PSDataCollec { throw PSTraceSource.NewArgumentNullException("output"); } + CoreInvoke(input, output, settings); } @@ -3416,6 +3436,7 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) { throw exception.ToInvalidRunspaceStateException(); } + throw; } } @@ -3935,6 +3956,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { return; } + break; case PSInvocationState.Stopping: // We are in stopping state and we should not honor Running state @@ -3949,6 +3971,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { copyStateInfo = new PSInvocationStateInfo(PSInvocationState.Stopped, stateInfo.Reason); } + break; default: break; @@ -4023,6 +4046,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) tempStopAsyncResult.Release(); } } + break; case PSInvocationState.Disconnected: try @@ -4197,8 +4221,10 @@ private void CoreInvoke(IEnumerable input, PSDataCollection ou { inputBuffer.Add(o); } + inputBuffer.Complete(); } + CoreInvoke(inputBuffer, output, settings); } @@ -4282,6 +4308,7 @@ private void CoreInvokeHelper(PSDataCollection input, P { throw poolException.ToInvalidRunspaceStateException(); } + throw; } } @@ -4546,6 +4573,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i inputStream = new ObjectStream(); inputStream.Close(); } + RemotePowerShell.Initialize( inputStream, new PSDataCollectionStream(InstanceId, output), new PSDataCollectionStream(InstanceId, _errorBuffer), @@ -4557,6 +4585,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i { RemotePowerShell.InputStream = inputStream; } + if (output != null) { RemotePowerShell.OutputStream = @@ -4594,6 +4623,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i throw e; } + _worker.CreateRunspaceIfNeededAndDoWork(rs, false); } else @@ -4623,6 +4653,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i { throw poolException.ToInvalidRunspaceStateException(); } + throw; } @@ -4796,6 +4827,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st _stopAsyncResult = new PowerShellAsyncResult(InstanceId, callback, state, null, false); _stopAsyncResult.SetAsCompleted(null); } + return _stopAsyncResult; case PSInvocationState.Running: @@ -4824,6 +4856,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st // Since object is stopped, allow result wait to end. _invokeAsyncResult.SetAsCompleted(null); } + _stopAsyncResult.SetAsCompleted(null); // Raise event for failed state change. @@ -5196,6 +5229,7 @@ internal void RunspaceAvailableCallback(IAsyncResult asyncResult) return; _isNotActive = true; } + _shell.PipelineStateChanged(this, new PipelineStateEventArgs( new PipelineStateInfo(PipelineState.Failed, @@ -5314,6 +5348,7 @@ internal void Stop(bool isSyncCall) { CurrentlyRunningPipeline.StopAsync(); } + return; } @@ -5668,6 +5703,7 @@ internal CimInstance AsPSPowerShellPipeline() { _worker.GetSettings(out addToHistoryValue, out noInputValue, out apartmentStateValue); } + CimProperty addToHistoryProperty = InternalMISerializer.CreateCimProperty("AddToHistory", addToHistoryValue, Microsoft.Management.Infrastructure.CimType.Boolean); @@ -5915,6 +5951,7 @@ internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { throw new ArgumentNullException("context"); } + if (powerShell == null) { throw new ArgumentNullException("powerShell"); diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 6c1671d6382..e7ace3aad53 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -209,6 +209,7 @@ internal RunspacePool RunspacePool return _runspacePool; } } + set { lock (_syncObject) @@ -239,6 +240,7 @@ internal void Start() _started = true; Process.Exited += ProcessExited; } + Process.Start(); } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs index 5469e83f263..4cc0cd3fd01 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs @@ -46,6 +46,7 @@ public RunspaceInvoke(Runspace runspace) { throw PSTraceSource.NewArgumentNullException("runspace"); } + _runspace = runspace; if (Runspace.DefaultRunspace == null) { @@ -84,6 +85,7 @@ public Collection Invoke(string script, IEnumerable input) { throw PSTraceSource.NewArgumentNullException("script"); } + Pipeline p = _runspace.CreatePipeline(script); return p.Invoke(input); } @@ -112,6 +114,7 @@ public Collection Invoke(string script, IEnumerable input, out IList e { throw PSTraceSource.NewArgumentNullException("script"); } + Pipeline p = _runspace.CreatePipeline(script); Collection output = p.Invoke(input); // 2004/06/30-JonN was ReadAll() which was non-blocking @@ -151,6 +154,7 @@ protected virtual void Dispose(bool disposing) _runspace = null; } } + _disposed = true; } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 5937df851e0..7961c3db3cd 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -463,6 +463,7 @@ internal bool IsActive return _isActive; } } + set { lock (SyncObject) @@ -713,6 +714,7 @@ public RunspaceConnectionInfo ConnectionInfo public TimeSpan CleanupInterval { get { return _internalPool.CleanupInterval; } + set { _internalPool.CleanupInterval = value; } } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index 2326487e35a..8d77a72c331 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -279,6 +279,7 @@ public virtual RunspaceConnectionInfo ConnectionInfo public TimeSpan CleanupInterval { get { return _cleanupInterval; } + set { lock (this.syncObject) @@ -831,6 +832,7 @@ public virtual void Dispose(bool disposing) _initialSessionState = null; host = null; } + _isDisposed = true; } } diff --git a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs index 224715f0340..cf7b5c10f2c 100644 --- a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs +++ b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs @@ -65,6 +65,7 @@ PSCredentialUIOptions options { throw; } + lpl.Stopper.Stop(); } diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index 8d0e4213f16..16b7c69b830 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -130,6 +130,7 @@ protected PipelineBase(PipelineBase pipeline) { throw PSTraceSource.NewArgumentNullException("pipeline"); } + if (pipeline._disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); @@ -323,6 +324,7 @@ private void CoreStop(bool syncCall) { PipelineFinishedEvent.WaitOne(); } + return; } @@ -504,6 +506,7 @@ private void CoreInvoke(IEnumerable input, bool syncCall) InputStream.Write(temp); } } + InputStream.Close(); } From 60debb2bea60e618b2fe3f006e812cd1aa60b0b5 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:08 -0800 Subject: [PATCH 63/81] Update interpreter --- .../engine/interpreter/AddInstruction.cs | 2 + .../engine/interpreter/ArrayOperations.cs | 7 +++ .../engine/interpreter/BranchLabel.cs | 3 + .../interpreter/CallInstruction.Generated.cs | 57 +++++++++++++++++++ .../engine/interpreter/CallInstruction.cs | 6 ++ .../interpreter/ControlFlowInstructions.cs | 13 +++++ .../engine/interpreter/DivInstruction.cs | 1 + .../engine/interpreter/DynamicInstructionN.cs | 1 + .../DynamicInstructions.Generated.cs | 16 ++++++ .../interpreter/DynamicSplatInstruction.cs | 1 + .../engine/interpreter/EqualInstruction.cs | 1 + .../engine/interpreter/FieldOperations.cs | 3 + .../interpreter/GreaterThanInstruction.cs | 1 + .../engine/interpreter/Instruction.cs | 6 ++ .../engine/interpreter/InstructionFactory.cs | 1 + .../engine/interpreter/InstructionList.cs | 6 ++ .../engine/interpreter/InterpretedFrame.cs | 3 + .../engine/interpreter/Interpreter.cs | 1 + .../engine/interpreter/LabelInfo.cs | 8 +++ .../engine/interpreter/LessThanInstruction.cs | 1 + .../engine/interpreter/LightCompiler.cs | 29 ++++++++++ .../interpreter/LightDelegateCreator.cs | 3 + .../interpreter/LightLambda.Generated.cs | 47 +++++++++++++++ .../engine/interpreter/LightLambda.cs | 3 + .../interpreter/LightLambdaClosureVisitor.cs | 9 +++ .../engine/interpreter/LocalAccess.cs | 8 +++ .../engine/interpreter/LocalVariables.cs | 7 +++ .../engine/interpreter/LoopCompiler.cs | 5 ++ .../engine/interpreter/MulInstruction.cs | 2 + .../engine/interpreter/NotEqualInstruction.cs | 1 + .../interpreter/NumericConvertInstruction.cs | 1 + .../interpreter/PowerShellInstructions.cs | 1 + .../engine/interpreter/RuntimeVariables.cs | 1 + .../engine/interpreter/StackOperations.cs | 1 + .../engine/interpreter/SubInstruction.cs | 2 + .../engine/interpreter/TypeOperations.cs | 9 +++ .../engine/interpreter/Utilities.cs | 21 +++++++ 37 files changed, 288 insertions(+) diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 445e8d61bcb..5af328509d1 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -22,6 +22,7 @@ internal abstract class AddInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private AddInstruction() @@ -154,6 +155,7 @@ internal abstract class AddOvfInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private AddOvfInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs b/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs index f85482522c5..8d8ffd8468f 100644 --- a/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs @@ -25,6 +25,7 @@ internal NewArrayInitInstruction(int elementCount) } public override int ConsumedStack { get { return _elementCount; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -34,6 +35,7 @@ public override int Run(InterpretedFrame frame) { array[i] = (TElement)frame.Pop(); } + frame.Push(array); return +1; } @@ -44,6 +46,7 @@ internal sealed class NewArrayInstruction : Instruction internal NewArrayInstruction() { } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -66,6 +69,7 @@ internal NewArrayBoundsInstruction(Type elementType, int rank) } public override int ConsumedStack { get { return _rank; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -75,6 +79,7 @@ public override int Run(InterpretedFrame frame) { lengths[i] = (int)frame.Pop(); } + var array = Array.CreateInstance(_elementType, lengths); frame.Push(array); return +1; @@ -86,6 +91,7 @@ internal sealed class GetArrayItemInstruction : Instruction internal GetArrayItemInstruction() { } public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -107,6 +113,7 @@ internal sealed class SetArrayItemInstruction : Instruction internal SetArrayItemInstruction() { } public override int ConsumedStack { get { return 3; } } + public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index e5fe6f9e09d..89b00785b18 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -59,6 +59,7 @@ public BranchLabel() internal int LabelIndex { get { return _labelIndex; } + set { _labelIndex = value; } } @@ -97,6 +98,7 @@ internal void Mark(InstructionList instructions) { FixupBranch(instructions, branchIndex); } + _forwardBranchFixups = null; } } @@ -112,6 +114,7 @@ internal void AddBranch(InstructionList instructions, int branchIndex) { _forwardBranchFixups = new List(); } + _forwardBranchFixups.Add(branchIndex); } else diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs index 1d1baab5d91..ee1c1bf8b03 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs @@ -68,14 +68,23 @@ public virtual object Invoke(params object[] args) { } public virtual object Invoke() { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { throw new InvalidOperationException(); } + public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { throw new InvalidOperationException(); } /// @@ -105,6 +114,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) // if we're on the return type relaxed delegates makes it ok to use object goto default; } + return FastCreate(target, pi); } case TypeCode.Int16: return FastCreate(target, pi); @@ -132,6 +142,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] if (target.ReturnType == typeof(void)) { return new ActionCallInstruction(target); } + return new FuncCallInstruction(target); } @@ -142,6 +153,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] // if we're on the return type relaxed delegates makes it ok to use object goto default; } + return FastCreate(target, pi); } case TypeCode.Int16: return FastCreate(target, pi); @@ -169,6 +181,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterIn if (target.ReturnType == typeof(void)) { return new ActionCallInstruction(target); } + return new FuncCallInstruction(target); } @@ -230,13 +243,16 @@ private static Type GetHelperType(MethodInfo info, Type[] arrTypes) { default: throw new InvalidOperationException(); } } + return t; } + public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); lock (s_cache) { s_cache[info] = new FuncCallInstruction(method); } + return info; } @@ -245,6 +261,7 @@ public static MethodInfo CacheFunc(Func method) { lock (s_cache) { s_cache[info] = new FuncCallInstruction(method); } + return info; } @@ -253,6 +270,7 @@ public static MethodInfo CacheFunc(Func method) { lock (s_cache) { s_cache[info] = new FuncCallInstruction(method); } + return info; } @@ -261,6 +279,7 @@ public static MethodInfo CacheFunc(Func meth lock (s_cache) { s_cache[info] = new FuncCallInstruction(method); } + return info; } @@ -269,6 +288,7 @@ public static MethodInfo CacheFunc(Func(method); } + return info; } @@ -277,6 +297,7 @@ public static MethodInfo CacheFunc(Func(method); } + return info; } @@ -285,6 +306,7 @@ public static MethodInfo CacheFunc(Func(method); } + return info; } @@ -293,6 +315,7 @@ public static MethodInfo CacheFunc(Func(method); } + return info; } @@ -301,6 +324,7 @@ public static MethodInfo CacheFunc(Func(method); } + return info; } @@ -309,6 +333,7 @@ public static MethodInfo CacheFunc(Fun lock (s_cache) { s_cache[info] = new FuncCallInstruction(method); } + return info; } @@ -317,6 +342,7 @@ public static MethodInfo CacheAction(Action method) { lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -325,6 +351,7 @@ public static MethodInfo CacheAction(Action method) { lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -333,6 +360,7 @@ public static MethodInfo CacheAction(Action method) { lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -341,6 +369,7 @@ public static MethodInfo CacheAction(Action method) { lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -349,6 +378,7 @@ public static MethodInfo CacheAction(Action meth lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -357,6 +387,7 @@ public static MethodInfo CacheAction(Action(method); } + return info; } @@ -365,6 +396,7 @@ public static MethodInfo CacheAction(Action(method); } + return info; } @@ -373,6 +405,7 @@ public static MethodInfo CacheAction(Action(method); } + return info; } @@ -381,6 +414,7 @@ public static MethodInfo CacheAction(Action(method); } + return info; } @@ -389,6 +423,7 @@ public static MethodInfo CacheAction(Action< lock (s_cache) { s_cache[info] = new ActionCallInstruction(method); } + return info; } @@ -397,6 +432,7 @@ public static MethodInfo CacheAction(Action< internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 0; } } public ActionCallInstruction(Action target) { @@ -422,6 +458,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 1; } } public ActionCallInstruction(Action target) { @@ -447,6 +484,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 2; } } public ActionCallInstruction(Action target) { @@ -472,6 +510,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 3; } } public ActionCallInstruction(Action target) { @@ -497,6 +536,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 4; } } public ActionCallInstruction(Action target) { @@ -522,6 +562,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 5; } } public ActionCallInstruction(Action target) { @@ -547,6 +588,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 6; } } public ActionCallInstruction(Action target) { @@ -572,6 +614,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 7; } } public ActionCallInstruction(Action target) { @@ -597,6 +640,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 8; } } public ActionCallInstruction(Action target) { @@ -622,6 +666,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 9; } } public ActionCallInstruction(Action target) { @@ -647,6 +692,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 0; } } public FuncCallInstruction(Func target) { @@ -671,6 +717,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 1; } } public FuncCallInstruction(Func target) { @@ -695,6 +742,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 2; } } public FuncCallInstruction(Func target) { @@ -719,6 +767,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 3; } } public FuncCallInstruction(Func target) { @@ -743,6 +792,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 4; } } public FuncCallInstruction(Func target) { @@ -767,6 +817,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 5; } } public FuncCallInstruction(Func target) { @@ -791,6 +842,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 6; } } public FuncCallInstruction(Func target) { @@ -815,6 +867,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 7; } } public FuncCallInstruction(Func target) { @@ -839,6 +892,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 8; } } public FuncCallInstruction(Func target) { @@ -863,6 +917,7 @@ public override int Run(InterpretedFrame frame) { internal sealed class FuncCallInstruction : CallInstruction { private readonly Func _target; public override MethodInfo Info { get { return _target.GetMethodInfo(); } } + public override int ArgumentCount { get { return 9; } } public FuncCallInstruction(Func target) { @@ -888,9 +943,11 @@ internal sealed partial class MethodInfoCallInstruction : CallInstruction { public override object Invoke() { return InvokeWorker(); } + public override object Invoke(object arg0) { return InvokeWorker(arg0); } + public override object Invoke(object arg0, object arg1) { return InvokeWorker(arg0, arg1); } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs index 3bac9e5df09..b9f8a3796d0 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs @@ -227,10 +227,12 @@ private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { types.Add(pi.ParameterType); } + if (info.ReturnType != typeof(void)) { types.Add(info.ReturnType); } + Type[] arrTypes = types.ToArray(); return (CallInstruction)Activator.CreateInstance(GetHelperType(info, arrTypes), info); @@ -241,6 +243,7 @@ private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) #region Instruction public sealed override int ProducedStack { get { return Info.ReturnType == typeof(void) ? 0 : 1; } } + public sealed override int ConsumedStack { get { return ArgumentCount; } } public sealed override string InstructionName @@ -262,6 +265,7 @@ internal sealed partial class MethodInfoCallInstruction : CallInstruction private readonly int _argumentCount; public override MethodInfo Info { get { return _target; } } + public override int ArgumentCount { get { return _argumentCount; } } internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) @@ -330,6 +334,7 @@ private static object[] GetNonStaticArgs(object[] args) { newArgs[i] = args[i + 1]; } + return newArgs; } @@ -352,6 +357,7 @@ public sealed override int Run(InterpretedFrame frame) { frame.StackIndex = first; } + return 1; } } diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index c6eb5feebfd..1d6eed6ffad 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -35,6 +35,7 @@ internal abstract class OffsetInstruction : Instruction protected int _offset = Unknown; public int Offset { get { return _offset; } } + public abstract Instruction[] Cache { get; } public Instruction Fixup(int offset) @@ -132,6 +133,7 @@ internal CoalescingBranchInstruction() } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -159,6 +161,7 @@ public override Instruction[] Cache { s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } + return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); } } @@ -266,6 +269,7 @@ internal sealed class GotoInstruction : IndexedBranchInstruction // case until the label is emitted. By then the consumed and produced stack information is useless. // The important thing here is that the stack balance is 0. public override int ConsumedContinuations { get { return 0; } } + public override int ProducedContinuations { get { return 0; } } public override int ConsumedStack @@ -292,6 +296,7 @@ internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasV var index = Variants * labelIndex | (hasResult ? 2 : 0) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue)); } + return new GotoInstruction(labelIndex, hasResult, hasValue); } @@ -328,6 +333,7 @@ internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex) { return new EnterTryCatchFinallyInstruction(labelIndex, true); } + internal static EnterTryCatchFinallyInstruction CreateTryCatch() { return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false); @@ -342,6 +348,7 @@ public override int Run(InterpretedFrame frame) // Push finally. frame.PushContinuation(_labelIndex); } + int prevInstrIndex = frame.InstructionIndex; frame.InstructionIndex++; @@ -464,6 +471,7 @@ internal sealed class EnterFinallyInstruction : IndexedBranchInstruction private static readonly EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize]; public override int ProducedStack { get { return 2; } } + public override int ConsumedContinuations { get { return 1; } } private EnterFinallyInstruction(int labelIndex) @@ -477,6 +485,7 @@ internal static EnterFinallyInstruction Create(int labelIndex) { return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); } + return new EnterFinallyInstruction(labelIndex); } @@ -587,6 +596,7 @@ internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool has int index = (2 * labelIndex) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); } + return new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } @@ -676,6 +686,7 @@ public override int Run(InterpretedFrame frame) // return frame.Interpreter.GotoHandler(frame, ex, out handler); throw new RethrowException(); } + throw ex; } } @@ -691,6 +702,7 @@ internal SwitchInstruction(Dictionary cases) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) @@ -748,6 +760,7 @@ public override int Run(InterpretedFrame frame) ThreadPool.QueueUserWorkItem(Compile, frame); } } + return 1; } diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index e8e60cd4f00..53a6e13316c 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -22,6 +22,7 @@ internal abstract class DivInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private DivInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs b/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs index daa941971b9..3d4686628cf 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs @@ -43,6 +43,7 @@ public DynamicInstructionN(Type delegateType, CallSite site, bool isVoid) } public override int ProducedStack { get { return _isVoid ? 0 : 1; } } + public override int ConsumedStack { get { return _argumentCount; } } public override int Run(InterpretedFrame frame) diff --git a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs index ca17ef48dae..ad10413f9d0 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs @@ -108,6 +108,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 0; } } public override int Run(InterpretedFrame frame) { @@ -133,6 +134,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { @@ -157,6 +159,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 2; } } public override int Run(InterpretedFrame frame) { @@ -182,6 +185,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 3; } } public override int Run(InterpretedFrame frame) { @@ -207,6 +211,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 4; } } public override int Run(InterpretedFrame frame) { @@ -232,6 +237,7 @@ private DynamicInstruction(CallSite> site) { } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 5; } } public override int Run(InterpretedFrame frame) { @@ -257,6 +263,7 @@ private DynamicInstruction(CallSite> site) } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 6; } } public override int Run(InterpretedFrame frame) { @@ -282,6 +289,7 @@ private DynamicInstruction(CallSite> si } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 7; } } public override int Run(InterpretedFrame frame) { @@ -307,6 +315,7 @@ private DynamicInstruction(CallSite> } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return 8; } } public override int Run(InterpretedFrame frame) { @@ -332,6 +341,7 @@ private DynamicInstruction(CallSite(elementCount)); } + return new NewArrayInitInstruction(elementCount); } } diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index dd65d26ac36..88190afd682 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -151,6 +151,7 @@ internal static InstructionView[] GetInstructionViews(IList instruc stackDepth += stackDiff; continuationsDepth += contDiff; } + return result.ToArray(); } @@ -302,6 +303,7 @@ public InstructionArray ToArray() if (!_instances.TryGetValue(name, out dict)) { _instances[name] = dict = new Dictionary(); } + dict[instr] = true; }); } @@ -372,6 +374,7 @@ public void EmitLoad(object value, Type type) { s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } + i -= PushIntMinCachedValue; Emit(s_ints[i] ?? (s_ints[i] = new LoadObjectInstruction(value))); return; @@ -937,8 +940,10 @@ private Instruction GetLoadField(FieldInfo field) { instruction = new LoadFieldInstruction(field); } + s_loadFields.Add(field, instruction); } + return instruction; } } @@ -1088,6 +1093,7 @@ internal static Instruction CreateDynamicInstruction(Type delegateType, CallSite s_factories[delegateType] = factory; } } + return factory(binder); } diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 7f89a41edcd..6254f22b2e2 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -159,12 +159,14 @@ public static IEnumerable GroupStackFrames(IEnumerable s { continue; } + inInterpretedFrame = true; } else { inInterpretedFrame = false; } + yield return frame; } } @@ -323,6 +325,7 @@ public int Goto(int labelIndex, object value, bool gotoExceptionHandler) { Data[StackIndex - 1] = value; } + return target.Index - InstructionIndex; } diff --git a/src/System.Management.Automation/engine/interpreter/Interpreter.cs b/src/System.Management.Automation/engine/interpreter/Interpreter.cs index 02ca997b2eb..0f6f640787e 100644 --- a/src/System.Management.Automation/engine/interpreter/Interpreter.cs +++ b/src/System.Management.Automation/engine/interpreter/Interpreter.cs @@ -75,6 +75,7 @@ internal int ClosureSize { return 0; } + return ClosureVariables.Count; } } diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index 2bcf53ece86..8a1e07b3bfd 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -121,6 +121,7 @@ private void ValidateJump(LabelScopeInfo reference) // found it, jump is valid! return; } + if (j.Kind == LabelScopeKind.Filter) { break; @@ -193,6 +194,7 @@ private bool DefinedIn(LabelScopeInfo scope) { return definitions.Contains(scope); } + return false; } @@ -211,6 +213,7 @@ private LabelScopeInfo FirstDefinition() { return scope; } + return ((HashSet)_definitions).First(); } @@ -227,6 +230,7 @@ private void AddDefinition(LabelScopeInfo scope) { _definitions = set = new HashSet() { (LabelScopeInfo)_definitions }; } + set.Add(scope); } } @@ -246,11 +250,13 @@ internal static T CommonNode(T first, T second, Func parent) where T : { return first; } + var set = new HashSet(cmp); for (T t = first; t != null; t = parent(t)) { set.Add(t); } + for (T t = second; t != null; t = parent(t)) { if (set.Contains(t)) @@ -258,6 +264,7 @@ internal static T CommonNode(T first, T second, Func parent) where T : return t; } } + return null; } } @@ -322,6 +329,7 @@ internal bool CanJumpInto case LabelScopeKind.Lambda: return true; } + return false; } } diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index 992f30eb579..1d5d263eb14 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -22,6 +22,7 @@ internal abstract class LessThanInstruction : Instruction private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private LessThanInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 048f48df304..82bebc2da19 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -62,6 +62,7 @@ public bool Matches(Type exceptionType) { return true; } + return false; } @@ -168,6 +169,7 @@ internal int GotoHandler(InterpretedFrame frame, object exception, out Exception Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called"); handler = _handlers.FirstOrDefault(t => t.Matches(exception.GetType())); if (handler == null) { return 0; } + return frame.Goto(handler.LabelIndex, exception, gotoExceptionHandler: true); } } @@ -409,6 +411,7 @@ private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) { _locals.Box(expr, _instructions); } + return local; } else if (_parent != null) @@ -435,6 +438,7 @@ private LocalVariable ResolveLocal(ParameterExpression variable) { local = EnsureAvailableForClosure(variable); } + return local; } @@ -563,6 +567,7 @@ private LocalDefinition[] CompileBlockStart(BlockExpression node) { CompileAsVoid(node.Expressions[i]); } + return locals; } @@ -657,6 +662,7 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { Compile(member.Expression); } + Compile(node.Right); int start = _instructions.Count; @@ -672,6 +678,7 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { _instructions.EmitCall(method); } + return; } @@ -682,6 +689,7 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { Compile(member.Expression); } + Compile(node.Right); int start = _instructions.Count; @@ -697,6 +705,7 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { _instructions.EmitStoreField(fi); } + return; } @@ -888,6 +897,7 @@ private void CompileConvertToType(Type typeFrom, Type typeTo, bool isChecked) { _instructions.EmitNumericConvertUnchecked(from, to); } + return; } @@ -967,6 +977,7 @@ private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) { _instructions.EmitBranchTrue(elseLabel); } + Compile(node.Right); _instructions.EmitBranch(endLabel, false, true); _instructions.MarkLabel(elseLabel); @@ -1056,6 +1067,7 @@ private void CompileSwitchExpression(Expression expr) { throw new NotImplementedException(); } + LabelInfo end = DefineLabel(null); bool hasValue = node.Type != typeof(void); @@ -1072,6 +1084,7 @@ private void CompileSwitchExpression(Expression expr) { Debug.Assert(!hasValue); } + _instructions.EmitBranch(end.GetLabel(this), false, hasValue); for (int i = 0; i < node.Cases.Count; i++) @@ -1176,6 +1189,7 @@ private LabelInfo EnsureLabel(LabelTarget node) { _treeLabels[node] = result = new LabelInfo(node); } + return result; } @@ -1192,6 +1206,7 @@ internal LabelInfo DefineLabel(LabelTarget node) { return new LabelInfo(null); } + LabelInfo result = EnsureLabel(node); result.Define(_labelBlock); return result; @@ -1213,6 +1228,7 @@ private bool TryPushLabelBlock(Expression node) PushLabelBlock(LabelScopeKind.Expression); return true; } + return false; case ExpressionType.Label: // LabelExpression is a bit special, if it's directly in a @@ -1225,12 +1241,14 @@ private bool TryPushLabelBlock(Expression node) { return false; } + if (_labelBlock.Parent.Kind == LabelScopeKind.Switch && _labelBlock.Parent.ContainsTarget(label)) { return false; } } + PushLabelBlock(LabelScopeKind.Statement); return true; case ExpressionType.Block: @@ -1241,6 +1259,7 @@ private bool TryPushLabelBlock(Expression node) { DefineBlockLabels(node); } + return true; case ExpressionType.Switch: PushLabelBlock(LabelScopeKind.Switch); @@ -1253,6 +1272,7 @@ private bool TryPushLabelBlock(Expression node) SwitchCase c = @switch.Cases[index]; DefineBlockLabels(c.Body); } + DefineBlockLabels(@switch.DefaultBody); return true; @@ -1263,6 +1283,7 @@ private bool TryPushLabelBlock(Expression node) // treat it as an expression goto default; } + PushLabelBlock(LabelScopeKind.Statement); return true; @@ -1301,6 +1322,7 @@ private HybridReferenceDictionary GetBranchMapping() { newLabelMapping[kvp.Key] = kvp.Value.GetLabel(this); } + return newLabelMapping; } @@ -1348,6 +1370,7 @@ private bool EndsWithRethrow(Expression expr) { return EndsWithRethrow(block.Expressions[block.Expressions.Count - 1]); } + return false; } @@ -1591,6 +1614,7 @@ private void CompileNewExpression(Expression expr) var arg = node.Arguments[index]; this.Compile(arg); } + _instructions.EmitNew(node.Constructor); } else @@ -1628,6 +1652,7 @@ private void CompileMemberExpression(Expression expr) Compile(node.Expression); _instructions.EmitLoadField(fi); } + return; } @@ -1639,6 +1664,7 @@ private void CompileMemberExpression(Expression expr) { Compile(node.Expression); } + _instructions.EmitCall(method); return; } @@ -1741,6 +1767,7 @@ private void CompileLambdaExpression(Expression expr) CompileGetBoxedVariable(variable); } } + _instructions.EmitCreateDelegate(creator); } @@ -1903,8 +1930,10 @@ internal void CompileAsVoid(Expression expr) { _instructions.EmitPop(); } + break; } + Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth); if (pushLabelBlock) { diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index 847030a4cd4..cee0480c20a 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -120,6 +120,7 @@ private Type DelegateType { return le.Type; } + return null; //return ((LightLambdaExpression)_lambda).Type; } @@ -138,6 +139,7 @@ internal Delegate CreateCompiledDelegate(StrongBox[] closure) var applyClosure = (Func[], Delegate>)_compiled; return applyClosure(closure); } + return _compiled; } @@ -210,6 +212,7 @@ private static Type GetFuncOrAction(LambdaExpression lambda) return delegateType; } } + return lambda.Type; //} } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs b/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs index fae037ab9f0..7ff5de773c5 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs @@ -33,6 +33,7 @@ internal TRet Run0() { var frame = MakeFrame(); var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -50,9 +51,11 @@ internal void RunVoid0() { internal static Delegate MakeRun0(LightLambda lambda) { return new Func(lambda.Run0); } + internal static Delegate MakeRunVoid0(LightLambda lambda) { return new Action(lambda.RunVoid0); } + internal TRet Run1(T0 arg0) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0); @@ -62,6 +65,7 @@ internal TRet Run1(T0 arg0) { frame.Data[0] = arg0; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -80,9 +84,11 @@ internal void RunVoid1(T0 arg0) { internal static Delegate MakeRun1(LightLambda lambda) { return new Func(lambda.Run1); } + internal static Delegate MakeRunVoid1(LightLambda lambda) { return new Action(lambda.RunVoid1); } + internal TRet Run2(T0 arg0,T1 arg1) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1); @@ -93,6 +99,7 @@ internal TRet Run2(T0 arg0,T1 arg1) { frame.Data[1] = arg1; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -112,9 +119,11 @@ internal void RunVoid2(T0 arg0,T1 arg1) { internal static Delegate MakeRun2(LightLambda lambda) { return new Func(lambda.Run2); } + internal static Delegate MakeRunVoid2(LightLambda lambda) { return new Action(lambda.RunVoid2); } + internal TRet Run3(T0 arg0,T1 arg1,T2 arg2) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2); @@ -126,6 +135,7 @@ internal TRet Run3(T0 arg0,T1 arg1,T2 arg2) { frame.Data[2] = arg2; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -146,9 +156,11 @@ internal void RunVoid3(T0 arg0,T1 arg1,T2 arg2) { internal static Delegate MakeRun3(LightLambda lambda) { return new Func(lambda.Run3); } + internal static Delegate MakeRunVoid3(LightLambda lambda) { return new Action(lambda.RunVoid3); } + internal TRet Run4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3); @@ -161,6 +173,7 @@ internal TRet Run4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { frame.Data[3] = arg3; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -182,9 +195,11 @@ internal void RunVoid4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { internal static Delegate MakeRun4(LightLambda lambda) { return new Func(lambda.Run4); } + internal static Delegate MakeRunVoid4(LightLambda lambda) { return new Action(lambda.RunVoid4); } + internal TRet Run5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4); @@ -198,6 +213,7 @@ internal TRet Run5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) frame.Data[4] = arg4; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -220,9 +236,11 @@ internal void RunVoid5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) internal static Delegate MakeRun5(LightLambda lambda) { return new Func(lambda.Run5); } + internal static Delegate MakeRunVoid5(LightLambda lambda) { return new Action(lambda.RunVoid5); } + internal TRet Run6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5); @@ -237,6 +255,7 @@ internal TRet Run6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 ar frame.Data[5] = arg5; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -260,9 +279,11 @@ internal void RunVoid6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg internal static Delegate MakeRun6(LightLambda lambda) { return new Func(lambda.Run6); } + internal static Delegate MakeRunVoid6(LightLambda lambda) { return new Action(lambda.RunVoid6); } + internal TRet Run7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6); @@ -278,6 +299,7 @@ internal TRet Run7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 frame.Data[6] = arg6; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -302,9 +324,11 @@ internal void RunVoid7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 internal static Delegate MakeRun7(LightLambda lambda) { return new Func(lambda.Run7); } + internal static Delegate MakeRunVoid7(LightLambda lambda) { return new Action(lambda.RunVoid7); } + internal TRet Run8(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); @@ -321,6 +345,7 @@ internal TRet Run8(T0 arg0,T1 arg1,T2 arg2,T3 arg3 frame.Data[7] = arg7; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -346,9 +371,11 @@ internal void RunVoid8(T0 arg0,T1 arg1,T2 arg2,T3 arg3, internal static Delegate MakeRun8(LightLambda lambda) { return new Func(lambda.Run8); } + internal static Delegate MakeRunVoid8(LightLambda lambda) { return new Action(lambda.RunVoid8); } + internal TRet Run9(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); @@ -366,6 +393,7 @@ internal TRet Run9(T0 arg0,T1 arg1,T2 arg2,T3 a frame.Data[8] = arg8; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -392,9 +420,11 @@ internal void RunVoid9(T0 arg0,T1 arg1,T2 arg2,T3 ar internal static Delegate MakeRun9(LightLambda lambda) { return new Func(lambda.Run9); } + internal static Delegate MakeRunVoid9(LightLambda lambda) { return new Action(lambda.RunVoid9); } + internal TRet Run10(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); @@ -413,6 +443,7 @@ internal TRet Run10(T0 arg0,T1 arg1,T2 arg2, frame.Data[9] = arg9; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -440,9 +471,11 @@ internal void RunVoid10(T0 arg0,T1 arg1,T2 arg2,T internal static Delegate MakeRun10(LightLambda lambda) { return new Func(lambda.Run10); } + internal static Delegate MakeRunVoid10(LightLambda lambda) { return new Action(lambda.RunVoid10); } + internal TRet Run11(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); @@ -462,6 +495,7 @@ internal TRet Run11(T0 arg0,T1 arg1,T2 a frame.Data[10] = arg10; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -490,9 +524,11 @@ internal void RunVoid11(T0 arg0,T1 arg1,T2 ar internal static Delegate MakeRun11(LightLambda lambda) { return new Func(lambda.Run11); } + internal static Delegate MakeRunVoid11(LightLambda lambda) { return new Action(lambda.RunVoid11); } + internal TRet Run12(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); @@ -513,6 +549,7 @@ internal TRet Run12(T0 arg0,T1 arg1, frame.Data[11] = arg11; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -542,9 +579,11 @@ internal void RunVoid12(T0 arg0,T1 arg1,T internal static Delegate MakeRun12(LightLambda lambda) { return new Func(lambda.Run12); } + internal static Delegate MakeRunVoid12(LightLambda lambda) { return new Action(lambda.RunVoid12); } + internal TRet Run13(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); @@ -566,6 +605,7 @@ internal TRet Run13(T0 arg0,T1 a frame.Data[12] = arg12; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -596,9 +636,11 @@ internal void RunVoid13(T0 arg0,T1 ar internal static Delegate MakeRun13(LightLambda lambda) { return new Func(lambda.Run13); } + internal static Delegate MakeRunVoid13(LightLambda lambda) { return new Action(lambda.RunVoid13); } + internal TRet Run14(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); @@ -621,6 +663,7 @@ internal TRet Run14(T0 arg0, frame.Data[13] = arg13; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -652,9 +695,11 @@ internal void RunVoid14(T0 arg0,T internal static Delegate MakeRun14(LightLambda lambda) { return new Func(lambda.Run14); } + internal static Delegate MakeRunVoid14(LightLambda lambda) { return new Action(lambda.RunVoid14); } + internal TRet Run15(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) { if (_compiled != null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); @@ -678,6 +723,7 @@ internal TRet Run15(T0 a frame.Data[14] = arg14; var current = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(current); } + return (TRet)frame.Pop(); } @@ -710,6 +756,7 @@ internal void RunVoid15(T0 ar internal static Delegate MakeRun15(LightLambda lambda) { return new Func(lambda.Run15); } + internal static Delegate MakeRunVoid15(LightLambda lambda) { return new Action(lambda.RunVoid15); } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambda.cs b/src/System.Management.Automation/engine/interpreter/LightLambda.cs index ec907b326d8..08f6ebe32dd 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambda.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambda.cs @@ -73,6 +73,7 @@ private static Func GetRunDelegateCtor(Type delegateType) { return fastCtor; } + return MakeRunDelegateCtor(delegateType); } } @@ -285,6 +286,7 @@ public object Run(params object[] arguments) { frame.Data[i] = arguments[i]; } + var currentFrame = frame.Enter(); try { @@ -294,6 +296,7 @@ public object Run(params object[] arguments) { frame.Leave(currentFrame); } + return frame.Pop(); } } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs index 31a18ba2cb3..465678f2875 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs @@ -93,6 +93,7 @@ protected override Expression VisitLambda(Expression node) { return node; } + return Expression.Lambda(b, node.Name, node.TailCall, node.Parameters); } @@ -102,15 +103,18 @@ protected override Expression VisitBlock(BlockExpression node) { _shadowedVars.Push(new HashSet(node.Variables)); } + var b = Visit(node.Expressions); if (node.Variables.Count > 0) { _shadowedVars.Pop(); } + if (b == node.Expressions) { return node; } + return Expression.Block(node.Variables, b); } @@ -120,16 +124,19 @@ protected override CatchBlock VisitCatchBlock(CatchBlock node) { _shadowedVars.Push(new HashSet(new[] { node.Variable })); } + Expression b = Visit(node.Body); Expression f = Visit(node.Filter); if (node.Variable != null) { _shadowedVars.Pop(); } + if (b == node.Body && f == node.Filter) { return node; } + return Expression.MakeCatchBlock(node.Test, node.Variable, b, f); } @@ -206,6 +213,7 @@ protected override Expression VisitBinary(BinaryExpression node) ); } } + return base.VisitBinary(node); } @@ -274,6 +282,7 @@ object IRuntimeVariables.this[int index] index = _indexes[index]; return (index >= 0) ? _first[index] : _second[-1 - index]; } + set { index = _indexes[index]; diff --git a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs index 26258908696..c2c70f14329 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs @@ -132,6 +132,7 @@ internal AssignLocalInstruction(int index) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -154,6 +155,7 @@ internal StoreLocalInstruction(int index) } public override int ConsumedStack { get { return 1; } } + public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Data[--frame.StackIndex]; @@ -175,6 +177,7 @@ internal AssignLocalBoxedInstruction(int index) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -193,6 +196,7 @@ internal StoreLocalBoxedInstruction(int index) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) @@ -211,6 +215,7 @@ internal AssignLocalToClosureInstruction(int index) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -340,6 +345,7 @@ public Instruction BoxIfIndexMatches(int index) { return InstructionList.ParameterBox(index); } + return null; } @@ -422,6 +428,7 @@ public RuntimeVariablesInstruction(int count) } public override int ProducedStack { get { return 1; } } + public override int ConsumedStack { get { return _count; } } public override int Run(InterpretedFrame frame) @@ -431,6 +438,7 @@ public override int Run(InterpretedFrame frame) { ret[i] = (IStrongBox)frame.Pop(); } + frame.Push(RuntimeVariables.Create(ret)); return +1; } diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index d9b8d33d360..398566c1398 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -36,6 +36,7 @@ internal sealed class LocalVariable public bool IsBoxed { get { return (_flags & IsBoxedFlag) != 0; } + set { if (value) @@ -121,6 +122,7 @@ public override int GetHashCode() { return 0; } + return _parameter.GetHashCode() ^ _index.GetHashCode(); } @@ -162,6 +164,7 @@ public LocalDefinition DefineLocal(ParameterExpression variable, int start) { existing.ChildScopes = new List(); } + existing.ChildScopes.Add(newScope); } else @@ -226,6 +229,7 @@ public int GetOrDefineLocal(ParameterExpression var) { return DefineLocal(var, 0).Index; } + return index; } @@ -243,6 +247,7 @@ public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable loca local = scope.Variable; return true; } + if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) { return true; @@ -263,6 +268,7 @@ internal Dictionary CopyLocals() { res[keyValue.Key] = keyValue.Value.Variable; } + return res; } @@ -291,6 +297,7 @@ internal LocalVariable AddClosureVariable(ParameterExpression variable) { _closureVariables = new Dictionary(); } + LocalVariable result = new LocalVariable(_closureVariables.Count, true, false); _closureVariables.Add(variable, result); return result; diff --git a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs index b6e018f50c4..6ff0e36f5c3 100644 --- a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs @@ -97,6 +97,7 @@ internal LoopFunc CreateDelegate() { local = _closureVariables[variable.Key]; } + Expression elemRef = local.LoadFromArray(_frameDataVar, _frameClosureVar); if (local.InClosureOrBoxed) @@ -256,6 +257,7 @@ protected override Expression VisitBinary(BinaryExpression node) { return Visit(node.Reduce()); } + Debug.Assert(!node.NodeType.IsReadWriteAssignment()); var param = node.Left as ParameterExpression; @@ -273,12 +275,14 @@ protected override Expression VisitBinary(BinaryExpression node) if (right.NodeType != ExpressionType.Parameter) { // { left.Value = (object)(rightVar = right), rightVar } + rightVar = AddTemp(Expression.Parameter(right.Type)); right = Expression.Assign(rightVar, right); } else { // { left.Value = (object)right, right } + rightVar = right; } @@ -305,6 +309,7 @@ protected override Expression VisitUnary(UnaryExpression node) { return Visit(node.Reduce()); } + Debug.Assert(!node.NodeType.IsReadWriteAssignment()); return base.VisitUnary(node); } diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 4c74db7092e..4f67b5be486 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -22,6 +22,7 @@ internal abstract class MulInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private MulInstruction() @@ -154,6 +155,7 @@ internal abstract class MulOvfInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private MulOvfInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index 882815d68c3..4100b8f8cbb 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -23,6 +23,7 @@ internal abstract class NotEqualInstruction : Instruction private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private NotEqualInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs b/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs index f61c512af32..eb37e13413e 100644 --- a/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs @@ -26,6 +26,7 @@ protected NumericConvertInstruction(TypeCode from, TypeCode to) } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override string ToString() diff --git a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs index f579bcaf73f..926f558a72b 100644 --- a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs @@ -39,6 +39,7 @@ public override int Run(InterpretedFrame frame) context.Debugger.OnSequencePointHit(functionContext); } } + return +1; } diff --git a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs index 40fd29333dd..638ff84c2ca 100644 --- a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs @@ -40,6 +40,7 @@ object IRuntimeVariables.this[int index] { return _boxes[index].Value; } + set { _boxes[index].Value = value; diff --git a/src/System.Management.Automation/engine/interpreter/StackOperations.cs b/src/System.Management.Automation/engine/interpreter/StackOperations.cs index 065bbbbf74f..6129fa6332a 100644 --- a/src/System.Management.Automation/engine/interpreter/StackOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/StackOperations.cs @@ -96,6 +96,7 @@ internal sealed class DupInstruction : Instruction private DupInstruction() { } public override int ConsumedStack { get { return 0; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index 78ba259fbca..37503783107 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -22,6 +22,7 @@ internal abstract class SubInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private SubInstruction() @@ -154,6 +155,7 @@ internal abstract class SubOvfInstruction : Instruction private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private SubOvfInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs index 5d50c5c957a..190e89d6e0b 100644 --- a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs @@ -28,6 +28,7 @@ internal CreateDelegateInstruction(LightDelegateCreator delegateCreator) } public override int ConsumedStack { get { return _creator.Interpreter.ClosureSize; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -63,7 +64,9 @@ public NewInstruction(ConstructorInfo constructor) _constructor = constructor; _argCount = constructor.GetParameters().Length; } + public override int ConsumedStack { get { return _argCount; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -84,6 +87,7 @@ public override int Run(InterpretedFrame frame) ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } + frame.Push(ret); return +1; } @@ -99,6 +103,7 @@ internal sealed class DefaultValueInstruction : Instruction internal DefaultValueInstruction() { } public override int ConsumedStack { get { return 0; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -118,6 +123,7 @@ internal sealed class TypeIsInstruction : Instruction internal TypeIsInstruction() { } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -138,6 +144,7 @@ internal sealed class TypeAsInstruction : Instruction internal TypeAsInstruction() { } public override int ConsumedStack { get { return 1; } } + public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) @@ -152,6 +159,7 @@ public override int Run(InterpretedFrame frame) { frame.Push(null); } + return +1; } @@ -166,6 +174,7 @@ internal sealed class TypeEqualsInstruction : Instruction public static readonly TypeEqualsInstruction Instance = new TypeEqualsInstruction(); public override int ConsumedStack { get { return 2; } } + public override int ProducedStack { get { return 1; } } private TypeEqualsInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 7951554ffab..a330da72d08 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -20,6 +20,7 @@ internal static Type GetNonNullableType(this Type type) { return type.GetGenericArguments()[0]; } + return type; } @@ -30,6 +31,7 @@ internal static Type GetNullableType(Type type) { return typeof(Nullable<>).MakeGenericType(type); } + return type; } @@ -64,6 +66,7 @@ internal static bool IsNumeric(Type type) return true; } } + return false; } @@ -84,6 +87,7 @@ internal static bool IsNumeric(TypeCode typeCode) case TypeCode.UInt64: return true; } + return false; } @@ -105,6 +109,7 @@ internal static bool IsArithmetic(Type type) return true; } } + return false; } } @@ -213,6 +218,7 @@ internal static Type MakeDelegate(Type[] types) #endregion } } + throw Assert.Unreachable; } } @@ -405,6 +411,7 @@ public bool TryGetValue(TKey key, out TValue value) } } } + value = default(TValue); return false; } @@ -463,6 +470,7 @@ public int Count { return _dict.Count; } + return _count; } } @@ -505,6 +513,7 @@ public TValue this[TKey key] throw new KeyNotFoundException(); } + set { Debug.Assert(key != null); @@ -550,6 +559,7 @@ public TValue this[TKey key] { _dict[_keysAndValues[i].Key] = _keysAndValues[i].Value; } + _keysAndValues = null; _dict[key] = value; @@ -646,8 +656,10 @@ public TValue this[TKey key] { return res; } + throw new KeyNotFoundException(); } + set { Add(key, value); @@ -703,6 +715,7 @@ public T Value { return GetStorageInfo().Value; } + set { GetStorageInfo().Value = value; @@ -841,6 +854,7 @@ private StorageInfo CreateStorageInfo() newStorage[i] = curStorage[i]; } } + curStorage = newStorage; } @@ -959,6 +973,7 @@ public static Expression Void(Expression expression) { return expression; } + return Expression.Block(expression, Utils.Empty()); } @@ -968,6 +983,7 @@ public static DefaultExpression Default(Type type) { return Empty(); } + return Expression.Default(type); } @@ -1046,6 +1062,7 @@ public static bool IsReadWriteAssignment(this ExpressionType type) case ExpressionType.SubtractAssignChecked: return true; } + return false; } } @@ -1074,6 +1091,7 @@ internal static U[] Map(this ICollection collection, Func select) { result[count++] = select(t); } + return result; } @@ -1086,6 +1104,7 @@ internal static int ListHashCode(this IEnumerable list) { h ^= (h << 5) ^ cmp.GetHashCode(t); } + return h; } @@ -1095,6 +1114,7 @@ internal static bool ListEquals(this ICollection first, ICollection sec { return false; } + var cmp = EqualityComparer.Default; var f = first.GetEnumerator(); var s = second.GetEnumerator(); @@ -1107,6 +1127,7 @@ internal static bool ListEquals(this ICollection first, ICollection sec return false; } } + return true; } } From dcada5a4a48d7e0c901279844d2b861f0640ce71 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:08 -0800 Subject: [PATCH 64/81] Update lang --- .../engine/lang/codegen.cs | 6 +++++ .../engine/lang/parserutils.cs | 27 +++++++++++++++++++ .../engine/lang/scriptblock.cs | 10 +++++++ 3 files changed, 43 insertions(+) diff --git a/src/System.Management.Automation/engine/lang/codegen.cs b/src/System.Management.Automation/engine/lang/codegen.cs index e463091ace7..bc0ff86adee 100644 --- a/src/System.Management.Automation/engine/lang/codegen.cs +++ b/src/System.Management.Automation/engine/lang/codegen.cs @@ -23,6 +23,7 @@ public static string EscapeSingleQuotedStringContent(string value) { return string.Empty; } + StringBuilder sb = new StringBuilder(value.Length); foreach (char c in value) { @@ -33,6 +34,7 @@ public static string EscapeSingleQuotedStringContent(string value) sb.Append(c); } } + return sb.ToString(); } @@ -48,6 +50,7 @@ public static string EscapeBlockCommentContent(string value) { return string.Empty; } + return value .Replace("<#", "<`#") .Replace("#>", "#`>"); @@ -67,6 +70,7 @@ public static string EscapeFormatStringContent(string value) { return string.Empty; } + StringBuilder sb = new StringBuilder(value.Length); foreach (char c in value) { @@ -77,6 +81,7 @@ public static string EscapeFormatStringContent(string value) sb.Append(c); } } + return sb.ToString(); } @@ -94,6 +99,7 @@ public static string EscapeVariableName(string value) { return string.Empty; } + return value .Replace("`", "``") .Replace("}", "`}") diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index c3759e97b64..85aef8a2c6f 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -43,25 +43,30 @@ public static bool IsDash(char c) { return (c == enDash || c == emDash || c == horizontalBar || c == '-'); } + public static bool IsSingleQuote(char c) { return (c == quoteSingleLeft || c == quoteSingleRight || c == quoteSingleBase || c == quoteReversed || c == '\''); } + public static bool IsDoubleQuote(char c) { return (c == '"' || c == quoteDoubleLeft || c == quoteDoubleRight || c == quoteLowDoubleLeft); } + public static bool IsQuote(char c) { return (IsSingleQuote(c) || IsDoubleQuote(c)); } + public static bool IsDelimiter(char c, char delimiter) { if (delimiter == '"') return IsDoubleQuote(c); if (delimiter == '\'') return IsSingleQuote(c); return (c == delimiter); } + public static bool IsCurlyBracket(char c) { return (c == '{' || c == '}'); @@ -367,6 +372,7 @@ internal static object IntToObject(int value) { return s_integerCache[value - _MinCache]; } + return (object)value; } @@ -416,6 +422,7 @@ internal static T ConvertTo(object obj, IScriptExtent errorPosition) re.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); throw re; } + return result; } @@ -534,22 +541,27 @@ private static RegexOptions parseRegexOptions(SplitOptions options) { result |= RegexOptions.CultureInvariant; } + if ((options & SplitOptions.IgnorePatternWhitespace) != 0) { result |= RegexOptions.IgnorePatternWhitespace; } + if ((options & SplitOptions.Multiline) != 0) { result |= RegexOptions.Multiline; } + if ((options & SplitOptions.Singleline) != 0) { result |= RegexOptions.Singleline; } + if ((options & SplitOptions.IgnoreCase) != 0) { result |= RegexOptions.IgnoreCase; } + if ((options & SplitOptions.ExplicitCapture) != 0) { result |= RegexOptions.ExplicitCapture; @@ -603,6 +615,7 @@ private static object SplitOperatorImpl(ExecutionContext context, IScriptExtent throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadOperatorArgument", ParserStrings.BadOperatorArgument, "-split", rval); } + if (args.Length >= 2) limit = FixNum(args[1], errorPosition); if (args.Length >= 3 && args[2] != null) @@ -616,6 +629,7 @@ private static object SplitOperatorImpl(ExecutionContext context, IScriptExtent throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionWithPredicate", ParserStrings.InvalidSplitOptionWithPredicate); } + if (ignoreCase && (options & SplitOptions.IgnoreCase) == 0) { options |= SplitOptions.IgnoreCase; @@ -682,6 +696,7 @@ private static object SplitWithPredicate(ExecutionContext context, IScriptExtent { split.Add(string.Empty); } + break; } @@ -1204,6 +1219,7 @@ internal static object MatchOperator(ExecutionContext context, IScriptExtent err { resultList.Add(val); } + if (check++ > 1000) { // Check to see if we're stopping every one in a while... @@ -1345,6 +1361,7 @@ internal static Regex NewRegex(string patternString, RegexOptions options) } } } + private static Dictionary s_regexCache = new Dictionary(); private const int MaxRegexCache = 1000; @@ -1428,15 +1445,18 @@ internal static string GetTypeFullName(object obj) { return String.Empty; } + PSObject mshObj = obj as PSObject; if (mshObj == null) { return obj.GetType().FullName; } + if (mshObj.InternalTypeNames.Count == 0) { return typeof(PSObject).FullName; } + return mshObj.InternalTypeNames[0]; } @@ -1476,6 +1496,7 @@ internal static object CallMethod( // "you can't call a method on null" throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "InvokeMethodOnNull", ParserStrings.InvokeMethodOnNull); } + targetBase = PSObject.Base(target); targetAsPSObject = PSObject.AsPSObject(target); @@ -1537,6 +1558,7 @@ internal static object CallMethod( throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, GetTypeFullName(target), methodName); } + propertyToSet.InvokeSet(valueToSet, paramArray); return valueToSet; } @@ -1598,6 +1620,7 @@ internal int LowerBound { get { return _lowerBound; } } + private int _upperBound; internal int UpperBound { @@ -1647,6 +1670,7 @@ public bool MoveNext() _firstElement = false; return true; } + if (_current == _upperBound) return false; @@ -1781,6 +1805,7 @@ internal static RuntimeException NewInterpreterExceptionWithInnerException(objec { message = StringUtil.Format(resourceString, args); } + if (String.IsNullOrEmpty(message)) { Dbg.Assert(false, @@ -1817,6 +1842,7 @@ internal static RuntimeException NewInterpreterExceptionWithInnerException(objec + "' due to FormatException " + e.Message); rte = NewBackupInterpreterException(exceptionType, errorPosition, resourceIdAndErrorId, e); } + rte.SetTargetObject(targetObject); return rte; @@ -1940,6 +1966,7 @@ internal static void Trace(ExecutionContext context, int level, string messageId { message = StringUtil.Format(resourceString, args); } + if (String.IsNullOrEmpty(message)) { message = "Could not load text for msh script tracing message id '" + messageId + "'"; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 5ac28c17dc5..9aa81841bc7 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -94,6 +94,7 @@ internal static ScriptBlock Create(ExecutionContext context, string script) { sb.SessionStateInternal = context.EngineSessionState; } + return sb; } @@ -231,6 +232,7 @@ public PowerShell GetPowerShell(Dictionary variables, params obj suppliedVariables = new Dictionary(variables, StringComparer.OrdinalIgnoreCase); context = null; } + return GetPowerShellImpl(context, suppliedVariables, false, false, null, args); } @@ -570,6 +572,7 @@ public string File public bool IsFilter { get { return _scriptBlockData.IsFilter; } + set { throw new PSInvalidOperationException(); } } @@ -579,6 +582,7 @@ public bool IsFilter public bool IsConfiguration { get { return _scriptBlockData.GetIsConfiguration(); } + set { throw new PSInvalidOperationException(); } } @@ -631,6 +635,7 @@ internal ReadOnlyCollection OutputType result.AddRange(outputType.Type); } } + return new ReadOnlyCollection(result); } } @@ -693,6 +698,7 @@ internal SessionState SessionState return SessionStateInternal != null ? SessionStateInternal.PublicSessionState : null; } + set { if (value == null) @@ -764,6 +770,7 @@ internal Delegate CreateDelegate(Type delegateType) { call = DynamicExpression.Dynamic(PSConvertBinder.Get(invokeMethod.ReturnType), invokeMethod.ReturnType, call); } + return Expression.Lambda(delegateType, call, parameterExprs).Compile(); } @@ -1020,6 +1027,7 @@ internal void SetPSScriptRootAndPSCommandPath(MutableTuple locals, ExecutionCont psScriptRoot = Path.GetDirectoryName(File); psCommandPath = File; } + locals.SetAutomaticVariable(AutomaticVariable.PSScriptRoot, psScriptRoot, context); locals.SetAutomaticVariable(AutomaticVariable.PSCommandPath, psCommandPath, context); } @@ -1103,11 +1111,13 @@ private void Begin(bool expectInput, ICommandRuntime commandRuntime) { _pipeline.LinkPipelineSuccessOutput(crt.OutputPipe); } + if (crt.ErrorOutputPipe != null) { _pipeline.LinkPipelineErrorOutput(crt.ErrorOutputPipe); } } + _pipeline.StartStepping(_expectInput); } finally From b8d58f2c4280443ede02936284a2c4c48d25c193 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:09 -0800 Subject: [PATCH 65/81] Update Modules --- .../engine/Modules/AnalysisCache.cs | 5 + .../Modules/ExportModuleMemberCommand.cs | 8 ++ .../engine/Modules/GetModuleCommand.cs | 1 + .../engine/Modules/ImportModuleCommand.cs | 44 ++++++++ .../engine/Modules/ModuleCmdletBase.cs | 102 ++++++++++++++++++ .../engine/Modules/ModuleIntrinsics.cs | 13 +++ .../engine/Modules/ModuleSpecification.cs | 4 + .../engine/Modules/ModuleUtils.cs | 5 + .../engine/Modules/NewModuleCommand.cs | 15 +++ .../Modules/NewModuleManifestCommand.cs | 70 ++++++++++++ .../engine/Modules/PSModuleInfo.cs | 23 ++++ .../engine/Modules/RemoteDiscoveryHelper.cs | 17 +++ .../engine/Modules/RemoveModuleCommand.cs | 9 ++ .../engine/Modules/ScriptAnalysis.cs | 13 +++ .../Modules/TestModuleManifestCommand.cs | 5 + 15 files changed, 334 insertions(+) diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 35e5e6dc3dd..fe4a4e2ff0a 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -278,8 +278,10 @@ private static bool AddPsd1EntryToResult(ConcurrentDictionary= 8, "Must pass a large enough byte array"); @@ -1011,6 +1014,7 @@ public static AnalysisCacheData Deserialize(string filename) { Task.Delay(10000).ContinueWith(_ => result.Cleanup()); } + return result; } } @@ -1040,6 +1044,7 @@ internal static AnalysisCacheData Get() break; } } + retryCount -= 1; Thread.Sleep(25); // Sleep a bit to give time for another process to finish writing the cache } while (retryCount > 0); diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index b0126b0112c..a7a8b511666 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -42,8 +42,10 @@ public string[] Function } } } + get { return _functionList; } } + private string[] _functionList; private List _functionPatterns; @@ -69,8 +71,10 @@ public string[] Cmdlet } } } + get { return _cmdletList; } } + private string[] _cmdletList; private List _cmdletPatterns; @@ -96,8 +100,10 @@ public string[] Variable } } } + get { return _variableExportList; } } + private string[] _variableExportList; private List _variablePatterns; @@ -123,8 +129,10 @@ public string[] Alias } } } + get { return _aliasExportList; } } + private string[] _aliasExportList; private List _aliasPatterns; diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 5ab485b079f..3397773eb26 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -93,6 +93,7 @@ public sealed class GetModuleCommand : ModuleCmdletBase, IDisposable public SwitchParameter SkipEditionCheck { get { return (SwitchParameter)BaseSkipEditionCheck; } + set { BaseSkipEditionCheck = value; } } diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 3dffa949989..a6bd291a8e3 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -57,6 +57,7 @@ public sealed class ImportModuleCommand : ModuleCmdletBase, IDisposable public SwitchParameter Global { set { base.BaseGlobal = value; } + get { return base.BaseGlobal; } } @@ -68,6 +69,7 @@ public SwitchParameter Global public string Prefix { set { BasePrefix = value; } + get { return BasePrefix; } } @@ -119,8 +121,10 @@ public string[] Function BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _functionImportList; } } + private string[] _functionImportList = Utils.EmptyArray(); /// @@ -145,8 +149,10 @@ public string[] Cmdlet BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _cmdletImportList; } } + private string[] _cmdletImportList = Utils.EmptyArray(); /// @@ -170,8 +176,10 @@ public string[] Variable BaseVariablePatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _variableExportList; } } + private string[] _variableExportList; /// @@ -196,8 +204,10 @@ public string[] Alias BaseAliasPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _aliasExportList; } } + private string[] _aliasExportList; /// @@ -207,6 +217,7 @@ public string[] Alias public SwitchParameter Force { get { return (SwitchParameter)BaseForce; } + set { BaseForce = value; } } @@ -217,6 +228,7 @@ public SwitchParameter Force public SwitchParameter SkipEditionCheck { get { return (SwitchParameter)BaseSkipEditionCheck; } + set { BaseSkipEditionCheck = value; } } @@ -227,6 +239,7 @@ public SwitchParameter SkipEditionCheck public SwitchParameter PassThru { get { return (SwitchParameter)BasePassThru; } + set { BasePassThru = value; } } @@ -237,6 +250,7 @@ public SwitchParameter PassThru public SwitchParameter AsCustomObject { get { return (SwitchParameter)BaseAsCustomObject; } + set { BaseAsCustomObject = value; } } @@ -250,6 +264,7 @@ public SwitchParameter AsCustomObject public Version MinimumVersion { get { return BaseMinimumVersion; } + set { BaseMinimumVersion = value; } } @@ -268,6 +283,7 @@ public string MaximumVersion else return BaseMaximumVersion.ToString(); } + set { if (string.IsNullOrWhiteSpace(value)) @@ -290,6 +306,7 @@ public string MaximumVersion public Version RequiredVersion { get { return BaseRequiredVersion; } + set { BaseRequiredVersion = value; } } @@ -310,6 +327,7 @@ public Version RequiredVersion public object[] ArgumentList { get { return BaseArgumentList; } + set { BaseArgumentList = value; } } @@ -321,6 +339,7 @@ public object[] ArgumentList public SwitchParameter DisableNameChecking { get { return BaseDisableNameChecking; } + set { BaseDisableNameChecking = value; } } @@ -338,12 +357,14 @@ public SwitchParameter DisableNameChecking public string Scope { get { return _scope; } + set { _scope = value; _isScopeSpecified = true; } } + private string _scope = string.Empty; private bool _isScopeSpecified = false; @@ -500,6 +521,7 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A { WriteObject(pair.Value); } + break; } else @@ -515,6 +537,7 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A { WriteObject(pair.Value); } + break; } } @@ -614,6 +637,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul { WriteObject(module); } + found = true; foundModule = module; } @@ -739,6 +763,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul { message = StringUtil.Format(Modules.MaximumVersionNotFound, name, BaseMaximumVersion); } + if (BaseRequiredVersion != null || BaseMinimumVersion != null || BaseMaximumVersion != null) { FileNotFoundException fnf = new FileNotFoundException(message); @@ -752,6 +777,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul er = new ErrorRecord(fnf, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, name); } + WriteError(er); } @@ -829,19 +855,23 @@ private IList ImportModule_RemotelyViaPsrpSession( { powerShell.AddParameter("Version", this.MinimumVersion); } + if (this.RequiredVersion != null) { powerShell.AddParameter("RequiredVersion", this.RequiredVersion); } + if (this.MaximumVersion != null) { powerShell.AddParameter("MaximumVersion", this.MaximumVersion); } } + if (this.ArgumentList != null) { powerShell.AddParameter("ArgumentList", this.ArgumentList); } + if (this.BaseForce) { powerShell.AddParameter("Force", true); @@ -984,6 +1014,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule { File.Delete(localPsd1File); } + File.Move( sourceFileName: Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psd1"), destFileName: localPsd1File); @@ -1027,6 +1058,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule { Directory.Delete(temporaryModulePath, recursive: true); } + return null; } @@ -1056,6 +1088,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule { Directory.Delete(temporaryModulePath, recursive: true); } + throw; } } @@ -1092,6 +1125,7 @@ private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule) { return true; } + Hashtable manifestData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable( mainManifestFile, temporaryModuleManifestPath, @@ -1245,6 +1279,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil { goodEntries = new List(); } + if (goodEntries == null) { goodEntries = new List(); @@ -1255,6 +1290,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil { badEntries = new List(); } + if (badEntries == null) { badEntries = new List(); @@ -1393,6 +1429,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { return null; } + localizedData = data; } @@ -1406,6 +1443,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { moduleVersion = null; } + temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath( remoteCimModule.ModuleName, moduleVersion, @@ -1421,6 +1459,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { return alreadyImportedModule; } + try { Directory.CreateDirectory(temporaryModuleDirectory); @@ -1468,6 +1507,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { return null; } + foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules) { Type cmdletAdapter; @@ -1491,6 +1531,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( this.ThrowTerminatingError(errorRecord); } } + if (IsMixedModePsCimModule(remoteCimModule)) { // warn that some commands have not been imported @@ -1561,6 +1602,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { Directory.Delete(temporaryModuleDirectory, recursive: true); } + throw; } finally @@ -1656,6 +1698,7 @@ protected override void BeginProcessing() ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } + if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Global, StringComparison.OrdinalIgnoreCase)) { base.BaseGlobal = true; @@ -1684,6 +1727,7 @@ protected override void ProcessRecord() string message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionInvalidRange, BaseMinimumVersion, BaseMaximumVersion); throw new PSArgumentOutOfRangeException(message); } + ImportModuleOptions importModuleOptions = new ImportModuleOptions(); importModuleOptions.NoClobber = NoClobber; if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Local, StringComparison.OrdinalIgnoreCase)) diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 3506ee131f0..dad909793ba 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -220,9 +220,11 @@ internal List MatchAll _matchAll = new List(); _matchAll.Add(WildcardPattern.Get("*", WildcardOptions.IgnoreCase)); } + return _matchAll; } } + private List _matchAll; // The list of commands permitted in a module manifest @@ -328,6 +330,7 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found); } + if (found) { break; @@ -335,6 +338,7 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer #if UNIX } } + if (found) { break; @@ -350,6 +354,7 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer AnalysisCache.CacheModuleExports(module, Context); } } + return found; } @@ -431,6 +436,7 @@ private Hashtable LoadModuleManifestData( ErrorCategory.ResourceUnavailable, scriptInfo.Path); WriteError(er); } + containedErrors = true; return null; } @@ -471,6 +477,7 @@ internal Hashtable LoadModuleManifestData( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + containedErrors = true; return null; } @@ -514,6 +521,7 @@ internal Hashtable LoadModuleManifestData( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + containedErrors = true; return null; } @@ -564,6 +572,7 @@ private bool ValidateManifestHash( badKeys.Append("'"); } } + if (badKeys.Length > 0) { result = false; @@ -597,6 +606,7 @@ private bool ValidateManifestHash( validMembersString.Append("', '"); validMembersString.Append(validMembers[i]); } + validMembersString.Append("'"); message = StringUtil.Format(Modules.InvalidModuleManifestMember, moduleManifestPath, validMembersString, badKeys); InvalidOperationException ioe = new InvalidOperationException(message); @@ -606,6 +616,7 @@ private bool ValidateManifestHash( } } } + return result; } @@ -660,6 +671,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module invalidOperation.SetErrorId("Modules_InvalidModuleExtension"); throw invalidOperation; } + extension = null; } @@ -905,6 +917,7 @@ internal List GetModule(string[] names, bool all, bool refresh) moduleNames.Add(n); } } + modulesToReturn.AddRange(GetModuleForRootedPaths(modulePaths, all, refresh)); } @@ -1221,6 +1234,7 @@ private PSModuleInfo CreateModuleInfoForGetModule(string file, bool refresh) { moduleInfo.SetModuleType(ModuleType.Manifest); } + moduleInfo.RootModule = moduleInfo.RootModuleForManifest; } else @@ -1346,6 +1360,7 @@ internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProc { return false; } + ExternalScriptInfo localizedScriptInfo = FindLocalizedModuleManifest(scriptInfo.Path); localizedData = null; if (localizedScriptInfo != null) @@ -1356,6 +1371,7 @@ internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProc return false; } } + return true; } @@ -1373,6 +1389,7 @@ private IEnumerable CreateFakeModuleObject(IEnumerable(data, moduleManifestPath, "RootModule", manifestProcessingFlags, @@ -1514,6 +1534,7 @@ internal PSModuleInfo LoadModuleManifest( WriteError(er); } } + if (bailOnFirstError) return null; } @@ -1676,6 +1697,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } else if (!ModuleIntrinsics.AreModuleFieldsMatchingConstraints( @@ -1757,6 +1779,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } } @@ -1793,6 +1816,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } } @@ -1831,6 +1855,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } } @@ -1870,6 +1895,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } } @@ -1899,6 +1925,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } } @@ -1931,6 +1958,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + if (bailOnFirstError) return null; } else if (higherThanKnownHighestVersion) @@ -1974,6 +2002,7 @@ internal PSModuleInfo LoadModuleManifest( { fakeManifestInfo.SetGuid(manifestGuid.Value); } + if (moduleVersion != null) { fakeManifestInfo.SetVersion(moduleVersion); @@ -2059,6 +2088,7 @@ internal PSModuleInfo LoadModuleManifest( nestedModules.Add(s); } } + Array.Clear(tmpNestedModules, 0, tmpNestedModules.Length); } @@ -2316,6 +2346,7 @@ internal PSModuleInfo LoadModuleManifest( { continue; } + if (entry.FileName.Equals(fileName, StringComparison.OrdinalIgnoreCase)) { isAlreadyLoaded = true; @@ -2371,6 +2402,7 @@ internal PSModuleInfo LoadModuleManifest( description = (string)LanguagePrimitives.ConvertTo(localizedData["Description"], typeof(string), CultureInfo.InvariantCulture); } + if (string.IsNullOrEmpty(description)) { description = (string)LanguagePrimitives.ConvertTo(data["Description"], @@ -2522,18 +2554,22 @@ internal PSModuleInfo LoadModuleManifest( { exportedFunctions = MatchAll; } + if (exportedCmdlets == null) { exportedCmdlets = MatchAll; } + if (exportedVariables == null) { exportedVariables = MatchAll; } + if (exportedAliases == null) { exportedAliases = MatchAll; } + if (exportedDscResources == null) { exportedDscResources = MatchAll; @@ -2572,6 +2608,7 @@ internal PSModuleInfo LoadModuleManifest( manifestInfo.AddRequiredAssembly(a); } } + if (fileList != null) { foreach (var f in fileList) @@ -2580,6 +2617,7 @@ internal PSModuleInfo LoadModuleManifest( manifestInfo.AddToFileList(absoluteFilePath); } } + if (moduleList != null) { foreach (var m in moduleList) @@ -2601,20 +2639,24 @@ internal PSModuleInfo LoadModuleManifest( manifestInfo.AddScript(s); } } + manifestInfo.RootModule = savedActualRootModule; manifestInfo.RootModuleForManifest = savedActualRootModule; if (manifestGuid != null) { manifestInfo.SetGuid((Guid)manifestGuid); } + if (helpInfoUri != null) { manifestInfo.SetHelpInfoUri(helpInfoUri); } + foreach (PSModuleInfo module in requiredModulesLoaded) { manifestInfo.AddRequiredModule(module); } + if (requiredModules != null) { foreach (ModuleSpecification moduleSpecification in requiredModules) @@ -3142,18 +3184,22 @@ internal PSModuleInfo LoadModuleManifest( { newManifestInfo.Description = description; } + if (newManifestInfo.Version.Equals(new Version(0, 0))) { newManifestInfo.SetVersion(moduleVersion); } + if (newManifestInfo.Guid.Equals(Guid.Empty) && (manifestGuid != null)) { newManifestInfo.SetGuid((Guid)manifestGuid); } + if (newManifestInfo.HelpInfoUri == null && (helpInfoUri != null)) { newManifestInfo.SetHelpInfoUri(helpInfoUri); } + if (requiredModules != null) { foreach (ModuleSpecification moduleSpecification in requiredModules) @@ -3161,6 +3207,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.AddRequiredModuleSpecification(moduleSpecification); } } + if (newManifestInfo.RootModule == null) { newManifestInfo.RootModule = manifestInfo.RootModule; @@ -3177,6 +3224,7 @@ internal PSModuleInfo LoadModuleManifest( { newManifestInfo.AddToTags(tag); } + newManifestInfo.ReleaseNotes = manifestInfo.ReleaseNotes; newManifestInfo.ProjectUri = manifestInfo.ProjectUri; newManifestInfo.LicenseUri = manifestInfo.LicenseUri; @@ -3353,6 +3401,7 @@ internal PSModuleInfo LoadModuleManifest( { newManifestInfo.SetExportedTypeFiles(manifestInfo.ExportedTypeFiles); } + if (manifestInfo.ExportedFormatFiles.Count > 0) { newManifestInfo.SetExportedFormatFiles(manifestInfo.ExportedFormatFiles); @@ -3599,6 +3648,7 @@ private static void SetDeclaredDscResources(List exportedDscRes return true; } } + return false; }); foreach (var exportedResource in exportedClassDscResources) @@ -3618,6 +3668,7 @@ private static void UpdateCommandCollection(List list, List list, List { requiredModuleSpecification }); } + if (requiredModuleSpecification != null) { requiredModules.Add(requiredModuleSpecification, new List(requiredModuleInfo.RequiredModulesSpecification)); @@ -3825,6 +3879,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, { mm = new MissingMemberException(error.Exception.Message); } + error = new ErrorRecord(mm, "Modules_InvalidManifest", ErrorCategory.ResourceUnavailable, moduleManifestPath); } @@ -3865,6 +3920,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, requiredModuleSpecification.Version, requiredModuleSpecification.MaximumVersion); } + break; case ModuleMatchFailure.MaximumVersion: @@ -3886,6 +3942,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, requiredModuleSpecification.Version, requiredModuleSpecification.MaximumVersion); } + break; case ModuleMatchFailure.Guid: @@ -3979,14 +4036,17 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul { ms.Guid = requiredModule.Guid.Value; } + if (requiredModule.RequiredVersion != null) { ms.RequiredVersion = requiredModule.RequiredVersion; } + if (requiredModule.Version != null) { ms.Version = requiredModule.Version; } + if (requiredModule.MaximumVersion != null) { ms.MaximumVersion = requiredModule.MaximumVersion; @@ -4016,6 +4076,7 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul } } } + return result; } @@ -4052,6 +4113,7 @@ internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSp { tempModuleName = rootedModulePath + StringLiterals.PowerShellDataFileExtension; } + ModuleSpecification tempSpec = new ModuleSpecification( string.IsNullOrEmpty(rootedModulePath) ? nestedModuleSpec.Name : tempModuleName); if (nestedModuleSpec.Guid.HasValue) @@ -4140,6 +4202,7 @@ internal static Collection GetModuleIfAvailable(ModuleSpecificatio result.Add(module); } } + return result; } @@ -4176,6 +4239,7 @@ private static bool HasRequiredModulesCyclicReference(ModuleSpecification curren break; } } + Dbg.Assert(mo != null, "The moduleInfo should be present"); string message = StringUtil.Format(Modules.RequiredModulesCyclicDependency, currentModuleSpecification.ToString(), requiredModuleSpecification.ToString(), mo.Path); MissingMemberException mm = new MissingMemberException(message); @@ -4283,6 +4347,7 @@ internal bool GetListOfStringsFromData( } } } + return true; } @@ -4402,6 +4467,7 @@ private bool GetListOfFilesFromData( string message = StringUtil.Format(SessionStateStrings.PathNotFound, fixedFileName); throw new FileNotFoundException(message, fixedFileName); } + list.Add(fixedFileName); } catch (Exception e) @@ -4410,6 +4476,7 @@ private bool GetListOfFilesFromData( { this.ThrowTerminatingError(GenerateInvalidModuleMemberErrorRecord(key, moduleManifestPath, e)); } + list = null; WriteInvalidManifestMemberError(this, key, moduleManifestPath, e, manifestProcessingFlags); return false; @@ -4537,6 +4604,7 @@ internal bool GetScalarFromData( ErrorCategory.ResourceUnavailable, moduleManifestPath); WriteError(er); } + return false; } } @@ -4829,6 +4897,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC { module.Path = module.Name; } + bool shouldModuleBeRemoved = ShouldModuleBeRemoved(module, moduleNameInRemoveModuleCmdlet, out isTopLevelModule); if (shouldModuleBeRemoved) @@ -4877,6 +4946,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC { continue; } + if (matches[i].Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { string name = matches[i].Name; @@ -4890,6 +4960,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC keysToRemoveFromCmdletCache.Add(cmdlet.Key); } } + foreach (string keyToRemove in keysToRemoveFromCmdletCache) { Context.EngineSessionState.RemoveCmdletEntry(keyToRemove, true); @@ -4968,6 +5039,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC { continue; } + if (func.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { try @@ -5010,6 +5082,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC { continue; } + if (ai.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { // Remove the alias with force... @@ -5040,6 +5113,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC } } } + if (isTopLevelModule) { // Remove it from the top level session state @@ -5088,6 +5162,7 @@ private bool ShouldModuleBeRemoved(PSModuleInfo module, string moduleNameInRemov { return true; } + return false; } @@ -5294,6 +5369,7 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, { WriteObject(module); } + found = true; return module; } @@ -5305,6 +5381,7 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, { RemoveModule(module); } + module = LoadModule(parentModule, fileName, moduleBase, prefix, ss, null, ref options, manifestProcessingFlags, out found, out moduleFileFound); if (found) { @@ -5340,6 +5417,7 @@ internal string GetDefaultPrefix(PSModuleInfo module) prefix = (string)LanguagePrimitives.ConvertTo(localizedData["DefaultCommandPrefix"], typeof(string), CultureInfo.InvariantCulture); } + if (string.IsNullOrEmpty(prefix)) { prefix = (string)LanguagePrimitives.ConvertTo(data["DefaultCommandPrefix"], @@ -5348,6 +5426,7 @@ internal string GetDefaultPrefix(PSModuleInfo module) } } } + return prefix; } @@ -5461,6 +5540,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { ext = Path.GetExtension(fileName); } + PSModuleInfo module = null; // Block ps1 files from being imported in constrained language. @@ -5708,6 +5788,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { e.ErrorRecord.PreserveInvocationInfoOnce = true; } + if (e.WasThrownFromThrowStatement) { ThrowTerminatingError(e.ErrorRecord); @@ -6125,6 +6206,7 @@ private static void AnalyzeSnapinDomainHelper() Exception ignored = null; assembly = ExecutionContext.LoadAssembly(path, null, out ignored); } + if (assembly != null) { assemblyVersion = GetAssemblyVersionNumber(assembly); @@ -6209,14 +6291,17 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon { module.AddDetectedAliasExport(commandName, null); } + if ((commandType & CommandTypes.Function) == CommandTypes.Function) { module.AddDetectedFunctionExport(commandName); } + if ((commandType & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { module.AddDetectedCmdletExport(commandName); } + if ((commandType & CommandTypes.Configuration) == CommandTypes.Configuration) { module.AddDetectedFunctionExport(commandName); @@ -6549,6 +6634,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { iss.Formats.Reset(); } + foreach (var a in ClrFacade.GetAssemblies()) { if (a.GetName().FullName.Equals(snapin.AssemblyName, StringComparison.Ordinal)) @@ -6634,6 +6720,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { typesFileNames.Add(sste.FileName); } + if (typesFileNames.Count > 0) { module.SetExportedTypeFiles(new ReadOnlyCollection(typesFileNames)); @@ -6646,6 +6733,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { formatsFileNames.Add(ssfe.FileName); } + if (formatsFileNames.Count > 0) { module.SetExportedFormatFiles(new ReadOnlyCollection(formatsFileNames)); @@ -6682,6 +6770,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { aliasEntry = commandEntry as SessionStateAliasEntry; } + Dbg.Assert((cmdletEntry != null || aliasEntry != null), "When importing a binary module, the commands entry should only have cmdlets/aliases in it"); if (ss != null) { @@ -6768,6 +6857,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { Context.EngineSessionState = ss.Internal; } + if (disableFormatUpdates) iss.DisableFormatUpdates = true; @@ -6784,6 +6874,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { allTypes = assemblyToLoad.ExportedTypes; } + foreach (Type type in allTypes) { // If it derives from JobSourceAdapter and it's not already registered, register it... @@ -6845,6 +6936,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module); } + return module; } @@ -6862,6 +6954,7 @@ private static Version GetAssemblyVersionNumber(Assembly assemblyToLoad) { assemblyVersion = new Version(0, 0); } + return assemblyVersion; } @@ -6882,6 +6975,7 @@ internal static string AddPrefixToCommandName(string commandName, string prefix) { commandName = prefix + commandName; } + return commandName; } @@ -6951,14 +7045,17 @@ internal static void AddModuleToModuleTables(ExecutionContext context, SessionSt { moduleTableKey = module.Name; } + if (!context.Modules.ModuleTable.ContainsKey(moduleTableKey)) { context.Modules.ModuleTable.Add(moduleTableKey, module); } + if (context.previousModuleImported.ContainsKey(module.Name)) { context.previousModuleImported.Remove(module.Name); } + context.previousModuleImported.Add(module.Name, module.Path); if (!targetSessionState.ModuleTable.ContainsKey(moduleTableKey)) @@ -7056,6 +7153,7 @@ internal static void ImportModuleMembers( if (m.Path.Equals(sourceModule.Path, StringComparison.OrdinalIgnoreCase)) present = true; } + if (!present) { targetSessionState.Module.AddNestedModule(sourceModule); @@ -7090,6 +7188,7 @@ internal static void ImportModuleMembers( cmdlet.WriteVerbose(message); continue; } + CmdletInfo prefixedCmdlet = new CmdletInfo( AddPrefixToCommandName(cmdletToImport.Name, prefix), cmdletToImport.ImplementingType, @@ -7319,6 +7418,7 @@ internal static bool CommandFound(string commandName, SessionStateInternal sessi { return false; } + return true; } finally @@ -7394,6 +7494,7 @@ private static void ValidateCommandName(ModuleCmdletBase cmdlet, message = StringUtil.Format(Modules.ImportingNonStandardVerb, moduleName); cmdlet.WriteWarning(message); } + string[] alternates = Verbs.SuggestedAlternates(verb); if (alternates == null) { @@ -7417,6 +7518,7 @@ private static void ValidateCommandName(ModuleCmdletBase cmdlet, cmdlet.WriteWarning(message); checkNoun = false; } + message = StringUtil.Format(Modules.ImportingNonStandardNounVerbose, commandName, moduleName); cmdlet.WriteVerbose(message); return; diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 72a15563bd2..39cd3b69caa 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -43,6 +43,7 @@ internal ModuleIntrinsics(ExecutionContext context) // And initialize the module path... SetModulePath(); } + private readonly ExecutionContext _context; // Holds the module collection... @@ -71,6 +72,7 @@ internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path) cmdlet.ThrowTerminatingError(er); } } + internal void DecrementModuleNestingCount() { --ModuleNestingDepth; @@ -190,6 +192,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object sb = ScriptBlock.Create(_context, sbText); } } + if (sb == null) throw PSTraceSource.NewInvalidOperationException(); @@ -232,6 +235,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object exitCode = (int)ee.Argument; setExitCode = true; } + result = resultList; } finally @@ -273,6 +277,7 @@ internal List GetModules(string[] patterns, bool all) internal List GetExactMatchModules(string moduleName, bool all, bool exactMatch) { if (moduleName == null) { moduleName = String.Empty; } + return GetModuleCore(new string[] { moduleName }, all, exactMatch); } @@ -330,6 +335,7 @@ private List GetModuleCore(string[] patterns, bool all, bool exact found[path] = true; } } + if (_context.EngineSessionState != _context.TopLevelSessionState) { foreach (var pair in _context.TopLevelSessionState.ModuleTable) @@ -866,6 +872,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath ExperimentalFeature.IsEnabled(featureName))); } } + return expFeatureList.ToArray(); } } @@ -927,6 +934,7 @@ internal static string GetModuleName(string path) { ext = Path.GetExtension(fileName); } + if (!string.IsNullOrEmpty(ext) && IsPowerShellModuleExtension(ext)) { return fileName.Substring(0, fileName.Length - ext.Length); @@ -1059,6 +1067,7 @@ internal static string GetExpandedEnvironmentVariable(string name, EnvironmentVa { result = Environment.ExpandEnvironmentVariables(result); } + return result; } @@ -1083,6 +1092,7 @@ private static int PathContainsSubstring(string pathToScan, string pathToLookFor // We have to use equality comparison on individual substrings (as opposed to simple 'string.IndexOf' or 'string.Contains') // because of cases like { pathToScan="C:\Temp\MyDir\MyModuleDir", pathToLookFor="C:\Temp" } + if (string.Equals(goodSubstring, goodPathToLookFor, StringComparison.OrdinalIgnoreCase)) { return pos; // match found - return index of it in the 'pathToScan' string @@ -1218,6 +1228,7 @@ private static string RemoveSxSPsHomeModulePath(string currentProcessModulePath, { modulePathString.Append(Path.PathSeparator); } + modulePathString.Append(trimedPath); } @@ -1559,6 +1570,7 @@ internal static void ExportModuleMembers( cmdlet.WriteVerbose(message); } } + SortAndRemoveDuplicates(sessionState.ExportedFunctions, delegate (FunctionInfo ci) { return ci.Name; }); } @@ -1636,6 +1648,7 @@ internal static void ExportModuleMembers( sessionState.ExportedVariables.Add(entry.Value); } } + SortAndRemoveDuplicates(sessionState.ExportedVariables, delegate (PSVariable v) { return v.Name; }); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 36e86916b23..7b1aafaa56c 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -47,6 +47,7 @@ public ModuleSpecification(string moduleName) { throw new ArgumentNullException(nameof(moduleName)); } + this.Name = moduleName; // Alias name of miniumVersion this.Version = null; @@ -120,6 +121,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu { badKeys.Append(", "); } + badKeys.Append("'"); badKeys.Append(entry.Key.ToString()); badKeys.Append("'"); @@ -163,6 +165,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "MaximumVersion", "RequiredVersion"); return new ArgumentException(message); } + return null; } @@ -210,6 +213,7 @@ public override string ToString() { moduleSpecBuilder.Append("; ModuleVersion = '").Append(Version).Append("'"); } + if (MaximumVersion != null) { moduleSpecBuilder.Append("; MaximumVersion = '").Append(MaximumVersion).Append("'"); diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index d8f8e89a125..d2db08ae641 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -349,6 +349,7 @@ private static void ProcessPossibleVersionSubdirectories(string[] subdirectories versionFolders.Add(version); } } + if (versionFolders.Count > 1) { versionFolders.Sort((x, y) => y.CompareTo(x)); @@ -364,6 +365,7 @@ internal static bool IsModuleInVersionSubdirectory(string modulePath, out Versio folderName = Path.GetFileName(folderName); return Version.TryParse(folderName, out version); } + return false; } @@ -524,6 +526,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe Module = tempModuleInfo }; } + if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context) @@ -531,6 +534,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe Module = tempModuleInfo }; } + if ((commandTypes & CommandTypes.Function) == CommandTypes.Function) { yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context) @@ -538,6 +542,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe Module = tempModuleInfo }; } + if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration) { yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context) diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index 6f16ed5404f..c2f42976e1b 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -28,8 +28,10 @@ public sealed class NewModuleCommand : ModuleCmdletBase public string Name { set { _name = value; } + get { return _name; } } + private string _name; /// @@ -41,11 +43,13 @@ public string Name public ScriptBlock ScriptBlock { get { return _scriptBlock; } + set { _scriptBlock = value; } } + private ScriptBlock _scriptBlock; /// @@ -70,8 +74,10 @@ public string[] Function BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _functionImportList; } } + private string[] _functionImportList = Utils.EmptyArray(); /// @@ -96,8 +102,10 @@ public string[] Cmdlet BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } + get { return _cmdletImportList; } } + private string[] _cmdletImportList = Utils.EmptyArray(); /// @@ -107,8 +115,10 @@ public string[] Cmdlet public SwitchParameter ReturnResult { get { return (SwitchParameter)_returnResult; } + set { _returnResult = value; } } + private bool _returnResult; /// @@ -118,8 +128,10 @@ public SwitchParameter ReturnResult public SwitchParameter AsCustomObject { get { return (SwitchParameter)_asCustomObject; } + set { _asCustomObject = value; } } + private bool _asCustomObject; /// @@ -131,8 +143,10 @@ public SwitchParameter AsCustomObject public object[] ArgumentList { get { return _arguments; } + set { _arguments = value; } } + private object[] _arguments; /// @@ -203,6 +217,7 @@ protected override void EndProcessing() { Context.Modules.DecrementModuleNestingCount(); } + return; } } diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 4603199ed36..12e1b2ddfb6 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -35,8 +35,10 @@ public sealed class NewModuleManifestCommand : PSCmdlet public string Path { get { return _path; } + set { _path = value; } } + private string _path; /// @@ -48,8 +50,10 @@ public string Path public object[] NestedModules { get { return _nestedModules; } + set { _nestedModules = value; } } + private object[] _nestedModules; /// @@ -59,8 +63,10 @@ public object[] NestedModules public Guid Guid { get { return _guid; } + set { _guid = value; } } + private Guid _guid = Guid.NewGuid(); /// @@ -71,8 +77,10 @@ public Guid Guid public string Author { get { return _author; } + set { _author = value; } } + private string _author; /// @@ -83,8 +91,10 @@ public string Author public string CompanyName { get { return _companyName; } + set { _companyName = value; } } + private string _companyName = string.Empty; /// @@ -95,8 +105,10 @@ public string CompanyName public string Copyright { get { return _copyright; } + set { _copyright = value; } } + private string _copyright; /// @@ -108,8 +120,10 @@ public string Copyright public string RootModule { get { return _rootModule; } + set { _rootModule = value; } } + private string _rootModule = null; /// @@ -120,8 +134,10 @@ public string RootModule public Version ModuleVersion { get { return _moduleVersion; } + set { _moduleVersion = value; } } + private Version _moduleVersion = new Version(0, 0, 1); /// @@ -132,8 +148,10 @@ public Version ModuleVersion public string Description { get { return _description; } + set { _description = value; } } + private string _description; /// @@ -143,8 +161,10 @@ public string Description public ProcessorArchitecture ProcessorArchitecture { get { return _processorArchitecture.HasValue ? _processorArchitecture.Value : ProcessorArchitecture.None; } + set { _processorArchitecture = value; } } + private ProcessorArchitecture? _processorArchitecture = null; /// @@ -154,8 +174,10 @@ public ProcessorArchitecture ProcessorArchitecture public Version PowerShellVersion { get { return _powerShellVersion; } + set { _powerShellVersion = value; } } + private Version _powerShellVersion = null; /// @@ -165,8 +187,10 @@ public Version PowerShellVersion public Version ClrVersion { get { return _ClrVersion; } + set { _ClrVersion = value; } } + private Version _ClrVersion = null; /// @@ -176,8 +200,10 @@ public Version ClrVersion public Version DotNetFrameworkVersion { get { return _DotNetFrameworkVersion; } + set { _DotNetFrameworkVersion = value; } } + private Version _DotNetFrameworkVersion = null; /// @@ -187,8 +213,10 @@ public Version DotNetFrameworkVersion public string PowerShellHostName { get { return _PowerShellHostName; } + set { _PowerShellHostName = value; } } + private string _PowerShellHostName = null; /// @@ -198,8 +226,10 @@ public string PowerShellHostName public Version PowerShellHostVersion { get { return _PowerShellHostVersion; } + set { _PowerShellHostVersion = value; } } + private Version _PowerShellHostVersion = null; /// @@ -212,8 +242,10 @@ public Version PowerShellHostVersion public object[] RequiredModules { get { return _requiredModules; } + set { _requiredModules = value; } } + private object[] _requiredModules; /// @@ -226,8 +258,10 @@ public object[] RequiredModules public string[] TypesToProcess { get { return _types; } + set { _types = value; } } + private string[] _types; /// @@ -240,8 +274,10 @@ public string[] TypesToProcess public string[] FormatsToProcess { get { return _formats; } + set { _formats = value; } } + private string[] _formats; /// @@ -254,8 +290,10 @@ public string[] FormatsToProcess public string[] ScriptsToProcess { get { return _scripts; } + set { _scripts = value; } } + private string[] _scripts; /// @@ -268,8 +306,10 @@ public string[] ScriptsToProcess public string[] RequiredAssemblies { get { return _requiredAssemblies; } + set { _requiredAssemblies = value; } } + private string[] _requiredAssemblies; /// @@ -282,8 +322,10 @@ public string[] RequiredAssemblies public string[] FileList { get { return _miscFiles; } + set { _miscFiles = value; } } + private string[] _miscFiles; /// @@ -298,8 +340,10 @@ public string[] FileList public object[] ModuleList { get { return _moduleList; } + set { _moduleList = value; } } + private object[] _moduleList; /// @@ -312,8 +356,10 @@ public object[] ModuleList public string[] FunctionsToExport { get { return _exportedFunctions; } + set { _exportedFunctions = value; } } + private string[] _exportedFunctions; /// @@ -326,8 +372,10 @@ public string[] FunctionsToExport public string[] AliasesToExport { get { return _exportedAliases; } + set { _exportedAliases = value; } } + private string[] _exportedAliases; /// @@ -340,8 +388,10 @@ public string[] AliasesToExport public string[] VariablesToExport { get { return _exportedVariables; } + set { _exportedVariables = value; } } + private string[] _exportedVariables = new string[] { "*" }; /// @@ -354,8 +404,10 @@ public string[] VariablesToExport public string[] CmdletsToExport { get { return _exportedCmdlets; } + set { _exportedCmdlets = value; } } + private string[] _exportedCmdlets; /// @@ -368,8 +420,10 @@ public string[] CmdletsToExport public string[] DscResourcesToExport { get { return _dscResourcesToExport; } + set { _dscResourcesToExport = value; } } + private string[] _dscResourcesToExport; /// @@ -383,8 +437,10 @@ public string[] DscResourcesToExport public string[] CompatiblePSEditions { get { return _compatiblePSEditions; } + set { _compatiblePSEditions = value; } } + private string[] _compatiblePSEditions; /// @@ -395,8 +451,10 @@ public string[] CompatiblePSEditions public object PrivateData { get { return _privateData; } + set { _privateData = value; } } + private object _privateData; /// @@ -445,8 +503,10 @@ public object PrivateData public string HelpInfoUri { get { return _helpInfoUri; } + set { _helpInfoUri = value; } } + private string _helpInfoUri; /// @@ -456,8 +516,10 @@ public string HelpInfoUri public SwitchParameter PassThru { get { return (SwitchParameter)_passThru; } + set { _passThru = value; } } + private bool _passThru; /// @@ -468,8 +530,10 @@ public SwitchParameter PassThru public string DefaultCommandPrefix { get { return _defaultCommandPrefix; } + set { _defaultCommandPrefix = value; } } + private string _defaultCommandPrefix; private string _indent = string.Empty; @@ -547,9 +611,11 @@ private string QuoteNames(IEnumerable names, StreamWriter streamWriter) result.Append(" "); offset = 15 + quotedString.Length; } + result.Append(quotedString); } } + if (result.Length == 0) return "@()"; @@ -617,6 +683,7 @@ private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) result.Append(streamWriter.NewLine); result.Append(" "); } + firstModule = false; if ((moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.MaximumVersion == null) && (moduleSpecification.RequiredVersion == null)) @@ -805,6 +872,7 @@ private List TryResolveFilePath(string filePath) { adjustedPath = adjustedPath.Substring(2); } + result.Add(adjustedPath); } } @@ -845,6 +913,7 @@ private string ManifestComment(string insert, StreamWriter streamWriter) { insert = " " + insert; } + return String.Format(CultureInfo.InvariantCulture, "#{0}{1}", insert, streamWriter.NewLine); } @@ -1043,6 +1112,7 @@ protected override void EndProcessing() { WriteObject(strResult); } + streamWriter.Write(strResult); } finally diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 4ed924cf42a..e6123531c41 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -249,6 +249,7 @@ public string Definition { get { return _definitionExtent == null ? String.Empty : _definitionExtent.Text; } } + internal IScriptExtent _definitionExtent; /// @@ -257,8 +258,10 @@ public string Definition public string Description { get { return _description; } + set { _description = value ?? String.Empty; } } + private string _description = String.Empty; /// @@ -296,10 +299,12 @@ public string ModuleBase (_moduleBase = !string.IsNullOrEmpty(Path) ? IO.Path.GetDirectoryName(Path) : string.Empty); } } + internal void SetModuleBase(string moduleBase) { _moduleBase = moduleBase; } + private string _moduleBase; /// @@ -320,6 +325,7 @@ public object PrivateData SetPSDataPropertiesFromPrivateData(); } } + private object _privateData = null; private void SetPSDataPropertiesFromPrivateData() @@ -462,15 +468,18 @@ public string Author public ModuleAccessMode AccessMode { get { return _accessMode; } + set { if (_accessMode == ModuleAccessMode.Constant) { throw PSTraceSource.NewInvalidOperationException(); } + _accessMode = value; } } + private ModuleAccessMode _accessMode = ModuleAccessMode.ReadWrite; /// @@ -564,6 +573,7 @@ public Dictionary ExportedFunctions } } } + return exports; } } @@ -808,8 +818,10 @@ internal List CompiledExports { _compiledExports.Add(ci); } + SessionState.Internal.ExportedCmdlets.Clear(); } + return _compiledExports; } } @@ -910,6 +922,7 @@ public ReadOnlyCollection NestedModules (_readonlyNestedModules = new ReadOnlyCollection(_nestedModules)); } } + private ReadOnlyCollection _readonlyNestedModules; /// @@ -920,6 +933,7 @@ internal void AddNestedModule(PSModuleInfo nestedModule) { AddModuleToList(nestedModule, _nestedModules); } + private readonly List _nestedModules = new List(); /// @@ -980,6 +994,7 @@ public IEnumerable RequiredAssemblies { get { return _requiredAssemblies; } } + private Collection _requiredAssemblies = new Collection(); internal void AddRequiredAssembly(string assembly) @@ -999,6 +1014,7 @@ public ReadOnlyCollection RequiredModules (_readonlyRequiredModules = new ReadOnlyCollection(_requiredModules)); } } + private ReadOnlyCollection _readonlyRequiredModules; /// @@ -1009,6 +1025,7 @@ internal void AddRequiredModule(PSModuleInfo requiredModule) { AddModuleToList(requiredModule, _requiredModules); } + private List _requiredModules = new List(); /// @@ -1023,6 +1040,7 @@ internal ReadOnlyCollection RequiredModulesSpecification (_readonlyRequiredModulesSpecification = new ReadOnlyCollection(_requiredModulesSpecification)); } } + private ReadOnlyCollection _readonlyRequiredModulesSpecification; /// @@ -1033,6 +1051,7 @@ internal void AddRequiredModuleSpecification(ModuleSpecification requiredModuleS { _requiredModulesSpecification.Add(requiredModuleSpecification); } + private List _requiredModulesSpecification = new List(); /// @@ -1066,6 +1085,7 @@ private static void AddModuleToList(PSModuleInfo module, List modu if (m.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) return; } + moduleList.Add(module); } @@ -1278,6 +1298,7 @@ public object Invoke(ScriptBlock sb, params object[] args) // and restore the scriptblocks session state... sb.SessionStateInternal = oldSessionState; } + return result; } @@ -1310,6 +1331,7 @@ public PSVariable GetVariableFromCallersModule(string variableName) break; } } + if (callersSessionState != null) { return callersSessionState.Internal.GetVariable(variableName); @@ -1448,6 +1470,7 @@ public PSModuleInfo Clone() { clone.AddRequiredModule(r); } + foreach (var r in _requiredModulesSpecification) { clone.AddRequiredModuleSpecification(r); diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index cac6faa18cb..99f665fdf07 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -97,6 +97,7 @@ internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleIn moduleInfo.AddToTags(tag); } } + moduleInfo.ReleaseNotes = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "ReleaseNotes", rehydrationFlags); moduleInfo.ProjectUri = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "ProjectUri", rehydrationFlags); moduleInfo.LicenseUri = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "LicenseUri", rehydrationFlags); @@ -299,6 +300,7 @@ private static void CopyParameterFromCmdletToPowerShell(Cmdlet cmdlet, PowerShel { continue; } + command.Parameters.Add(commandParameter); } } @@ -403,6 +405,7 @@ private static IEnumerable EnumerateWithCatch(IEnumerable enumerable, A { exceptionHandler(e); } + if (enumerator != null) using (enumerator) { @@ -532,6 +535,7 @@ private static T GetPropertyValue(CimInstance cimInstance, string propertyNam { Array.Reverse(lengthBytes); } + return (T)(object)(lengthBytes.Concat(contentBytes).ToArray()); } } @@ -563,23 +567,28 @@ public CimFileCode FileCode { return CimFileCode.PsdV1; } + if (this.FileName.EndsWith(".cdxml", StringComparison.OrdinalIgnoreCase)) { return CimFileCode.CmdletizationV1; } + if (this.FileName.EndsWith(".types.ps1xml", StringComparison.OrdinalIgnoreCase)) { return CimFileCode.TypesV1; } + if (this.FileName.EndsWith(".format.ps1xml", StringComparison.OrdinalIgnoreCase)) { return CimFileCode.FormatV1; } + return CimFileCode.Unknown; } } public abstract string FileName { get; } + internal abstract byte[] RawFileDataCore { get; } public byte[] RawFileData @@ -599,9 +608,11 @@ public string FileData _fileData = sr.ReadToEnd(); } } + return _fileData; } } + private string _fileData; } @@ -809,6 +820,7 @@ private static IEnumerable GetCimModules( cmdlet.ThrowTerminatingError(errorRecord); } } + cmdlet.WriteError(errorRecord); }); } @@ -894,6 +906,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti return GetCimCredentials(PasswordAuthenticationMechanism.Default, credential); } } + if (authentication.Equals("Basic", StringComparison.OrdinalIgnoreCase)) { if (credential == null) @@ -905,6 +918,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti return GetCimCredentials(PasswordAuthenticationMechanism.Basic, credential); } } + if (authentication.Equals("Negotiate", StringComparison.OrdinalIgnoreCase)) { if (credential == null) @@ -916,6 +930,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti return GetCimCredentials(PasswordAuthenticationMechanism.Negotiate, credential); } } + if (authentication.Equals("CredSSP", StringComparison.OrdinalIgnoreCase)) { if (credential == null) @@ -927,6 +942,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti return GetCimCredentials(PasswordAuthenticationMechanism.CredSsp, credential); } } + if (authentication.Equals("Digest", StringComparison.OrdinalIgnoreCase)) { if (credential == null) @@ -938,6 +954,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti return GetCimCredentials(PasswordAuthenticationMechanism.Digest, credential); } } + if (authentication.Equals("Kerberos", StringComparison.OrdinalIgnoreCase)) { if (credential == null) diff --git a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs index 984badafa94..b086fcc7c6a 100644 --- a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs @@ -32,8 +32,10 @@ public sealed class RemoveModuleCommand : ModuleCmdletBase public string[] Name { set { _name = value; } + get { return _name; } } + private string[] _name = Utils.EmptyArray(); /// @@ -51,8 +53,10 @@ public string[] Name public PSModuleInfo[] ModuleInfo { set { _moduleInfo = value; } + get { return _moduleInfo; } } + private PSModuleInfo[] _moduleInfo = Utils.EmptyArray(); /// @@ -62,6 +66,7 @@ public PSModuleInfo[] ModuleInfo public SwitchParameter Force { get { return BaseForce; } + set { BaseForce = value; } } @@ -175,6 +180,7 @@ protected override void ProcessRecord() ErrorCategory.PermissionDenied, module); WriteError(er); } + continue; } @@ -194,6 +200,7 @@ protected override void ProcessRecord() string message = StringUtil.Format(Modules.CoreModuleCannotBeRemoved, module.Name); this.WriteWarning(message); } + continue; } // Specify the overall module name if there is only one. @@ -211,6 +218,7 @@ protected override void ProcessRecord() // Add module to remove list. moduleList.Add(module); } + actualModulesToRemove[entry.Key] = moduleList; } @@ -348,6 +356,7 @@ protected override void EndProcessing() { isEngineModule = false; } + if (!WildcardPattern.ContainsWildcardCharacters(n)) hasWildcards = false; } diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index b9275748f3d..73c8a78985e 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -179,12 +179,14 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun // recorded for command/parameter completion. // function Foo-Bar { ... } + var functionName = functionDefinitionAst.Name; DiscoveredFunctions[functionName] = functionDefinitionAst; ModuleIntrinsics.Tracer.WriteLine("Discovered function definition: {0}", functionName); // Check if they've defined any aliases // function Foo-Bar { [Alias("Alias1", "...")] param() ... } + var functionBody = functionDefinitionAst.Body; if ((functionBody.ParamBlock != null) && (functionBody.ParamBlock.Attributes != null)) { @@ -213,6 +215,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun { DiscoveredExports.Add(functionName); } + return AstVisitAction.Continue; } @@ -231,19 +234,28 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a ModuleIntrinsics.Tracer.WriteLine("Module adds itself to the path."); AddsSelfToPath = true; } + return AstVisitAction.SkipChildren; } // We skip a bunch of random statements because we can't really be accurate detecting functions/classes etc. that // are conditionally defined. public override AstVisitAction VisitIfStatement(IfStatementAst ifStmtAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitForStatement(ForStatementAst forStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitWhileStatement(WhileStatementAst whileStatementAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) { return AstVisitAction.SkipChildren; } + public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AstVisitAction.SkipChildren; } // Visit one the other variations: @@ -480,6 +492,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command result[parameterInfo.name] = GetSafeValueVisitor.GetSafeValue(argumentAst, null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis); } + break; } } diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 2867911924e..b139947b44d 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -43,8 +43,10 @@ public TestModuleManifestCommand() public string Path { get { return _path; } + set { _path = value; } } + private string _path; /// @@ -258,6 +260,7 @@ protected override void ProcessRecord() { Context.ModuleBeingProcessed = _origModuleBeingProcessed; } + DirectoryInfo parent = null; try { @@ -324,6 +327,7 @@ private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathSc ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, path); ThrowTerminatingError(er); } + path = pathInfos[0].Path; // First, we validate if the path does exist. @@ -367,6 +371,7 @@ private bool IsValidGacAssembly(string assemblyName) assemblyFile = assemblyName + StringLiterals.PowerShellILAssemblyExtension; ngenAssemblyFile = assemblyName + StringLiterals.PowerShellNgenAssemblyExtension; } + try { var allFiles = Directory.GetFiles(gacPath, assemblyFile, SearchOption.AllDirectories); From 54b18773134ff6e68ebc50cb95ced0d47c3505f1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:10 -0800 Subject: [PATCH 66/81] Update parser --- .../engine/parser/AstVisitor.cs | 124 ++++++++++++++ .../engine/parser/CharTraits.cs | 7 + .../engine/parser/Compiler.cs | 74 +++++++++ .../engine/parser/ConstantValues.cs | 76 +++++++++ .../engine/parser/DebugViewWriter.cs | 38 +++++ .../engine/parser/GlobalAssemblyCache.cs | 3 + .../engine/parser/PSType.cs | 25 +++ .../engine/parser/Parser.cs | 153 ++++++++++++++++++ .../engine/parser/Position.cs | 30 ++++ .../engine/parser/PreOrderVisitor.cs | 1 + .../engine/parser/SafeValues.cs | 88 ++++++++++ .../engine/parser/SemanticChecks.cs | 30 ++++ .../engine/parser/SymbolResolver.cs | 9 ++ .../engine/parser/TypeInferenceVisitor.cs | 2 + .../engine/parser/TypeResolver.cs | 15 ++ .../engine/parser/VariableAnalysis.cs | 26 +++ .../engine/parser/ast.cs | 124 ++++++++++++++ .../engine/parser/token.cs | 2 + .../engine/parser/tokenizer.cs | 143 ++++++++++++++++ 19 files changed, 970 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 3eed5bf2f21..9f0750a53ab 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -189,67 +189,128 @@ internal AstVisitAction CheckParent(Ast ast) { Diagnostics.Assert(ast.Parent != null, "Parent not set"); } + return AstVisitAction.Continue; } + public override AstVisitAction VisitErrorStatement(ErrorStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitScriptBlock(ScriptBlockAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitParamBlock(ParamBlockAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitNamedBlock(NamedBlockAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitAttribute(AttributeAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitParameter(ParameterAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitTypeExpression(TypeExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitStatementBlock(StatementBlockAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitIfStatement(IfStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitTrap(TrapStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitDataStatement(DataStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitForEachStatement(ForEachStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitForStatement(ForStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitWhileStatement(WhileStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitCatchClause(CatchClauseAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitTryStatement(TryStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitBreakStatement(BreakStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitContinueStatement(ContinueStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitReturnStatement(ReturnStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitExitStatement(ExitStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitThrowStatement(ThrowStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitPipeline(PipelineAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitCommand(CommandAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitCommandExpression(CommandExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitCommandParameter(CommandParameterAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitFileRedirection(FileRedirectionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitBinaryExpression(BinaryExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitUnaryExpression(UnaryExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitConvertExpression(ConvertExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitConstantExpression(ConstantExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitSubExpression(SubExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitUsingExpression(UsingExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitVariableExpression(VariableExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitMemberExpression(MemberExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitArrayExpression(ArrayExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitHashtable(HashtableAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitParenExpression(ParenExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitIndexExpression(IndexExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitBlockStatement(BlockStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitNamedAttributeArgument(NamedAttributeArgumentAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitFunctionMember(FunctionMemberAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitPropertyMember(PropertyMemberAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitUsingStatement(UsingStatementAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst ast) { return CheckParent(ast); } + public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst ast) { return CheckParent(ast); } } @@ -265,6 +326,7 @@ public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { Diagnostics.Assert(!(type is TypeBuilder), "ReflectionType can never be TypeBuilder"); } + return AstVisitAction.Continue; } } @@ -317,6 +379,7 @@ internal static bool IsUsingDollarInput(Ast ast) varAst.VariablePath.UnqualifiedPath.Equals(SpecialVariables.Input, StringComparison.OrdinalIgnoreCase); } + return false; }, searchNestedScriptBlocks: false)); @@ -347,6 +410,7 @@ protected AstVisitAction Check(Ast ast) return AstVisitAction.StopVisit; } } + return AstVisitAction.Continue; } @@ -357,68 +421,128 @@ protected AstVisitAction CheckScriptBlock(Ast ast) { action = AstVisitAction.SkipChildren; } + return action; } public override AstVisitAction VisitErrorStatement(ErrorStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitScriptBlock(ScriptBlockAst ast) { return Check(ast); } + public override AstVisitAction VisitParamBlock(ParamBlockAst ast) { return Check(ast); } + public override AstVisitAction VisitNamedBlock(NamedBlockAst ast) { return Check(ast); } + public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { return Check(ast); } + public override AstVisitAction VisitAttribute(AttributeAst ast) { return Check(ast); } + public override AstVisitAction VisitParameter(ParameterAst ast) { return Check(ast); } + public override AstVisitAction VisitTypeExpression(TypeExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { return CheckScriptBlock(ast); } + public override AstVisitAction VisitStatementBlock(StatementBlockAst ast) { return Check(ast); } + public override AstVisitAction VisitIfStatement(IfStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitTrap(TrapStatementAst ast) { return CheckScriptBlock(ast); } + public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitDataStatement(DataStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitForEachStatement(ForEachStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitForStatement(ForStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitWhileStatement(WhileStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitCatchClause(CatchClauseAst ast) { return Check(ast); } + public override AstVisitAction VisitTryStatement(TryStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitBreakStatement(BreakStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitContinueStatement(ContinueStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitReturnStatement(ReturnStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitExitStatement(ExitStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitThrowStatement(ThrowStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitPipeline(PipelineAst ast) { return Check(ast); } + public override AstVisitAction VisitCommand(CommandAst ast) { return Check(ast); } + public override AstVisitAction VisitCommandExpression(CommandExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitCommandParameter(CommandParameterAst ast) { return Check(ast); } + public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst ast) { return Check(ast); } + public override AstVisitAction VisitFileRedirection(FileRedirectionAst ast) { return Check(ast); } + public override AstVisitAction VisitBinaryExpression(BinaryExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitUnaryExpression(UnaryExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitConvertExpression(ConvertExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitConstantExpression(ConstantExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitSubExpression(SubExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitUsingExpression(UsingExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitVariableExpression(VariableExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitMemberExpression(MemberExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitArrayExpression(ArrayExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst ast) { return Check(ast); } + public override AstVisitAction VisitHashtable(HashtableAst ast) { return Check(ast); } + public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst ast) { return CheckScriptBlock(ast); } + public override AstVisitAction VisitParenExpression(ParenExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitIndexExpression(IndexExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst ast) { return Check(ast); } + public override AstVisitAction VisitNamedAttributeArgument(NamedAttributeArgumentAst ast) { return Check(ast); } + public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst ast) { return Check(ast); } + public override AstVisitAction VisitPropertyMember(PropertyMemberAst ast) { return Check(ast); } + public override AstVisitAction VisitFunctionMember(FunctionMemberAst ast) { return Check(ast); } + public override AstVisitAction VisitUsingStatement(UsingStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitBlockStatement(BlockStatementAst ast) { return Check(ast); } + public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst ast) { return Check(ast); } + public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst ast) { return Check(ast); } } diff --git a/src/System.Management.Automation/engine/parser/CharTraits.cs b/src/System.Management.Automation/engine/parser/CharTraits.cs index 541060659cd..aecb00b7bbd 100644 --- a/src/System.Management.Automation/engine/parser/CharTraits.cs +++ b/src/System.Management.Automation/engine/parser/CharTraits.cs @@ -259,6 +259,7 @@ internal static bool IsVariableStart(this char c) { return (s_traits[c] & CharTraits.VarNameFirst) != 0; } + return char.IsLetterOrDigit(c); } @@ -270,6 +271,7 @@ internal static bool IsIdentifierStart(this char c) { return (s_traits[c] & CharTraits.IdentifierStart) != 0; } + return char.IsLetter(c); } @@ -281,6 +283,7 @@ internal static bool IsIdentifierFollow(this char c) { return (s_traits[c] & (CharTraits.IdentifierStart | CharTraits.Digit)) != 0; } + return char.IsLetterOrDigit(c); } @@ -291,6 +294,7 @@ internal static bool IsHexDigit(this char c) { return (s_traits[c] & CharTraits.HexDigit) != 0; } + return false; } @@ -301,6 +305,7 @@ internal static bool IsDecimalDigit(this char c) { return (s_traits[c] & CharTraits.Digit) != 0; } + return false; } @@ -311,6 +316,7 @@ internal static bool IsTypeSuffix(this char c) { return (s_traits[c] & CharTraits.TypeSuffix) != 0; } + return false; } @@ -321,6 +327,7 @@ internal static bool IsMultiplierStart(this char c) { return (s_traits[c] & CharTraits.MultiplierStart) != 0; } + return false; } diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index cdce773ceb5..d4184de36e3 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -565,6 +565,7 @@ internal static Expression Constant(int i) result = Expression.Constant(i); s_intConstants[i + 1] = result; } + return result; } @@ -625,6 +626,7 @@ internal static Expression Cast(this Expression expr, Type type) Expression.Convert(expr, typeof(object)), Expression.Constant(type, typeof(Type))); } + return Expression.Convert(expr, type); } @@ -728,6 +730,7 @@ static Compiler() DottedLocalsNameIndexMap.Add(SpecialVariables.AutomaticVariables[i], i); DottedScriptCmdletLocalsNameIndexMap.Add(SpecialVariables.AutomaticVariables[i], i); } + for (i = 0; i < SpecialVariables.PreferenceVariables.Length; ++i) { DottedScriptCmdletLocalsNameIndexMap.Add(SpecialVariables.PreferenceVariables[i], @@ -759,8 +762,11 @@ internal Compiler() internal bool CompilingConstantExpression { get; set; } internal bool Optimize { get; private set; } + internal Type LocalVariablesTupleType { get; private set; } + internal ParameterExpression LocalVariablesParameter { get; private set; } + private SymbolDocumentInfo _debugSymbolDocument; internal TypeDefinitionAst _memberFunctionType; private bool _compilingTrap; @@ -782,6 +788,7 @@ internal Type MemberFunctionReturnType Diagnostics.Assert(CompilingMemberFunction, "Return not only set for member functions"); return _memberFunctionReturnType; } + set { _memberFunctionReturnType = value; } } @@ -801,6 +808,7 @@ internal Expression CompileExpressionOperand(ExpressionAst exprAst) { result = Expression.Block(result, ExpressionCache.NullConstant); } + return result; } @@ -837,6 +845,7 @@ internal Expression GetLocal(int tupleIndex) { result = Expression.Property(result, property); } + return result; } @@ -956,6 +965,7 @@ internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) firstConvert = (ConvertExpressionAst)expr; break; } + expr = ((AttributedExpressionAst)expr).Child; } @@ -1074,6 +1084,7 @@ private static Delegate GetAttributeGenerator(CallInfo callInfo) s_attributeGeneratorCache.Add(callInfo, result); } } + return result; } @@ -1368,6 +1379,7 @@ private static Attribute NewAliasAttribute(AttributeAst ast) args[i] = _attrArgToStringConverter.Target(_attrArgToStringConverter, ast.PositionalArguments[i].Accept(s_cvv)); } + return new AliasAttribute(args); } @@ -1476,6 +1488,7 @@ internal static Attribute GetAttribute(AttributeAst attributeAst) var posArg = attributeAst.PositionalArguments[index]; delegateArgs[i++] = posArg.Accept(s_cvv); } + for (int index = 0; index < attributeAst.NamedArguments.Count; index++) { var namedArg = attributeAst.NamedArguments[index]; @@ -1497,6 +1510,7 @@ internal static Attribute GetAttribute(AttributeAst attributeAst) "ExceptionConstructingAttribute", ExtendedTypeSystem.ExceptionConstructingAttribute, innerException, innerException.Message, attributeAst.TypeName.FullName); } + InterpreterError.UpdateExceptionErrorRecordPosition(rte, attributeAst.Extent); throw rte; } @@ -1510,6 +1524,7 @@ internal static Attribute GetAttribute(TypeConstraintAst typeConstraintAst) { type = ihct.CachedType; } + if (type == null) { type = TypeOps.ResolveTypeName(typeConstraintAst.TypeName, typeConstraintAst.Extent); @@ -1518,6 +1533,7 @@ internal static Attribute GetAttribute(TypeConstraintAst typeConstraintAst) ihct.CachedType = type; } } + return new ArgumentTypeConverterAttribute(type); } @@ -1597,6 +1613,7 @@ private static RuntimeDefinedParameter GetRuntimeDefinedParameter(ParameterAst p result.Value = defaultValue; } } + return result; } @@ -1680,6 +1697,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) { _switchTupleIndex = VariableAnalysis.ForceDynamic; } + if (!nameToIndexMap.TryGetValue(SpecialVariables.@foreach, out _foreachTupleIndex)) { _foreachTupleIndex = VariableAnalysis.ForceDynamic; @@ -1855,11 +1873,13 @@ private static object GetExpressionValue(ExpressionAst expressionAst, var boundParameters = new PSBoundParametersDictionary { ImplicitUsingParameters = usingValues }; functionContext._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters, context); } + var result = lambda(functionContext); if (result == AutomationNull.Value) { return resultList.Count == 0 ? null : PipelineOps.PipelineResult(resultList); } + return result; } catch (TargetInvocationException tie) @@ -1915,8 +1935,11 @@ internal LoopGotoTargets(string label, LabelTarget breakLabel, LabelTarget conti this.BreakLabel = breakLabel; this.ContinueLabel = continueLabel; } + internal string Label { get; private set; } + internal LabelTarget ContinueLabel { get; private set; } + internal LabelTarget BreakLabel { get; private set; } } @@ -1977,6 +2000,7 @@ private Expression CaptureAstResults( // Add merge redirection expressions if delegate is provided. generateRedirectExprs(exprs, finallyExprs); } + exprs.Add(Compile(ast)); switch (context) @@ -2043,6 +2067,7 @@ private Expression CaptureStatementResultsHelper( { return GetRedirectedExpression(commandExpressionAst, captureForInput: true); } + return Compile(commandExpressionAst.Expression); } @@ -2054,6 +2079,7 @@ private Expression CaptureStatementResultsHelper( { expr = Expression.Block(expr, ExpressionCache.Empty); } + return expr; } @@ -2083,6 +2109,7 @@ private Expression CaptureStatementResults( // does have a measurable impact, so only set $? = $true if the condition might change $? to $false. // We do this after evaluating the condition so that you could do something like: // if ((dir file1,file2 -ea SilentlyContinue) -and $?) { <# files both exist, otherwise $? would be $false if 0 or 1 files existed #> } + if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, ast => ast is CommandAst, searchNestedScriptBlocks: false) != null) { var tmp = NewTemp(result.Type, "condTmp"); @@ -2091,6 +2118,7 @@ private Expression CaptureStatementResults( s_setDollarQuestionToTrue, tmp); } + return result; } @@ -2138,6 +2166,7 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) _beginBlockLambda = CompileNamedBlock(scriptBlockAst.BeginBlock, funcName + "", rootForDefiningTypesAndUsings); rootForDefiningTypesAndUsings = null; } + if (scriptBlockAst.ProcessBlock != null) { var processFuncName = funcName; @@ -2145,15 +2174,18 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { processFuncName = funcName + ""; } + _processBlockLambda = CompileNamedBlock(scriptBlockAst.ProcessBlock, processFuncName, rootForDefiningTypesAndUsings); rootForDefiningTypesAndUsings = null; } + if (scriptBlockAst.EndBlock != null) { if (!scriptBlockAst.EndBlock.Unnamed) { funcName = funcName + ""; } + _endBlockLambda = CompileNamedBlock(scriptBlockAst.EndBlock, funcName, rootForDefiningTypesAndUsings); } @@ -2348,6 +2380,7 @@ internal static void GenerateLoadUsings(IEnumerable usingStat TypeOps.GetNamespacesForTypeResolutionState(usingStatements), assemblies); } + exprs.Add(Expression.Call(CachedReflectionInfo.TypeOps_SetCurrentTypeResolutionState, Expression.Constant(trs), _executionContextParameter)); if (typesToAdd != null && typesToAdd.Count > 0) @@ -2430,6 +2463,7 @@ private static Dictionary LoadUsingsImpl(IEnumerable< types[SymbolResolver.GetModuleQualifiedName(module.Name, nameTypePair.Key)] = nameTypePair.Value; } } + break; case UsingStatementKind.Namespace: break; @@ -2498,6 +2532,7 @@ private static Assembly LoadAssembly(string assemblyName, string scriptFileName) ParserStrings.ErrorLoadingAssembly, assemblyName); } + return assembly; } @@ -2678,6 +2713,7 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) { exprs.Add(ExpressionCache.Empty); } + return Expression.Block(typeof(void), temps, exprs); } @@ -3148,6 +3184,7 @@ public object VisitPipeline(PipelineAst pipelineAst) i = 0; commandsInPipe = pipeElements.Count; } + Expression[] pipelineExprs = new Expression[commandsInPipe]; CommandBaseAst[] pipeElementAsts = new CommandBaseAst[commandsInPipe]; var commandRedirections = new object[commandsInPipe]; @@ -3421,6 +3458,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // finally { // finallyExprs // } + var wrapExpr = Expression.TryFinally(Expression.Block(exprs), Expression.Block(extraFileRedirectExprs)); exprs.Clear(); exprs.Add(wrapExpr); @@ -3447,6 +3485,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo { return Expression.Block(temps.ToArray(), Expression.TryFinally(Expression.Block(exprs), Expression.Block(finallyExprs))); } + return Expression.Block(temps.ToArray(), exprs); } @@ -3609,6 +3648,7 @@ public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return expr; } + return CallAddPipe(expr, s_getCurrentPipe); } @@ -4055,6 +4095,7 @@ private static CatchBlock[] GenerateLoopBreakContinueCatchBlocks(string label, L return new[] { // catch (BreakException ev) { if (ev.MatchLabel(loopStatement.Label) { goto breakTarget; } throw; } + Expression.Catch(breakExceptionVar, Expression.IfThenElse( Expression.Call(breakExceptionVar, @@ -4064,6 +4105,7 @@ private static CatchBlock[] GenerateLoopBreakContinueCatchBlocks(string label, L Expression.Rethrow())), // catch (ContinueException ev) { if (ev.MatchLabel(loopStatement.Label) { goto continueTarget; } throw; } + Expression.Catch(continueExceptionVar, Expression.IfThenElse( Expression.Call(continueExceptionVar, @@ -4144,6 +4186,7 @@ private Expression GenerateWhileLoop(string loopLabel, { loopBodyExprs.Add(Expression.Goto(loopTop)); } + _loopTargets.RemoveAt(_loopTargets.Count - 1); Expression loopBody = @@ -4174,6 +4217,7 @@ private Expression GenerateWhileLoop(string loopLabel, { exprs.Add(loopBody); } + exprs.Add(Expression.Label(breakLabel)); enterLoop.LoopStatementCount = _stmtCount - preStmtCount; return (enterLoop.Loop = new PowerShellLoopExpression(exprs)); @@ -4234,6 +4278,7 @@ private Expression GenerateDoLoop(LoopStatementAst loopStatement) { test = Expression.Not(test); } + test = UpdatePositionForInitializerOrCondition(loopStatement.Condition, test); exprs.Add(Expression.IfThen(test, Expression.Goto(repeatLabel))); exprs.Add(Expression.Label(breakLabel)); @@ -4462,6 +4507,7 @@ public object VisitForStatement(ForStatementAst forStatementAst) { return Expression.Block(init, loop); } + return loop; } @@ -4584,6 +4630,7 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) // $_ = oldDollarUnder // context.CurrentExceptionBeingHandled = oldrte // } + AutomaticVarSaver avs = new AutomaticVarSaver(this, SpecialVariables.UnderbarVarPath, (int)AutomaticVariable.Underbar); var rte = NewTemp(typeof(RuntimeException), "rte"); @@ -4695,6 +4742,7 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) Expression.Constant(ct.TypeName), Expression.Constant(ct.Extent))))); } + i += 1; } } @@ -4997,6 +5045,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { result = Expression.Not(result); } + return result; case TokenKind.As: @@ -5015,6 +5064,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { return Expression.Multiply(lhs, rhs); } + binder = PSBinaryOperationBinder.Get(ExpressionType.Multiply); return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); case TokenKind.Divide: @@ -5022,6 +5072,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { return Expression.Divide(lhs, rhs); } + binder = PSBinaryOperationBinder.Get(ExpressionType.Divide); return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); case TokenKind.Rem: @@ -5032,6 +5083,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { return Expression.Add(lhs, rhs); } + binder = PSBinaryOperationBinder.Get(ExpressionType.Add); return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); case TokenKind.Minus: @@ -5039,6 +5091,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { return Expression.Subtract(lhs, rhs); } + binder = PSBinaryOperationBinder.Get(ExpressionType.Subtract); return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); case TokenKind.Format: @@ -5046,6 +5099,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { lhs = DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), lhs, _executionContextParameter); } + return Expression.Call(CachedReflectionInfo.StringOps_FormatOperator, lhs, rhs.Cast(typeof(object))); case TokenKind.Xor: return Expression.NotEqual(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); @@ -5306,6 +5360,7 @@ private Expression CompileIncrementOrDecrement(ExpressionAst exprAst, int valueT ExpressionCache.Constant(0).Cast(typeof(object)), tmp)); } } + temps.Add(tmp); return Expression.Block(temps, exprs); } @@ -5330,6 +5385,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) new[] { temp }, BuildHashtable(hashTableAst.KeyValuePairs, temp, ordered: true)); } + if (typeName.FullName.Equals("PSCustomObject", StringComparison.OrdinalIgnoreCase)) { // pure laziness here - we should construct the PSObject directly. Instead, we're relying on the conversion @@ -5421,10 +5477,12 @@ public object VisitVariableExpression(VariableExpressionAst variableExpressionAs { return ExpressionCache.NullConstant; } + if (varPath.UnqualifiedPath.Equals(SpecialVariables.True, StringComparison.OrdinalIgnoreCase)) { return ExpressionCache.Constant(true); } + if (varPath.UnqualifiedPath.Equals(SpecialVariables.False, StringComparison.OrdinalIgnoreCase)) { return ExpressionCache.Constant(false); @@ -5453,6 +5511,7 @@ public object VisitVariableExpression(VariableExpressionAst variableExpressionAs { return CallGetVariable(Expression.Constant(variableExpressionAst.VariablePath), variableExpressionAst); } + return GetLocal(tupleIndex); } @@ -5655,6 +5714,7 @@ public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) return Expression.NewArrayInit(typeof(object)); } } + values = values ?? CaptureAstResults(subExpr, CaptureAstContext.Enumerable); if (pureExprAst is ArrayLiteralAst) @@ -5662,12 +5722,14 @@ public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) // If the pure expression is ArrayLiteralAst, just return the result. return values; } + if (values.Type.IsPrimitive || values.Type == typeof(string)) { // Slight optimization - no need for a dynamic site. We could special case other // types as well, but it's probably not worth it. return Expression.NewArrayInit(typeof(object), values.Cast(typeof(object))); } + if (values.Type == typeof(void)) { // A dynamic site can't take void - but a void value is just an empty array. @@ -5685,6 +5747,7 @@ public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) var eValue = Compile(element); elementValues.Add(eValue.Type != typeof(void) ? eValue.Cast(typeof(object)) : Expression.Block(eValue, ExpressionCache.AutomationNullConstant)); } + return Expression.NewArrayInit(typeof(object), elementValues); } @@ -5708,6 +5771,7 @@ private IEnumerable BuildHashtable(ReadOnlyCollection Expression.Call(CachedReflectionInfo.HashtableOps_AddKeyValuePair, temp, key, value, errorExtent); } + yield return temp; } @@ -5991,6 +6055,7 @@ public Expression GetValue(Compiler compiler, List exprs, List _exprs; @@ -6115,7 +6183,9 @@ public void AddInstructions(LightCompiler compiler) internal class EnterLoopExpression : Expression, Interpreter.IInstructionProvider { public override bool CanReduce { get { return true; } } + public override Type Type { get { return typeof(void); } } + public override ExpressionType NodeType { get { return ExpressionType.Extension; } } public override Expression Reduce() @@ -6125,6 +6195,7 @@ public override Expression Reduce() internal new PowerShellLoopExpression Loop { get; set; } internal EnterLoopInstruction EnterLoopInstruction { get; private set; } + internal int LoopStatementCount { get; set; } public void AddInstructions(LightCompiler compiler) @@ -6145,7 +6216,9 @@ public void AddInstructions(LightCompiler compiler) internal class UpdatePositionExpr : Expression, Interpreter.IInstructionProvider { public override bool CanReduce { get { return true; } } + public override Type Type { get { return typeof(void); } } + public override ExpressionType NodeType { get { return ExpressionType.Extension; } } private readonly IScriptExtent _extent; @@ -6186,6 +6259,7 @@ public override Expression Reduce() CachedReflectionInfo.Debugger_OnSequencePointHit, Compiler._functionContext))); } + exprs.Add(ExpressionCache.Empty); return Expression.Block(exprs); diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index c81e0b2713e..74c83f93980 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -30,6 +30,7 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu { break; } + parent = parent.Parent; } @@ -56,41 +57,77 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu internal bool CheckingRequiresArgument { get; set; } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } + public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } + public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } + public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } + public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return false; } + public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return false; } + public object VisitAttribute(AttributeAst attributeAst) { return false; } + public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return false; } + public object VisitParameter(ParameterAst parameterAst) { return false; } + public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return false; } + public object VisitIfStatement(IfStatementAst ifStmtAst) { return false; } + public object VisitTrap(TrapStatementAst trapStatementAst) { return false; } + public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return false; } + public object VisitDataStatement(DataStatementAst dataStatementAst) { return false; } + public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return false; } + public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return false; } + public object VisitForStatement(ForStatementAst forStatementAst) { return false; } + public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return false; } + public object VisitCatchClause(CatchClauseAst catchClauseAst) { return false; } + public object VisitTryStatement(TryStatementAst tryStatementAst) { return false; } + public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return false; } + public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return false; } + public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return false; } + public object VisitExitStatement(ExitStatementAst exitStatementAst) { return false; } + public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return false; } + public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } + public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } + public object VisitCommand(CommandAst commandAst) { return false; } + public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return false; } + public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return false; } + public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return false; } + public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return false; } + public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { return false; } + public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { return false; } + public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return false; } + public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return false; } + public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return false; } public object VisitStatementBlock(StatementBlockAst statementBlockAst) @@ -155,12 +192,14 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { return false; } + if (!type.IsSafePrimitive()) { // Only do conversions to built-in types - other conversions might not // be safe to optimize. return false; } + return (bool)convertExpressionAst.Child.Accept(this); } @@ -288,41 +327,77 @@ private static object CompileAndInvoke(Ast ast) } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return AutomationNull.Value; } + public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return AutomationNull.Value; } + public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return AutomationNull.Value; } + public object VisitParamBlock(ParamBlockAst paramBlockAst) { return AutomationNull.Value; } + public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return AutomationNull.Value; } + public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return AutomationNull.Value; } + public object VisitAttribute(AttributeAst attributeAst) { return AutomationNull.Value; } + public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return AutomationNull.Value; } + public object VisitParameter(ParameterAst parameterAst) { return AutomationNull.Value; } + public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return AutomationNull.Value; } + public object VisitIfStatement(IfStatementAst ifStmtAst) { return AutomationNull.Value; } + public object VisitTrap(TrapStatementAst trapStatementAst) { return AutomationNull.Value; } + public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AutomationNull.Value; } + public object VisitDataStatement(DataStatementAst dataStatementAst) { return AutomationNull.Value; } + public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return AutomationNull.Value; } + public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return AutomationNull.Value; } + public object VisitForStatement(ForStatementAst forStatementAst) { return AutomationNull.Value; } + public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return AutomationNull.Value; } + public object VisitCatchClause(CatchClauseAst catchClauseAst) { return AutomationNull.Value; } + public object VisitTryStatement(TryStatementAst tryStatementAst) { return AutomationNull.Value; } + public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return AutomationNull.Value; } + public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return AutomationNull.Value; } + public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return AutomationNull.Value; } + public object VisitExitStatement(ExitStatementAst exitStatementAst) { return AutomationNull.Value; } + public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return AutomationNull.Value; } + public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return AutomationNull.Value; } + public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return AutomationNull.Value; } + public object VisitCommand(CommandAst commandAst) { return AutomationNull.Value; } + public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return AutomationNull.Value; } + public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return AutomationNull.Value; } + public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return AutomationNull.Value; } + public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return AutomationNull.Value; } + public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { return AutomationNull.Value; } + public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { return AutomationNull.Value; } + public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return AutomationNull.Value; } + public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return AutomationNull.Value; } + public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return AutomationNull.Value; } public object VisitStatementBlock(StatementBlockAst statementBlockAst) @@ -442,6 +517,7 @@ public object VisitHashtable(HashtableAst hashtableAst) { result.Add(pair.Item1.Accept(this), pair.Item2.Accept(this)); } + return result; } } diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 0e462e0516d..36725b9ff9a 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -86,6 +86,7 @@ private int Depth { private void Indent() { _delta += Tab; } + private void Dedent() { _delta -= Tab; } @@ -106,6 +107,7 @@ private static int GetId(T e, ref Dictionary ids) { id = ids.Count + 1; ids.Add(e, id); } + return id; } } @@ -181,6 +183,7 @@ private void Out(Flow before, string s, Flow after) { Write(new String(' ', Depth)); break; } + Write(s); _flow = after; } @@ -189,6 +192,7 @@ private void WriteLine() { _out.WriteLine(); _column = 0; } + private void Write(string s) { _out.Write(s); _column += s.Length; @@ -212,6 +216,7 @@ private Flow CheckBreak(Flow flow) { flow &= ~Flow.Break; } } + return flow; } @@ -278,6 +283,7 @@ private void VisitDeclarations(IList expressions) { if (variable.IsByRef) { Out("&"); } + Out(" "); VisitParameter(variable); }); @@ -294,12 +300,15 @@ private void VisitExpressions(char open, char separator, IList expressions if (open == '{' || expressions.Count > 1) { NewLine(); } + isFirst = false; } else { Out(separator.ToString(), Flow.NewLine); } + visit(e); } + Dedent(); } @@ -318,6 +327,7 @@ private void VisitExpressions(char open, char separator, IList expressions if (open == '{') { NewLine(); } + Out(close.ToString(), Flow.Break); } @@ -403,16 +413,19 @@ protected override Expression VisitBinary(BinaryExpression node) { op ); } + Out(beforeOp, op, Flow.Space | Flow.Break); if (parenthesizeRight) { Out("(", Flow.None); } + Visit(node.Right); if (parenthesizeRight) { Out(Flow.None, ")", Flow.Break); } } + return node; } @@ -428,6 +441,7 @@ protected override Expression VisitParameter(ParameterExpression node) { } else { Out(GetDisplayName(node.Name)); } + return node; } @@ -474,6 +488,7 @@ protected override Expression VisitConditional(ConditionalExpression node) { Dedent(); Out(Flow.NewLine, ") {", Flow.NewLine); } + Indent(); Visit(node.IfTrue); Dedent(); @@ -516,6 +531,7 @@ protected override Expression VisitConstant(ConstantExpression node) { value)); } } + return node; } @@ -523,21 +539,27 @@ private static string GetConstantValueSuffix(Type type) { if (type == typeof(UInt32)) { return "U"; } + if (type == typeof(Int64)) { return "L"; } + if (type == typeof(UInt64)) { return "UL"; } + if (type == typeof(Double)) { return "D"; } + if (type == typeof(Single)) { return "F"; } + if (type == typeof(Decimal)) { return "M"; } + return null; } @@ -628,6 +650,7 @@ private static bool NeedsParentheses(Expression parent, Expression child) { // Need to have parenthesis for the right operand. return child == binary.Right; } + return true; } @@ -782,6 +805,7 @@ protected override Expression VisitMethodCall(MethodCallExpression node) { } else { Out(""); } + Out("."); Out(node.Method.Name); VisitExpressions('(', node.Arguments); @@ -795,9 +819,11 @@ protected override Expression VisitNewArray(NewArrayExpression node) { VisitExpressions('[', node.Expressions); } else { // .NewArray MyType {expr1, expr2} + Out(".NewArray " + node.Type.ToString(), Flow.Space); VisitExpressions('{', node.Expressions); } + return node; } @@ -813,6 +839,7 @@ protected override ElementInit VisitElementInit(ElementInit node) { } else { VisitExpressions('{', node.Arguments); } + return node; } @@ -859,6 +886,7 @@ protected override Expression VisitTypeBinary(TypeBinaryExpression node) { Out(Flow.Space, ".TypeEqual", Flow.Space); break; } + Out(node.TypeOperand.ToString()); return node; } @@ -902,6 +930,7 @@ protected override Expression VisitUnary(UnaryExpression node) { } else { Out(".Throw", Flow.Space); } + break; case ExpressionType.IsFalse: Out(".IsFalse"); @@ -946,6 +975,7 @@ protected override Expression VisitUnary(UnaryExpression node) { Out("++"); break; } + return node; } @@ -995,6 +1025,7 @@ protected override Expression VisitLoop(LoopExpression node) { if (node.ContinueLabel != null) { DumpLabel(node.ContinueLabel); } + Out(" {", Flow.NewLine); Indent(); Visit(node.Body); @@ -1004,6 +1035,7 @@ protected override Expression VisitLoop(LoopExpression node) { Out(string.Empty, Flow.NewLine); DumpLabel(node.BreakLabel); } + return node; } @@ -1013,6 +1045,7 @@ protected override SwitchCase VisitSwitchCase(SwitchCase node) { Visit(test); Out("):", Flow.NewLine); } + Indent(); Indent(); Visit(node.Body); Dedent(); Dedent(); @@ -1033,6 +1066,7 @@ protected override Expression VisitSwitch(SwitchExpression node) { Dedent(); Dedent(); NewLine(); } + Out("}"); return node; } @@ -1043,10 +1077,12 @@ protected override CatchBlock VisitCatchBlock(CatchBlock node) { Out(Flow.Space, string.Empty); VisitParameter(node.Variable); } + if (node.Filter != null) { Out(") .If (", Flow.Break); Visit(node.Filter); } + Out(") {", Flow.NewLine); Indent(); Visit(node.Body); @@ -1150,6 +1186,7 @@ private string GetLambdaName(LambdaExpression lambda) { if (String.IsNullOrEmpty(lambda.Name)) { return "#Lambda" + GetLambdaId(lambda); } + return GetDisplayName(lambda.Name); } @@ -1163,6 +1200,7 @@ private static bool ContainsWhiteSpace(string name) { return true; } } + return false; } diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs index f16f64f54ad..b4fe6eaba9e 100644 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs @@ -22,6 +22,7 @@ internal static class GlobalAssemblyCache /// public static readonly ProcessorArchitecture[] CurrentArchitectures = (IntPtr.Size == 4) ? new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86 } + : new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64 }; #region Interop @@ -99,6 +100,7 @@ private enum ASM_CACHE // no assembly found yield break; } + if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); @@ -107,6 +109,7 @@ private enum ASM_CACHE // invalid assembly name: yield break; } + if (e != null) { throw e; diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index a495ea5f5aa..38d7a2ad8d9 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -34,6 +34,7 @@ private static bool TryConvertArg(object arg, Type type, out object result, Pars result = arg; return true; } + if (!LanguagePrimitives.TryConvertTo(arg, type, out result)) { parser.ReportError(errorExtent, @@ -42,6 +43,7 @@ private static bool TryConvertArg(object arg, Type type, out object result, Pars ToStringCodeMethods.Type(type)); return false; } + return true; } @@ -117,8 +119,10 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu { return null; } + paramsArray.SetValue(arg, i); } + break; } @@ -127,6 +131,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu { return null; } + ctorArgs[argIndex] = arg; } @@ -171,6 +176,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu { return null; } + fieldInfoList.Add(fieldInfo); fieldArgs.Add(arg); } @@ -491,6 +497,7 @@ public void DefineMembers() instanceCtors.Add(method); } } + hasAnyMethods = true; DefineMethod(method); @@ -652,6 +659,7 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type { setIlGen.Emit(OpCodes.Box, type); } + setIlGen.Emit(OpCodes.Call, CachedReflectionInfo.ClassOps_ValidateSetProperty); } @@ -666,6 +674,7 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type setIlGen.Emit(OpCodes.Ldarg_1); setIlGen.Emit(OpCodes.Stfld, backingField); } + setIlGen.Emit(OpCodes.Ret); // Map the two methods created above to our PropertyBuilder to @@ -764,8 +773,10 @@ private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) typeConstraint.TypeName.FullName); anyErrors = true; } + result[i] = paramType; } + return anyErrors ? null : result; } @@ -778,6 +789,7 @@ private bool MethodExistsOnBaseClassAndFinal(string methodName, Type[] parameter { return false; } + var mi = baseType.GetMethod(methodName, parameterTypes); return mi != null && mi.IsFinal; } @@ -790,6 +802,7 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) // There must have been an error, just return return; } + if (CheckForDuplicateOverload(functionMemberAst, parameterTypes)) { return; @@ -809,8 +822,10 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) ParserStrings.StaticConstructorCantHaveParameters); return; } + methodAttributes |= Reflection.MethodAttributes.Static; } + DefineConstructor(functionMemberAst, functionMemberAst.Attributes, functionMemberAst.IsHidden, methodAttributes, parameterTypes); return; } @@ -829,8 +844,10 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) attributes |= Reflection.MethodAttributes.HideBySig; attributes |= Reflection.MethodAttributes.NewSlot; } + attributes |= Reflection.MethodAttributes.Virtual; } + var returnType = functionMemberAst.GetReturnType(); if (returnType == null) { @@ -840,12 +857,14 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) functionMemberAst.ReturnType.TypeName.FullName); return; } + var method = _typeBuilder.DefineMethod(functionMemberAst.Name, attributes, returnType, parameterTypes); DefineCustomAttributes(method, functionMemberAst.Attributes, _parser, AttributeTargets.Method); if (functionMemberAst.IsHidden) { method.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } + var ilGenerator = method.GetILGenerator(); DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Count()), functionMemberAst.IsStatic, parameterTypes, returnType, (i, n) => method.DefineParameter(i, ParameterAttributes.None, n)); @@ -862,6 +881,7 @@ private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollecti { ctor.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } + var ilGenerator = ctor.GetILGenerator(); if (!isStatic) @@ -932,12 +952,14 @@ private void DefineMethodBody( { ilGenerator.Emit(OpCodes.Box, parameterTypes[i]); } + ilGenerator.Emit(OpCodes.Stelem_Ref); // save the argument in the array // Set the parameter name, mostly for Get-Member // Parameters are indexed beginning with the number 1 for the first parameter parameterNameSetter(i + 1, parameters[i].Name.VariablePath.UserPath); } + ilGenerator.Emit(OpCodes.Ldloc, local); // load array } else @@ -954,6 +976,7 @@ private void DefineMethodBody( { invokeHelper = typeof(ScriptBlockMemberMethodWrapper).GetMethod("InvokeHelperT", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(returnType); } + ilGenerator.Emit(OpCodes.Tailcall); ilGenerator.EmitCall(OpCodes.Call, invokeHelper, null); ilGenerator.Emit(OpCodes.Ret); @@ -1183,6 +1206,7 @@ internal void DefineEnum() } } } + _enumDefinitionAst.Type = enumBuilder.CreateTypeInfo().AsType(); } } @@ -1330,6 +1354,7 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst nameParts.Add("<" + parent.Extent.Text.GetHashCode().ToString("x", CultureInfo.InvariantCulture) + ">"); } } + parent = parent.Parent; } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 9e1097621ea..457bfb3b5e7 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -100,6 +100,7 @@ public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out { DynamicKeyword.Push(); } + result = parser.Parse(fileName, scriptContents, tokenList, out errors, ParseMode.Default); } catch (Exception e) @@ -117,6 +118,7 @@ public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out tokens = tokenList.ToArray(); return result; } + private string _keywordModuleName; /// @@ -276,6 +278,7 @@ internal static ITypeName ScanType(string typename, bool ignoreErrors) { result = null; } + return result; } @@ -290,6 +293,7 @@ internal static ExpressionAst ScanString(string str) { throw new ParseException(parser.ErrorList.ToArray()); } + return ast; } @@ -331,6 +335,7 @@ internal void SetPreviousFirstLastToken(ExecutionContext context) } //public bool V3FeatureUsed { get { return _v3FeatureUsed; } } + internal List ErrorList { get; } #region Utilities @@ -383,8 +388,10 @@ private void SyncOnError(bool consumeClosingToken, params TokenKind[] syncTokens { UngetToken(token); } + return; } + break; case TokenKind.LCurly: ++curlies; break; @@ -396,8 +403,10 @@ private void SyncOnError(bool consumeClosingToken, params TokenKind[] syncTokens { UngetToken(token); } + return; } + break; case TokenKind.LBracket: ++braces; break; @@ -409,8 +418,10 @@ private void SyncOnError(bool consumeClosingToken, params TokenKind[] syncTokens { UngetToken(token); } + return; } + break; case TokenKind.EndOfInput: @@ -465,6 +476,7 @@ private Token NextLBracket() // If _ungotToken is not null, we're in some sort of error state, don't return the token. return null; } + return _tokenizer.GetLBracket(); } @@ -475,6 +487,7 @@ private StringToken GetVerbatimCommandArgumentToken() _ungotToken = null; return _tokenizer.GetVerbatimCommandArgument(); } + return null; } @@ -525,6 +538,7 @@ private void SetTokenizerMode(TokenizerMode mode) } #endif } + _tokenizer.Mode = mode; } @@ -606,6 +620,7 @@ internal static IScriptExtent LastCharacterOf(IScriptExtent extent) { offset = 0; } + return new InternalScriptExtent(scriptExtent.PositionHelper, offset, offset); } @@ -637,21 +652,32 @@ internal static IScriptExtent ExtentFromFirstOf(params object[] objs) return (IScriptExtent)obj; } } + Diagnostics.Assert(false, "One of the objects must not be null"); return PositionUtilities.EmptyExtent; } internal static IScriptExtent ExtentOf(Token first, Token last) { return ExtentOf(first.Extent, last.Extent); } + internal static IScriptExtent ExtentOf(Ast first, Ast last) { return ExtentOf(first.Extent, last.Extent); } + internal static IScriptExtent ExtentOf(Ast first, Token last) { return ExtentOf(first.Extent, last.Extent); } + internal static IScriptExtent ExtentOf(Token first, Ast last) { return ExtentOf(first.Extent, last.Extent); } + internal static IScriptExtent ExtentOf(IScriptExtent first, Ast last) { return ExtentOf(first, last.Extent); } + internal static IScriptExtent ExtentOf(IScriptExtent first, Token last) { return ExtentOf(first, last.Extent); } + internal static IScriptExtent ExtentOf(Ast first, IScriptExtent last) { return ExtentOf(first.Extent, last); } + internal static IScriptExtent ExtentOf(Token first, IScriptExtent last) { return ExtentOf(first.Extent, last); } //private static IScriptExtent Before(Ast ast) { return Before(ast.Extent); } + internal static IScriptExtent Before(Token token) { return Before(token.Extent); } + internal static IScriptExtent After(Ast ast) { return After(ast.Extent); } + internal static IScriptExtent After(Token token) { return After(token.Extent); } private static IEnumerable GetNestedErrorAsts(params object[] asts) @@ -789,6 +815,7 @@ private ScriptBlockAst ScriptBlockRule(Token lCurly, bool isFilter, StatementAst // mean something different, such as a type literal expression, or a cast.) Resync(restorePoint); } + SkipNewlinesAndSemicolons(); return ScriptBlockBodyRule(lCurly, usingStatements, paramBlock, isFilter, predefinedStatementAst); @@ -810,6 +837,7 @@ private List UsingStatementsRule() { result = new List(); } + var usingStatement = statement as UsingStatementAst; // otherwise returned statement is ErrorStatementAst. // We ignore it here, because error already reported to the parser. @@ -817,6 +845,7 @@ private List UsingStatementsRule() { result.Add(usingStatement); } + continue; } @@ -920,8 +949,10 @@ private List ParameterListRule() ParserStrings.MissingExpressionAfterToken, commaToken.Kind.Text()); } + break; } + parameters.Add(parameter); SkipNewlines(); commaToken = PeekToken(); @@ -929,6 +960,7 @@ private List ParameterListRule() { break; } + SkipToken(); } @@ -974,6 +1006,7 @@ private ParameterAst ParameterRule() var extent = ExtentOf(attributes[0].Extent, attributes[attributes.Count - 1].Extent); return new ParameterAst(extent, new VariableExpressionAst(extent, "__error__", false), attributes, null); } + return null; } @@ -1022,6 +1055,7 @@ private List AttributeListRule(bool inExpressionMode) { SkipNewlines(); } + attribute = AttributeRule(); } @@ -1093,6 +1127,7 @@ private AttributeBaseAst AttributeRule() nameof(ParserStrings.MissingEndParenthesisInExpression), ParserStrings.MissingEndParenthesisInExpression); } + SkipNewlines(); Token rBracket = NextToken(); if (rBracket.Kind != TokenKind.RBracket) @@ -1179,6 +1214,7 @@ private void AttributeArgumentsRule(ICollection positionalArgumen expr = new ErrorExpressionAst(errorPosition); SyncOnError(true, TokenKind.Comma, TokenKind.RParen, TokenKind.RBracket, TokenKind.NewLine); } + lastItemExtent = expr.Extent; } else @@ -1350,6 +1386,7 @@ private ITypeName FinishTypeNameRule(Token typeName, bool unBracketedGenericArg nameof(ParserStrings.MissingTypename), ParserStrings.MissingTypename); } + return new TypeName(typeName.Extent, typeName.Text); } } @@ -1365,6 +1402,7 @@ private ITypeName FinishTypeNameRule(Token typeName, bool unBracketedGenericArg ParserStrings.MissingAssemblyNameSpecification); return new TypeName(typeName.Extent, typeName.Text); } + return new TypeName(ExtentOf(typeName.Extent, _tokenizer.CurrentExtent()), typeName.Text, assemblyNameSpec); } @@ -1427,6 +1465,7 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok { break; } + V3SkipNewlines(); token = PeekToken(); @@ -1442,6 +1481,7 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok ParserStrings.MissingTypename); typeName = new TypeName(commaOrRBracketToken.Extent, ":ErrorTypeName:"); } + genericArguments.Add(typeName); } @@ -1465,6 +1505,7 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok SkipToken(); return CompleteArrayTypeName(result, openGenericType, NextToken()); } + if (token.Kind == TokenKind.Comma && !unBracketedGenericArg) { SkipToken(); @@ -1480,6 +1521,7 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok openGenericType.AssemblyName = assemblyNameSpec; } } + return result; } @@ -1551,6 +1593,7 @@ private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForA { typeForAssemblyQualification.AssemblyName = assemblyName; } + break; } @@ -1596,6 +1639,7 @@ private bool CompleteScriptBlockBody(Token lCurly, ref IScriptExtent bodyExtent, bodyExtent = ExtentOf(After(lCurly), Before(rCurly)); } } + fullBodyExtent = ExtentOf(lCurly, endScriptBlock); } else @@ -1638,6 +1682,7 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List { statements.Add(predefinedStatementAst); } + IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null; IScriptExtent scriptBlockExtent; @@ -1728,6 +1773,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List { startExtent = blockNameToken.Extent; } + endExtent = blockNameToken.Extent; StatementBlockAst statementBlock = StatementBlockRule(); @@ -1776,6 +1822,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List SkipNewlinesAndSemicolons(); } + finished_named_block_list: CompleteScriptBlockBody(lCurly, ref extent, out scriptBlockExtent); @@ -1859,6 +1906,7 @@ private IScriptExtent StatementListRule(List statements, List custom { _inConfiguration = oldInConfiguration; } + if (configurationBodyScriptBlock == null) { ReportError(After(lCurly.Extent), @@ -3075,6 +3137,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom keywordProp.TypeConstraint = typeConstraint.TypeName.Name; continue; } + var aAst = attr as AttributeAst; if (aAst != null) { @@ -3105,6 +3168,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom } } } + keywordToAddForThisConfigurationStatement.Properties.Add(keywordProp.Name, keywordProp); } } @@ -3138,6 +3202,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom attribute => (attribute.TypeName.GetReflectionAttributeType() != null) && (attribute.TypeName.GetReflectionAttributeType() == typeof(DscLocalConfigurationManagerAttribute))); } + ScriptBlockExpressionAst bodyAst = configurationBodyScriptBlock as ScriptBlockExpressionAst; IScriptExtent configurationExtent = ExtentOf(startExtent, bodyAst); return new ConfigurationDefinitionAst(configurationExtent, @@ -3217,6 +3282,7 @@ private ExpressionAst GetWordOrExpression(Token keywordToken) ParserStrings.ParameterRequiresArgument, keywordToken.Text); } + return argument; } @@ -3295,6 +3361,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo forEachToken.Kind.Text()); return new ErrorStatementAst(ExtentOf(startOfStatement, endErrorStatement)); } + SkipNewlines(); Token token = NextToken(); @@ -3418,32 +3485,38 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) forToken.Kind.Text()); return new ErrorStatementAst(ExtentOf(labelToken ?? forToken, endErrorStatement)); } + SkipNewlines(); PipelineBaseAst initializer = PipelineRule(); if (initializer != null) { endErrorStatement = initializer.Extent; } + if (PeekToken().Kind == TokenKind.Semi) { endErrorStatement = NextToken().Extent; } + SkipNewlines(); PipelineBaseAst condition = PipelineRule(); if (condition != null) { endErrorStatement = condition.Extent; } + if (PeekToken().Kind == TokenKind.Semi) { endErrorStatement = NextToken().Extent; } + SkipNewlines(); PipelineBaseAst iterator = PipelineRule(); if (iterator != null) { endErrorStatement = iterator.Extent; } + SkipNewlines(); Token rParen = NextToken(); StatementBlockAst body = null; @@ -3456,6 +3529,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) { endErrorStatement = lParen.Extent; } + ReportIncompleteInput(After(endErrorStatement), nameof(ParserStrings.MissingEndParenthesisAfterStatement), ParserStrings.MissingEndParenthesisAfterStatement, @@ -3542,6 +3616,7 @@ private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) ParserStrings.MissingEndParenthesisAfterStatement, whileToken.Kind.Text()); } + return new ErrorStatementAst(ExtentOf(labelToken ?? whileToken, condition), GetNestedErrorAsts(errorCondition)); } @@ -3659,6 +3734,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw nameof(ParserStrings.MissingBraceInObjectDefinition), ParserStrings.MissingBraceInObjectDefinition); } + return null; } @@ -3724,6 +3800,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw ParserStrings.UnexpectedToken, nameToken.Text); } + return null; } @@ -4023,6 +4100,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) ParserStrings.MissingExpressionAfterKeyword, whileOrUntilToken.Kind.Text()); } + SkipNewlines(); rParen = NextToken(); if (rParen.Kind != TokenKind.RParen) @@ -4056,6 +4134,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) { return new DoUntilStatementAst(extent, label, condition, body); } + return new DoWhileStatementAst(extent, label, condition, body); } @@ -4161,12 +4240,14 @@ private StatementAst ClassDefinitionRule(List customAttributes members.Add(member); lastExtent = member.Extent; } + if (astsOnError != null && astsOnError.Count > 0) { if (nestedAsts == null) { nestedAsts = new List(); } + nestedAsts.AddRange(astsOnError); lastExtent = astsOnError.Last().Extent; } @@ -4278,6 +4359,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) { ReportError(attribute.Extent, nameof(ParserStrings.TooManyTypes), ParserStrings.TooManyTypes); } + continue; } @@ -4298,6 +4380,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) ParserStrings.DuplicateQualifier, token.Text); } + if (privateToken != null) { ReportError(token.Extent, @@ -4306,6 +4389,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) privateToken.Text, token.Text); } + publicToken = token; SkipToken(); break; @@ -4318,6 +4402,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) ParserStrings.DuplicateQualifier, token.Text); } + if (publicToken != null) { ReportError(token.Extent, @@ -4326,6 +4411,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) publicToken.Text, token.Text); } + privateToken = token; SkipToken(); break; @@ -4339,6 +4425,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) ParserStrings.DuplicateQualifier, token.Text); } + hiddenToken = token; lastAttribute = token; SkipToken(); @@ -4352,6 +4439,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) ParserStrings.DuplicateQualifier, token.Text); } + staticToken = token; lastAttribute = token; SkipToken(); @@ -4387,6 +4475,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) { attributes |= PropertyAttributes.Static; } + if (hiddenToken != null) { attributes |= PropertyAttributes.Hidden; @@ -4400,6 +4489,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) nameof(ParserStrings.MissingPropertyTerminator), ParserStrings.MissingPropertyTerminator); } + SkipNewlinesAndSemicolons(); // Include the semicolon in the extent but not newline or rcurly as that will look weird, e.g. if an error is reported on the full extent @@ -4450,10 +4540,12 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) { attributes |= MethodAttributes.Static; } + if (hiddenToken != null) { attributes |= MethodAttributes.Hidden; } + return new FunctionMemberAst(ExtentOf(startExtent, functionDefinition), functionDefinition, typeConstraint, attributeList, attributes); } @@ -4481,6 +4573,7 @@ private void RecordErrorAsts(Ast errAst, ref List astsOnError) { astsOnError = new List(); } + astsOnError.Add(errAst); } @@ -4495,6 +4588,7 @@ private void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError { astsOnError = new List(); } + astsOnError.AddRange(errAsts); } @@ -4512,6 +4606,7 @@ private Token NextTypeIdentifierToken() UngetToken(typeName); return null; } + return typeName; } finally @@ -4589,6 +4684,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, nestedAsts.Add(enumDefn); return new ErrorStatementAst(startExtent, nestedAsts); } + return enumDefn; } @@ -4655,6 +4751,7 @@ private MemberAst EnumMemberRule() ParserStrings.MissingPropertyTerminator); } } + SkipNewlinesAndSemicolons(); // Include the semicolon in the extent but not newline or rcurly as that will look weird, e.g. if an error is reported on the full extent @@ -4896,6 +4993,7 @@ private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressio { workingDirectory = Path.GetDirectoryName(scriptFileName); } + assemblyFileName = workingDirectory + @"\" + assemblyFileName; } @@ -5053,6 +5151,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class baseCallExtent = PositionUtilities.EmptyExtent; baseKeywordExtent = PositionUtilities.EmptyExtent; } + var invokeMemberAst = new BaseCtorInvokeMemberExpressionAst(baseKeywordExtent, baseCallExtent, baseCtorCallParams); baseCtorCallStatement = new CommandExpressionAst(invokeMemberAst.Extent, invokeMemberAst, null); } @@ -5199,8 +5298,10 @@ private List FunctionParameterDeclarationRule(out IScriptExtent en nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList), ParserStrings.MissingEndParenthesisInFunctionParameterList); } + SkipNewlines(); } + return parameters; } @@ -5284,6 +5385,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L nameof(ParserStrings.MissingTypeLiteralToken), ParserStrings.MissingTypeLiteralToken); } + break; } @@ -5304,6 +5406,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L { exceptionTypes = new List(); } + exceptionTypes.Add(typeConstraintAst); SkipNewlines(); @@ -5312,6 +5415,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L { break; } + SkipToken(); } while (true); @@ -5329,6 +5433,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L nameof(ParserStrings.MissingCatchHandlerBlock), ParserStrings.MissingCatchHandlerBlock); } + if (exceptionTypes != null) { if (errorAsts == null) @@ -5340,6 +5445,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L errorAsts.AddRange(exceptionTypes); } } + return null; } @@ -5479,6 +5585,7 @@ private StatementAst DataStatementRule(Token dataToken) nameof(ParserStrings.MissingValueForSupportedCommandInDataSectionStatement), ParserStrings.MissingValueForSupportedCommandInDataSectionStatement); } + endErrorStatement = commaToken != null ? commaToken.Extent : supportedCommandToken.Extent; break; } @@ -5617,6 +5724,7 @@ private PipelineBaseAst PipelineRule() { redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; } + IScriptExtent unused = null; lastRedirection = RedirectionRule(redirectionToken, redirections, ref unused); @@ -5638,6 +5746,7 @@ private PipelineBaseAst PipelineRule() { startExtent = commandAst.Extent; } + pipelineElements.Add(commandAst); } else if (pipelineElements.Count > 0 || PeekToken().Kind == TokenKind.Pipe) @@ -5678,6 +5787,7 @@ private PipelineBaseAst PipelineRule() nameof(ParserStrings.EmptyPipeElement), ParserStrings.EmptyPipeElement); } + break; case TokenKind.AndAnd: case TokenKind.OrOr: @@ -5692,6 +5802,7 @@ private PipelineBaseAst PipelineRule() { scanning = false; } + break; default: @@ -5807,6 +5918,7 @@ private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, Redire default: throw PSTraceSource.NewArgumentOutOfRangeException("result.FromStream", result.FromStream); } + ReportError(result.Extent, nameof(ParserStrings.StreamAlreadyRedirected), ParserStrings.StreamAlreadyRedirected, @@ -5932,6 +6044,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t foundVerbatimArgument = true; } } + break; default: @@ -5952,6 +6065,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t token.SetIsCommandArgument(); break; } + break; } @@ -5970,11 +6084,13 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t { break; } + commaToken = token; if (commandArgs == null) { commandArgs = new List(); } + commandArgs.Add(exprAst); SkipToken(); @@ -6104,6 +6220,7 @@ internal Ast CommandRule(bool forDynamicKeyword) elements.Add(commandName); break; } + var parameterToken = (ParameterToken)token; ExpressionAst parameterArgs; IScriptExtent extent; @@ -6144,6 +6261,7 @@ internal Ast CommandRule(bool forDynamicKeyword) { redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; } + RedirectionRule((RedirectionToken)token, redirections, ref endExtent); } else @@ -6155,6 +6273,7 @@ internal Ast CommandRule(bool forDynamicKeyword) endExtent = token.Extent; elements.Add(new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord)); } + break; default: @@ -6193,6 +6312,7 @@ internal Ast CommandRule(bool forDynamicKeyword) endExtent = ast.Extent; elements.Add(ast); } + break; } @@ -6220,6 +6340,7 @@ internal Ast CommandRule(bool forDynamicKeyword) ParserStrings.MissingExpression, firstToken.Text); } + return null; } @@ -6300,6 +6421,7 @@ private ExpressionAst ExpressionRule() { return ErrorRecoveryParameterInExpression(paramToken, expr); } + return expr; } @@ -6330,6 +6452,7 @@ private ExpressionAst ExpressionRule() token.Text); expr = new ErrorExpressionAst(extent); } + operandStack.Push(expr); token = NextToken(); @@ -6353,9 +6476,11 @@ private ExpressionAst ExpressionRule() break; precedence = operatorStack.Peek().Kind.GetBinaryPrecedence(); } + operatorStack.Push(token); precedence = newPrecedence; } + rhs = operandStack.Pop(); Diagnostics.Assert(operandStack.Count == operatorStack.Count, "Stacks out of sync"); while (operandStack.Count > 0) @@ -6430,6 +6555,7 @@ private ExpressionAst ArrayLiteralRule() arrayValues.Add(lastExpr); break; } + arrayValues.Add(lastExpr); commaToken = PeekToken(); @@ -6545,6 +6671,7 @@ private ExpressionAst UnaryExpressionRule() lastAttribute.TypeName.FullName); return new ErrorExpressionAst(ExtentOf(token, lastAttribute)); } + expr = new AttributedExpressionAst(ExtentOf(lastAttribute, child), lastAttribute, child); } else @@ -6681,6 +6808,7 @@ private ExpressionAst PrimaryExpressionRule(bool withMemberAccess) { return expr; } + return CheckPostPrimaryExpressionOperators(NextMemberAccessToken(true), expr); } @@ -6698,6 +6826,7 @@ private ExpressionAst CheckUsingVariable(VariableToken variableToken, bool withM return new UsingExpressionAst(childExpr.Extent, childExpr); } + return new VariableExpressionAst(variableToken); } @@ -6716,6 +6845,7 @@ private ExpressionAst CheckPostPrimaryExpressionOperators(Token token, Expressio { expr = ElementAccessRule(expr, token); } + token = NextMemberAccessToken(true); } @@ -6743,6 +6873,7 @@ private ExpressionAst HashExpressionRule(Token atCurlyToken, bool parsingSchemaE { break; } + keyValuePairs.Add(pair); Token token = PeekToken(); @@ -6977,6 +7108,7 @@ private ExpressionAst ParenthesizedExpressionRule(Token lParen) ParserStrings.ExpectedExpression); pipelineAst = new ErrorStatementAst(errorPosition); } + SkipNewlines(); rParen = NextToken(); if (rParen.Kind != TokenKind.RParen) @@ -7043,10 +7175,12 @@ private List ParseNestedExpressions(StringExpandableToken expanda _tokenizer.FinishNestedScan(ts); } } + nestedExpressions.Add(exprAst); } if (_savingTokens) { expandableStringToken.NestedTokens = new ReadOnlyCollection(newNestedTokens); } + return nestedExpressions; } @@ -7066,6 +7200,7 @@ private ExpressionAst ExpandableStringRule(StringExpandableToken strToken) { expr = new StringConstantExpressionAst(strToken); } + return expr; } @@ -7197,8 +7332,10 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx TokenKind.Comma.Text()); reportedError = true; } + break; } + arguments.Add(argument); SkipNewlines(); @@ -7210,6 +7347,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx break; } } + SkipNewlines(); rParen = NextToken(); if (rParen.Kind != TokenKind.RParen) @@ -7223,6 +7361,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx nameof(ParserStrings.MissingEndParenthesisInMethodCall), ParserStrings.MissingEndParenthesisInMethodCall); } + rParen = null; } } @@ -7230,6 +7369,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx { _disableCommaOperator = oldDisableCommaOperator; } + lastExtent = ExtentFromFirstOf(rParen, comma, arguments.LastOrDefault(), lParen); return arguments; } @@ -7267,6 +7407,7 @@ private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token l nameof(ParserStrings.MissingEndSquareBracket), ParserStrings.MissingEndSquareBracket); } + rBracket = null; } @@ -7348,6 +7489,7 @@ private static object[] arrayOfOneArg { get { return t_arrayOfOneArg ?? (t_arrayOfOneArg = new object[1]); } } + [ThreadStatic] private static object[] t_arrayOfOneArg; @@ -7355,6 +7497,7 @@ private static object[] arrayOfTwoArgs { get { return t_arrayOfTwoArgs ?? (t_arrayOfTwoArgs = new object[2]); } } + [ThreadStatic] private static object[] t_arrayOfTwoArgs; @@ -7493,6 +7636,7 @@ public override string ToString() #endregion Error related classes // Guid is {eba789d9-533b-58d4-cd1f-2e6520e3a9c2} + [EventSource(Name = "Microsoft-PowerShell-Parser")] internal class ParserEventSource : EventSource { @@ -7500,14 +7644,23 @@ internal class ParserEventSource : EventSource internal const int MaxScriptLengthToLog = 50; public void ParseStart(string FileName, int Length) { WriteEvent(1, FileName, Length); } + public void ParseStop() { WriteEvent(2); } + public void ResolveSymbolsStart() { WriteEvent(3); } + public void ResolveSymbolsStop() { WriteEvent(4); } + public void SemanticChecksStart() { WriteEvent(5); } + public void SemanticChecksStop() { WriteEvent(6); } + public void CheckSecurityStart(string FileName) { WriteEvent(7, FileName); } + public void CheckSecurityStop(string FileName) { WriteEvent(8, FileName); } + public void CompileStart(string FileName, int Length, bool Optimized) { WriteEvent(9, FileName, Length, Optimized); } + public void CompileStop() { WriteEvent(10); } internal static string GetFileOrScript(string fileName, string input) diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index c5e18b31322..079ba40e718 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -199,6 +199,7 @@ internal static string VerboseMessage(IScriptExtent position) { errorLength = maxLineLength - prefix; } + needsSuffixDots = true; } else @@ -216,6 +217,7 @@ internal static string VerboseMessage(IScriptExtent position) { suffix += Math.Min(totalSuffix, maxLineLength - candidateLength); } + needsSuffixDots = (suffix < totalSuffix); } @@ -259,6 +261,7 @@ internal static string BriefMessage(IScriptPosition position) { message.Insert(position.ColumnNumber - 1, " >>>> "); } + return StringUtil.Format(ParserStrings.TraceScriptLineMessage, position.LineNumber, message.ToString()); } @@ -268,10 +271,12 @@ internal static IScriptExtent NewScriptExtent(IScriptExtent start, IScriptExtent { return start; } + if (start == EmptyExtent) { return end; } + if (end == EmptyExtent) { return start; @@ -341,6 +346,7 @@ internal static bool ContainsLineAndColumn(this IScriptExtent extent, int line, if (extent.EndLineNumber != extent.StartLineNumber) return true; return (column < extent.EndColumnNumber); } + return false; } @@ -387,6 +393,7 @@ internal int LineFromOffset(int offset) { line = ~line - 1; } + return line + 1; } @@ -403,6 +410,7 @@ internal string Text(int line) int length = _lineStartMap[line] - start; return ScriptText.Substring(start, length); } + return ScriptText.Substring(start); } } @@ -418,9 +426,13 @@ internal InternalScriptPosition(PositionHelper _positionHelper, int offset) } public string File { get { return _positionHelper.File; } } + public int LineNumber { get { return _positionHelper.LineFromOffset(Offset); } } + public int ColumnNumber { get { return _positionHelper.ColumnFromOffset(Offset); } } + public string Line { get { return _positionHelper.Text(LineNumber); } } + public int Offset { get; } internal InternalScriptPosition CloneWithNewOffset(int offset) @@ -487,6 +499,7 @@ public string Text { return string.Empty; } + return PositionHelper.ScriptText.Substring(StartOffset, EndOffset - StartOffset); } } @@ -497,7 +510,9 @@ public override string ToString() } internal PositionHelper PositionHelper { get; } + public int StartOffset { get; } + public int EndOffset { get; } } @@ -508,24 +523,38 @@ public override string ToString() internal sealed class EmptyScriptPosition : IScriptPosition { public string File { get { return null; } } + public int LineNumber { get { return 0; } } + public int ColumnNumber { get { return 0; } } + public int Offset { get { return 0; } } + public string Line { get { return string.Empty; } } + public string GetFullScript() { return null; } } internal sealed class EmptyScriptExtent : IScriptExtent { public string File { get { return null; } } + public IScriptPosition StartScriptPosition { get { return PositionUtilities.EmptyPosition; } } + public IScriptPosition EndScriptPosition { get { return PositionUtilities.EmptyPosition; } } + public int StartLineNumber { get { return 0; } } + public int StartColumnNumber { get { return 0; } } + public int EndLineNumber { get { return 0; } } + public int EndColumnNumber { get { return 0; } } + public int StartOffset { get { return 0; } } + public int EndOffset { get { return 0; } } + public string Text { get { return string.Empty; } } public override bool Equals(object obj) @@ -721,6 +750,7 @@ public string Text return _startPosition.Line.Substring(_startPosition.ColumnNumber - 1, _endPosition.ColumnNumber - _startPosition.ColumnNumber); } + return string.Format(CultureInfo.InvariantCulture, "{0}...{1}", _startPosition.Line.Substring(_startPosition.ColumnNumber), _endPosition.Line.Substring(0, _endPosition.ColumnNumber)); diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 25239f547c7..09717e4c20e 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -41,6 +41,7 @@ internal AstVisitAction CheckForPostAction(Ast ast, AstVisitAction action) { postActionHandler.PostVisit(ast); } + return action; } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index f4636315ec7..5eaa37654a1 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -55,6 +55,7 @@ internal bool IsAstSafe(Ast ast) { return true; } + return false; } @@ -72,39 +73,73 @@ internal bool IsAstSafe(Ast ast) private readonly GetSafeValueVisitor.SafeValueContext _safeValueContext; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } + public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } + public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } + public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } + public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return false; } + public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return false; } + public object VisitAttribute(AttributeAst attributeAst) { return false; } + public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return false; } + public object VisitParameter(ParameterAst parameterAst) { return false; } + public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return false; } + public object VisitIfStatement(IfStatementAst ifStmtAst) { return false; } + public object VisitTrap(TrapStatementAst trapStatementAst) { return false; } + public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return false; } + public object VisitDataStatement(DataStatementAst dataStatementAst) { return false; } + public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return false; } + public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return false; } + public object VisitForStatement(ForStatementAst forStatementAst) { return false; } + public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return false; } + public object VisitCatchClause(CatchClauseAst catchClauseAst) { return false; } + public object VisitTryStatement(TryStatementAst tryStatementAst) { return false; } + public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return false; } + public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return false; } + public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return false; } + public object VisitExitStatement(ExitStatementAst exitStatementAst) { return false; } + public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return false; } + public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } + public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } + public object VisitCommand(CommandAst commandAst) { return false; } + public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return false; } + public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return false; } + public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return false; } + public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return false; } + public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return false; } + public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return false; } + public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return false; } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) @@ -124,6 +159,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa break; } } + return isSafe; } @@ -138,12 +174,14 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) isSafe = false; break; } + if (!(bool)statement.Accept(this)) { isSafe = false; break; } } + return isSafe; } @@ -170,6 +208,7 @@ public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { _visitCount++; } + return unaryExpressionIsSafe; } @@ -180,12 +219,14 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { return false; } + if (!type.IsSafePrimitive()) { // Only do conversions to built-in types - other conversions might not // be safe to optimize. return false; } + _visitCount++; return (bool)convertExpressionAst.Child.Accept(this); } @@ -271,6 +312,7 @@ public object VisitHashtable(HashtableAst hashtableAst) { return false; } + return hashtableAst.KeyValuePairs.All(pair => (bool)pair.Item1.Accept(this) && (bool)pair.Item2.Accept(this)); } @@ -316,45 +358,80 @@ public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueCo { return null; } + throw PSTraceSource.NewArgumentException("ast"); } private static ExecutionContext s_context; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitParamBlock(ParamBlockAst paramBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitNamedBlock(NamedBlockAst namedBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitAttribute(AttributeAst attributeAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitParameter(ParameterAst parameterAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitIfStatement(IfStatementAst ifStmtAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitTrap(TrapStatementAst trapStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitDataStatement(DataStatementAst dataStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitForStatement(ForStatementAst forStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitWhileStatement(WhileStatementAst whileStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitCatchClause(CatchClauseAst catchClauseAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitTryStatement(TryStatementAst tryStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitBreakStatement(BreakStatementAst breakStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitExitStatement(ExitStatementAst exitStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitCommand(CommandAst commandAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitCommandParameter(CommandParameterAst commandParameterAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitBlockStatement(BlockStatementAst blockStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } + public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } // @@ -373,8 +450,10 @@ private object GetSingleValueFromTarget(object target, object index) { return null; } + return offset >= 0 ? targetString[offset] : targetString[targetString.Length + offset]; } + var targetArray = target as object[]; if (targetArray != null) { @@ -384,8 +463,10 @@ private object GetSingleValueFromTarget(object target, object index) { return null; } + return offset >= 0 ? targetArray[offset] : targetArray[targetArray.Length + offset]; } + var targetHashtable = target as Hashtable; if (targetHashtable != null) { @@ -424,10 +505,12 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa { ofs = s_context.SessionState.PSVariable.GetValue("OFS") as string; } + if (ofs == null) { ofs = " "; } + for (int offset = 0; offset < safeValues.Length; offset++) { var result = expandableStringExpressionAst.NestedExpressions[offset].Accept(this); @@ -473,6 +556,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa subExpressionResult[subExpressionOffset] = resultArray[subExpressionOffset]; } } + safeValues[offset] = string.Join(ofs, subExpressionResult); } else @@ -510,6 +594,7 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) throw PSTraceSource.NewArgumentException("ast"); } } + return statementList.ToArray(); } @@ -520,6 +605,7 @@ public object VisitPipeline(PipelineAst pipelineAst) { return expr.Accept(this); } + throw PSTraceSource.NewArgumentException("ast"); } @@ -641,6 +727,7 @@ public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { arrayElements.Add(element.Accept(this)); } + return arrayElements.ToArray(); } @@ -653,6 +740,7 @@ public object VisitHashtable(HashtableAst hashtableAst) var value = pair.Item2.Accept(this); hashtable.Add(key, value); } + return hashtable; } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 8a12d3173a7..989cc856aba 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -94,6 +94,7 @@ private void CheckForDuplicateParameters(ReadOnlyCollection parame { parametersSet.Add(parameterName); } + var voidConstraint = parameter.Attributes.OfType().FirstOrDefault(t => typeof(void) == t.TypeName.GetReflectionType()); @@ -286,6 +287,7 @@ private static string GetValidNamedAttributeProperties(Type attributeType) propertyNames.Add(fieldInfo.Name); } } + return string.Join(", ", propertyNames); } @@ -315,6 +317,7 @@ public override AstVisitAction VisitParameter(ParameterAst parameterAst) nameof(ParserStrings.MultipleTypeConstraintsOnMethodParam), ParserStrings.MultipleTypeConstraintsOnMethodParam); } + isParamTypeDefined = true; } } @@ -351,6 +354,7 @@ internal static void CheckArrayTypeNameDepth(ITypeName typeName, IScriptExtent e ParserStrings.ScriptTooComplicated); break; } + if (type is ArrayTypeName) { type = ((ArrayTypeName)type).ElementType; @@ -374,6 +378,7 @@ public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinit break; } } + if (dscResourceAttributeAst != null) { DscResourceChecker.CheckType(_parser, typeDefinitionAst, dscResourceAttributeAst); @@ -584,6 +589,7 @@ private void CheckLabelExists(StatementAst ast, string label) ParserStrings.LabelNotFound, label); } + break; } @@ -678,6 +684,7 @@ private void CheckForReturnStatement(ReturnStatementAst ast) { return; } + if (ast.Pipeline != null) { if (functionMemberAst.IsReturnTypeVoid()) @@ -770,6 +777,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act ParserStrings.VoidTypeConstraintNotAllowed); } } + expr = ((AttributedExpressionAst)expr).Child; } @@ -801,16 +809,20 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act varPath.UnqualifiedPath, expectedType); } + break; } + specialIndex += 1; } } } + CheckAssignmentTarget(expr, simpleAssignment, reportError); } } } + if (errorAst != null) { reportError(errorAst); @@ -904,6 +916,7 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve nameof(ParserStrings.ReferenceNeedsToBeByItselfInTypeSequence), ParserStrings.ReferenceNeedsToBeByItselfInTypeSequence); } + child = childAttrExpr.Child; continue; } @@ -935,12 +948,15 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve skipError = statementAst.Left.Find(ast1 => ast1 == convertExpressionAst, searchNestedScriptBlocks: true) != null; break; } + if (ast is CommandExpressionAst) { break; } + ast = ast.Parent; } + if (!skipError) { _parser.ReportError(convertExpressionAst.Type.Extent, @@ -948,6 +964,7 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve ParserStrings.ReferenceNeedsToBeLastTypeInTypeConversion); } } + parent = parent.Child as AttributedExpressionAst; } } @@ -1000,6 +1017,7 @@ private ExpressionAst CheckUsingExpression(ExpressionAst exprAst) { return indexExpr.Index; } + return CheckUsingExpression(indexExpr.Target); } @@ -1179,6 +1197,7 @@ public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) { _memberScopeStack.Push(null); } + return AstVisitAction.Continue; } @@ -1242,13 +1261,16 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA } } } + break; } + statementAst = ast as PipelineAst; ancestorNodeLevel++; ast = ast.Parent; } } + return AstVisitAction.Continue; } @@ -1315,6 +1337,7 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem e.ToString()); } } + DynamicKeyword keyword = dynamicKeywordStatementAst.Keyword; HashtableAst hashtable = dynamicKeywordStatementAst.BodyExpression as HashtableAst; if (hashtable != null) @@ -1392,6 +1415,7 @@ public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMem propertyMemberAst.PropertyType.TypeName.FullName); } } + _memberScopeStack.Push(propertyMemberAst); return AstVisitAction.Continue; } @@ -1405,6 +1429,7 @@ public void PostVisit(Ast ast) { _memberScopeStack.Pop(); } + _scopeStack.Pop(); scriptBlockAst.PostParseChecksPerformed = true; // at this moment, we could use different parser for the initial syntax check @@ -1564,6 +1589,7 @@ private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeD CheckKey(parser, propertyMemberAst, ref hasKey); } } + if (baseTypeDefinitionAst.BaseTypes != null && (!hasSet || !hasGet || !hasTest || !hasKey)) { LookupRequiredMembers(parser, baseTypeDefinitionAst, ref hasSet, ref hasGet, ref hasTest, ref hasKey); @@ -1582,6 +1608,7 @@ private static void CheckGet(Parser parser, FunctionMemberAst functionMemberAst, { return; } + if (functionMemberAst.Name.Equals("Get", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0) { @@ -1684,12 +1711,14 @@ private static void CheckKey(Parser parser, PropertyMemberAst propertyMemberAst, } } } + if (!keyPropertyTypeAllowed) { parser.ReportError(propertyMemberAst.Extent, nameof(ParserStrings.DscResourceInvalidKeyProperty), ParserStrings.DscResourceInvalidKeyProperty); } + return; } } @@ -2066,6 +2095,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) ParserStrings.CmdletNotInAllowedListForDataSection, commandAst.Extent.Text); } + return AstVisitAction.Continue; } diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index bf69ec8f98f..05276084abf 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -176,6 +176,7 @@ internal void AddTypesInScope(Ast ast) // This way, we can support types that refer to each other, e.g. // class C1 { [C2]$x } // class C2 { [C1]$c1 } + var types = ast.FindAll(x => x is TypeDefinitionAst, searchNestedScriptBlocks: false); foreach (var type in types) { @@ -231,6 +232,7 @@ public TypeLookupResult LookupType(TypeName typeName) if (result != null) break; } + return result; } @@ -243,6 +245,7 @@ public Ast LookupVariable(VariablePath variablePath) if (result != null) break; } + return result; } @@ -353,6 +356,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun { _symbolTable.EnterScope(functionDefinitionAst.Body, ScopeType.Function); } + return AstVisitAction.Continue; } @@ -389,6 +393,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a break; } } + if (variableExpressionAst != null && variableExpressionAst.VariablePath.IsVariable) { var ast = _symbolTable.LookupVariable(variableExpressionAst.VariablePath); @@ -420,6 +425,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a } // TODO: static look for alias and function. } + return AstVisitAction.Continue; } @@ -611,6 +617,7 @@ private bool DispatchTypeName(ITypeName type, int genericArgumentCount, bool isA } } } + return false; } @@ -670,6 +677,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA errorId = nameof(ParserStrings.TypeNotFound); errorMsg = ParserStrings.TypeNotFound; } + _parser.ReportError(typeName.Extent, errorId, errorMsg, typeName.Name); } } @@ -731,6 +739,7 @@ public override object VisitFunctionDefinition(FunctionDefinitionAst functionDef { _symbolResolver._symbolTable.LeaveScope(); } + return null; } diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 3e0c9835cf3..95223bce4ed 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -544,6 +544,7 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) { name = nameValue.ToString(); } + if (name != null) { object value = null; @@ -1835,6 +1836,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List candidates) @@ -142,6 +143,7 @@ internal static bool IsPublic(Type type) { return true; } + if (!type.IsNestedPublic) { return false; @@ -154,6 +156,7 @@ internal static bool IsPublic(Type type) return false; } } + return true; } @@ -178,6 +181,7 @@ private static Type ResolveTypeNameWorker(TypeName typeName, { return result; } + currentScope = currentScope.Parent; } @@ -438,6 +442,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception { TypeCache.Add(typeName, typeResolutionState, result); } + return result; } @@ -600,6 +605,7 @@ internal string GetAlternateTypeName(string typeName) { alternateName = typeName + "Attribute"; } + return alternateName; } @@ -651,14 +657,17 @@ public override int GetHashCode() { result = Utils.CombineHashCodes(result, stringComparer.GetHashCode(namespaces[i])); } + for (int i = 0; i < assemblies.Length; i++) { result = Utils.CombineHashCodes(result, this.assemblies[i].GetHashCode()); } + foreach (var t in _typesDefined) { result = Utils.CombineHashCodes(result, t.GetHashCode()); } + return result; } } @@ -812,15 +821,18 @@ internal static bool Contains(Type inputType) { return true; } + if (inputType.IsEnum) { return true; } + if (inputType.IsGenericType) { var genericTypeDefinition = inputType.GetGenericTypeDefinition(); return genericTypeDefinition == typeof(Nullable<>) || genericTypeDefinition == typeof(FlagsExpression<>); } + return (inputType.IsArray && Contains(inputType.GetElementType())); } } @@ -897,6 +909,7 @@ internal static string FindBuiltinAccelerator(Type type, string expectedKey = nu return expectedKey; } } + return null; } /// @@ -925,6 +938,7 @@ public static bool Remove(string typeName) { s_allTypeAccelerators.Remove(typeName); } + return true; } @@ -959,6 +973,7 @@ internal static void FillCache(Dictionary cache) { cache.Add(val.Key, val.Value); } + foreach (KeyValuePair val in userTypeAccelerators) { cache.Add(val.Key, val.Value); diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index aaef8dd0a0c..4021d61f8f4 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -102,6 +102,7 @@ internal static Dictionary Visit(IParameterMeta { visitor.VisitParameters(ast.Parameters); } + localsAllocated = visitor._variables.Where(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed).Count(); return visitor._variables; } @@ -175,6 +176,7 @@ private void VisitParameters(ReadOnlyCollection parameters) // comparisons with $null and don't try to convert the $null value to the // valuetype because the parameter has no value yet. For example: // & { param([System.Reflection.MemberTypes]$m) ($null -eq $m) } + object unused; if (!Compiler.TryGetDefaultParameterValue(analysisDetails.Type, out unused)) { @@ -223,6 +225,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var // TODO: force just this variable to be dynamic, not all variables. _disableOptimizations = true; } + NoteVariable(VariableAnalysis.GetUnaliasedVariableName(varPath), VariableAnalysis.Unanalyzed, null); } @@ -239,6 +242,7 @@ public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpr { usingExpressionAst.RuntimeUsingIndex = _runtimeUsingIndex; } + Diagnostics.Assert(usingExpressionAst.RuntimeUsingIndex == _runtimeUsingIndex, "Logic error in visiting using expressions."); _runtimeUsingIndex += 1; @@ -333,8 +337,11 @@ internal LoopGotoTargets(string label, Block breakTarget, Block continueTarget) this.BreakTarget = breakTarget; this.ContinueTarget = continueTarget; } + internal string Label { get; private set; } + internal Block BreakTarget { get; private set; } + internal Block ContinueTarget { get; private set; } } @@ -379,6 +386,7 @@ internal void FlowsTo(Block next) { next._unreachable = false; } + _successors.Add(next); next._predecessors.Add(this); } @@ -451,6 +459,7 @@ internal override object Accept(ICustomAstVisitor visitor) Diagnostics.Assert(false, "This code is unreachable."); return null; } + internal override AstVisitAction InternalVisit(AstVisitor visitor) { Diagnostics.Assert(false, "This code is unreachable."); @@ -665,6 +674,7 @@ private Tuple> FinishAnalysis(bool scriptCmdlet = bitArray.And((BitArray)pred._visitData); } } + Diagnostics.Assert(predCount != 0, "If we didn't and anything, there is a flaw in the logic and incorrect code may be generated."); AnalyzeBlock(bitArray, block); @@ -790,6 +800,7 @@ private void AnalyzeBlock(BitArray assignedBitArray, Block block) : VariableAnalysis.ForceDynamic; } } + continue; } @@ -804,6 +815,7 @@ private void AnalyzeBlock(BitArray assignedBitArray, Block block) { CheckLHSAssignVar(assignmentTarget._variableName, assignedBitArray, assignmentTarget._type); } + continue; } @@ -932,10 +944,12 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { scriptBlockAst.BeginBlock.Accept(this); } + if (scriptBlockAst.ProcessBlock != null) { scriptBlockAst.ProcessBlock.Accept(this); } + if (scriptBlockAst.EndBlock != null) { scriptBlockAst.EndBlock.Accept(this); @@ -1119,6 +1133,7 @@ public object VisitDataStatement(DataStatementAst dataStatementAst) { _currentBlock.AddAst(dataStatementAst); } + return null; } @@ -1166,6 +1181,7 @@ private void GenerateWhileLoop(string loopLabel, var breakBlock = new Block(); // Condition can be null from an uncommon for loop: for() {} + if (generateCondition != null) { generateCondition(); @@ -1424,6 +1440,7 @@ private Block ControlFlowStatement(PipelineBaseAst pipelineAst) { pipelineAst.Accept(this); } + _currentBlock.FlowsTo(_exitBlock); var lastBlockInStatement = _currentBlock; @@ -1497,6 +1514,7 @@ public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatemen { anyAttributes = true; } + leftAst = ((AttributedExpressionAst)leftAst).Child; } @@ -1531,6 +1549,7 @@ public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatemen assignTarget.Accept(this); } } + return null; } @@ -1544,6 +1563,7 @@ public object VisitPipeline(PipelineAst pipelineAst) { invokesCommand = true; } + foreach (var redir in command.Redirections) { redir.Accept(this); @@ -1578,6 +1598,7 @@ public object VisitCommand(CommandAst commandAst) { element.Accept(this); } + return null; } @@ -1593,6 +1614,7 @@ public object VisitCommandParameter(CommandParameterAst commandParameterAst) { commandParameterAst.Argument.Accept(this); } + return null; } @@ -1728,6 +1750,7 @@ public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMember arg.Accept(this); } } + return null; } @@ -1743,6 +1766,7 @@ public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { element.Accept(this); } + return null; } @@ -1753,6 +1777,7 @@ public object VisitHashtable(HashtableAst hashtableAst) pair.Item1.Accept(this); pair.Item2.Accept(this); } + return null; } @@ -1776,6 +1801,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa { expr.Accept(this); } + return null; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index fecf1fa56ae..892f4b12dfb 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -59,6 +59,7 @@ internal interface IParameterMetadataProvider bool UsesCmdletBinding(); ReadOnlyCollection Parameters { get; } + ScriptBlockAst Body { get; } #region Remoting/Invoke Command @@ -218,11 +219,13 @@ public object SafeGetValue() internal static T[] CopyElements(ReadOnlyCollection elements) where T : Ast { if (elements == null || elements.Count == 0) { return null; } + var result = new T[elements.Count]; for (int i = 0; i < result.Count(); i++) { result[i] = (T)elements[i].Copy(); } + return result; } @@ -235,6 +238,7 @@ internal static T[] CopyElements(ReadOnlyCollection elements) where T : As internal static T CopyElement(T element) where T : Ast { if (element == null) { return null; } + return (T)element.Copy(); } @@ -269,6 +273,7 @@ internal void SetParent(Ast child) { throw new InvalidOperationException(ParserStrings.AstIsReused); } + Diagnostics.Assert(child.Parent == null, "Parent can only be set once"); child.Parent = this; } @@ -345,6 +350,7 @@ internal static HashtableAst GetAncestorHashtableAst(Ast ast, out Ast lastChildO lastChildOfHashtable = ast; ast = ast.Parent; } + return hashtableAst; } @@ -385,6 +391,7 @@ internal static T GetAncestorAst(Ast ast) where T : Ast break; parent = parent.Parent; } + return targetAst; } @@ -612,6 +619,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } @@ -757,6 +765,7 @@ public class ScriptBlockAst : Ast, IParameterMetadataProvider internal bool HadErrors { get; set; } internal bool IsConfiguration { get; private set; } + internal bool PostParseChecksPerformed { get; set; } /// @@ -801,21 +810,25 @@ public ScriptBlockAst(IScriptExtent extent, this.ParamBlock = paramBlock; SetParent(paramBlock); } + if (beginBlock != null) { this.BeginBlock = beginBlock; SetParent(beginBlock); } + if (processBlock != null) { this.ProcessBlock = processBlock; SetParent(processBlock); } + if (endBlock != null) { this.EndBlock = endBlock; SetParent(endBlock); } + if (dynamicParamBlock != null) { this.DynamicParamBlock = dynamicParamBlock; @@ -1014,6 +1027,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using this.ParamBlock = paramBlock; SetParent(paramBlock); } + if (isFilter) { this.ProcessBlock = new NamedBlockAst(statements.Extent, TokenKind.Process, statements, true); @@ -1097,6 +1111,7 @@ public CommentHelpInfo GetHelpContent() { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } + return null; } @@ -1176,6 +1191,7 @@ internal string ToStringForSerialization() "There is an incorrect assumption about the extent."); result = result.Substring(1, result.Length - 2); } + return result; } @@ -1275,6 +1291,7 @@ internal void PerformPostParseChecks(Parser parser) ParserEventSource.Log.ResolveSymbolsStop(); ParserEventSource.Log.SemanticChecksStart(); } + SemanticChecks.CheckAst(parser, this); if (etwEnabled) ParserEventSource.Log.SemanticChecksStop(); @@ -1321,6 +1338,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } } + if (action == AstVisitAction.Continue && ParamBlock != null) action = ParamBlock.InternalVisit(visitor); if (action == AstVisitAction.Continue && DynamicParamBlock != null) @@ -1349,6 +1367,7 @@ RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadat { return Compiler.GetParameterMetaData(ParamBlock.Parameters, automaticPositions, ref usesCmdletBinding); } + return new RuntimeDefinedParameterDictionary { Data = RuntimeDefinedParameterDictionary.EmptyParameterArray }; } @@ -1502,6 +1521,7 @@ private string GetWithInputHandlingForInvokeCommandImpl(Tuple parameters) break; } } + return usesCmdletBinding; } } @@ -1747,6 +1770,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs var stmt = statements[index]; stmt.ClearParent(); } + SetParents(statements); var traps = statementBlock.Traps; @@ -1758,6 +1782,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs var trap = traps[index]; trap.ClearParent(); } + SetParents(traps); } @@ -1825,6 +1850,7 @@ public override Ast Copy() // Used by the debugger for command breakpoints internal IScriptExtent OpenCurlyExtent { get; private set; } + internal IScriptExtent CloseCurlyExtent { get; private set; } #region Visitors @@ -2055,6 +2081,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue) { for (int index = 0; index < NamedArguments.Count; index++) @@ -2064,6 +2091,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } @@ -2174,6 +2202,7 @@ public ParameterAst(IScriptExtent extent, { this.Attributes = s_emptyAttributeList; } + this.Name = name; SetParent(name); if (defaultValue != null) @@ -2212,6 +2241,7 @@ public Type StaticType { type = typeConstraint.TypeName.GetReflectionType(); } + return type ?? typeof(object); } } @@ -2310,14 +2340,17 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue) { action = Name.InternalVisit(visitor); } + if (action == AstVisitAction.Continue && DefaultValue != null) { action = DefaultValue.InternalVisit(visitor); } + return visitor.CheckForPostAction(this, action); } @@ -2419,6 +2452,7 @@ internal static AstVisitAction InternalVisit(AstVisitor visitor, if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue && statements != null) { for (int index = 0; index < statements.Count; index++) @@ -2428,6 +2462,7 @@ internal static AstVisitAction InternalVisit(AstVisitor visitor, if (action != AstVisitAction.Continue) break; } } + return action; } @@ -2581,6 +2616,7 @@ internal Type Type { return _type; } + set { // The assert may seem a little bit confusing. @@ -3007,6 +3043,7 @@ public PropertyMemberAst(IScriptExtent extent, string name, TypeConstraintAst pr { this.Attributes = s_emptyAttributeList; } + PropertyAttributes = propertyAttributes; InitialValue = initialValue; @@ -3280,6 +3317,7 @@ internal override string GetTooltip() { sb.Append("static "); } + sb.Append(IsReturnTypeVoid() ? "void" : ReturnType.TypeName.FullName); sb.Append(' '); sb.Append(Name); @@ -3290,8 +3328,10 @@ internal override string GetTooltip() { sb.Append(", "); } + sb.Append(Parameters[i].GetTooltip()); } + sb.Append(')'); return sb.ToString(); } @@ -3436,6 +3476,7 @@ public override string Name } internal TypeDefinitionAst DefiningType { get; private set; } + internal SpecialMemberFunctionType Type { get; private set; } internal override string GetTooltip() @@ -3486,6 +3527,7 @@ public bool UsesCmdletBinding() } public ReadOnlyCollection Parameters { get { return null; } } + public ScriptBlockAst Body { get; private set; } public PowerShell GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, @@ -3562,6 +3604,7 @@ public FunctionDefinitionAst(IScriptExtent extent, this.Parameters = new ReadOnlyCollection(parameters.ToArray()); SetParents(Parameters); } + this.Body = body; SetParent(body); } @@ -3626,6 +3669,7 @@ public CommentHelpInfo GetHelpContent() { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } + return null; } @@ -3651,6 +3695,7 @@ public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenC { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } + return null; } @@ -3699,6 +3744,7 @@ internal string GetParamTextFromParameterList(Tuple, : param.ToString()); separator = ", "; } + sb.Append(")"); sb.Append(Environment.NewLine); @@ -3728,9 +3774,11 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue) action = Body.InternalVisit(visitor); } + return visitor.CheckForPostAction(this, action); } @@ -3749,10 +3797,12 @@ RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadat { return Compiler.GetParameterMetaData(Parameters, automaticPositions, ref usesCmdletBinding); } + if (Body.ParamBlock != null) { return Compiler.GetParameterMetaData(Body.ParamBlock.Parameters, automaticPositions, ref usesCmdletBinding); } + return new RuntimeDefinedParameterDictionary { Data = RuntimeDefinedParameterDictionary.EmptyParameterArray }; } @@ -3810,6 +3860,7 @@ bool IParameterMetadataProvider.UsesCmdletBinding() { usesCmdletBinding = ((IParameterMetadataProvider)Body).UsesCmdletBinding(); } + return usesCmdletBinding; } @@ -3907,10 +3958,12 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue && ElseClause != null) { action = ElseClause.InternalVisit(visitor); } + return visitor.CheckForPostAction(this, action); } @@ -3961,6 +4014,7 @@ public DataStatementAst(IScriptExtent extent, { this.CommandsAllowed = new ReadOnlyCollection(s_emptyCommandsAllowed); } + this.Body = body; SetParent(body); } @@ -4273,6 +4327,7 @@ public ForStatementAst(IScriptExtent extent, this.Initializer = initializer; SetParent(initializer); } + if (iterator != null) { this.Iterator = iterator; @@ -4662,6 +4717,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue && Default != null) action = Default.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); @@ -4758,6 +4814,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; action = catchType.InternalVisit(visitor); } + if (action == AstVisitAction.Continue) action = Body.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); @@ -4877,6 +4934,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue && Finally != null) action = Finally.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); @@ -4914,6 +4972,7 @@ public TrapStatementAst(IScriptExtent extent, TypeConstraintAst trapType, Statem this.TrapType = trapType; SetParent(trapType); } + this.Body = body; SetParent(body); } @@ -5246,8 +5305,10 @@ public bool IsRethrow { return true; } + parent = parent.Parent; } + return false; } } @@ -5453,6 +5514,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } @@ -5524,6 +5586,7 @@ public CommandParameterAst(IScriptExtent extent, string parameterName, Expressio this.Argument = argument; SetParent(argument); } + this.ErrorPosition = errorPosition; } @@ -5570,6 +5633,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { action = Argument.InternalVisit(visitor); } + return visitor.CheckForPostAction(this, action); } @@ -5724,6 +5788,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + if (action == AstVisitAction.Continue) { for (int index = 0; index < Redirections.Count; index++) @@ -5735,6 +5800,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } } + return visitor.CheckForPostAction(this, action); } @@ -5809,6 +5875,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } } + return visitor.CheckForPostAction(this, action); } @@ -6103,6 +6170,7 @@ public IEnumerable GetAssignmentTargets() { yield return element; } + yield break; } @@ -6172,14 +6240,17 @@ public ConfigurationDefinitionAst(IScriptExtent extent, { throw PSTraceSource.NewArgumentNullException("extent"); } + if (body == null) { throw PSTraceSource.NewArgumentNullException("body"); } + if (instanceName == null) { throw PSTraceSource.NewArgumentNullException("instanceName"); } + this.Body = body; SetParent(body); this.ConfigurationType = type; @@ -6239,14 +6310,17 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); } + if (action == AstVisitAction.Continue) { action = InstanceName.InternalVisit(visitor); } + if (action == AstVisitAction.Continue) { Body.InternalVisit(visitor); } + return visitor.CheckForPostAction(this, action); } @@ -6294,6 +6368,7 @@ internal PipelineAst GenerateSetItemPipelineAst() // $IsMetaConfig = $false # the configuration to generated is a meta configuration // ) // } + var cea = new Collection { new StringConstantExpressionAst(this.Extent, @@ -6360,6 +6435,7 @@ internal PipelineAst GenerateSetItemPipelineAst() { paramAsts.AddRange(Body.ScriptBlock.ParamBlock.Parameters.Select(parameterAst => (ParameterAst)parameterAst.Copy())); } + var paramBlockAst = new ParamBlockAst(this.Extent, attribAsts, paramAsts); var cmdAst = new CommandAst(this.Extent, cea, TokenKind.Unknown, null); @@ -6489,6 +6565,7 @@ private static bool IsImportCommand(StatementAst stmt, List(moduleVersionEvaluated); // Use -ModuleVersion only in the case, if -ModuleName specified. @@ -6545,9 +6622,11 @@ private static IEnumerable ConfigurationBuildInParameters } } } + return s_configurationBuildInParameters; } } + private static List s_configurationBuildInParameters; private static IEnumerable ConfigurationBuildInParameterAttribAsts { @@ -6578,9 +6657,11 @@ private static IEnumerable ConfigurationBuildInParameterAttribAsts } } } + return s_configurationBuildInParameterAttrAsts; } } + private static List s_configurationBuildInParameterAttrAsts; private static IEnumerable ConfigurationExtraParameterStatements @@ -6608,9 +6689,11 @@ private static IEnumerable ConfigurationExtraParameterStatements } } } + return s_configurationExtraParameterStatements; } } + private static List s_configurationExtraParameterStatements; #endregion @@ -6638,6 +6721,7 @@ public DynamicKeywordStatementAst(IScriptExtent extent, { throw PSTraceSource.NewArgumentException("commandElements"); } + this.CommandElements = new ReadOnlyCollection(commandElements.ToArray()); SetParents(CommandElements); } @@ -6702,6 +6786,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) break; } } + return visitor.CheckForPostAction(this, action); } @@ -6715,11 +6800,13 @@ internal DynamicKeyword Keyword { return _keyword; } + set { _keyword = value.Copy(); } } + private DynamicKeyword _keyword; internal Token LCurly { get; set; } internal Token FunctionName { get; set; } @@ -7102,6 +7189,7 @@ public override Type StaticType case TokenKind.Is: return typeof(bool); } + return typeof(object); } } @@ -7383,6 +7471,7 @@ private List GetAttributes() attributes.Add(childAttributeAst.Attribute); childAttributeAst = childAttributeAst.Child as AttributedExpressionAst; } + attributes.Reverse(); return attributes; } @@ -7493,6 +7582,7 @@ IAssignableValue ISupportsAssignment.GetAssignableValue() // the child as the assignable value. return varExpr; } + return this; } @@ -7670,6 +7760,7 @@ internal AstVisitAction InternalVisitChildren(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return action; } @@ -7851,6 +7942,7 @@ public TypeName(IScriptExtent extent, string name, string assembly) { throw PSTraceSource.NewArgumentNullException("assembly"); } + AssemblyName = assembly; } @@ -7894,8 +7986,10 @@ internal bool HasDefaultCtor() // we are pessimistic about default ctor presence. return false; } + return reflectionType.HasDefaultCtor(); } + bool hasExplicitCtor = false; foreach (var member in _typeDefinitionAst.Members) { @@ -7944,9 +8038,11 @@ public Type GetReflectionType() Diagnostics.Assert(_typeDefinitionAst != null, "_typeDefinitionAst can never be null"); return type; } + Interlocked.CompareExchange(ref _type, type, null); } } + return _type; } @@ -7970,6 +8066,7 @@ public Type GetReflectionAttributeType() result = null; } } + return result; } @@ -8037,12 +8134,14 @@ internal bool IsType(Type type) { return fullTypeName.Substring(lastDotIndex + 1).Equals(Name, StringComparison.OrdinalIgnoreCase); } + return false; } Type ISupportsTypeCaching.CachedType { get { return _type; } + set { _type = value; } } } @@ -8078,6 +8177,7 @@ public GenericTypeName(IScriptExtent extent, ITypeName genericTypeName, IEnumera { throw PSTraceSource.NewArgumentNullException(extent == null ? "extent" : "genericTypeName"); } + if (genericArguments == null) { throw PSTraceSource.NewArgumentException("genericArguments"); @@ -8113,9 +8213,11 @@ public string FullName { sb.Append(','); } + first = false; sb.Append(typename.FullName); } + sb.Append(']'); var assemblyName = TypeName.AssemblyName; if (assemblyName != null) @@ -8123,8 +8225,10 @@ public string FullName sb.Append(','); sb.Append(assemblyName); } + Interlocked.CompareExchange(ref _cachedFullName, sb.ToString(), null); } + return _cachedFullName; } } @@ -8147,9 +8251,11 @@ public string Name { sb.Append(','); } + first = false; sb.Append(typename.Name); } + sb.Append(']'); return sb.ToString(); } @@ -8223,6 +8329,7 @@ public Type GetReflectionType() { return type; } + Interlocked.CompareExchange(ref _cachedType, type, null); } catch (Exception) @@ -8231,6 +8338,7 @@ public Type GetReflectionType() } } } + return _cachedType; } @@ -8284,6 +8392,7 @@ public Type GetReflectionAttributeType() Interlocked.CompareExchange(ref _cachedType, type, null); } } + return type; } @@ -8327,12 +8436,14 @@ public override int GetHashCode() { hash = Utils.CombineHashCodes(hash, GenericArguments[i].GetHashCode()); } + return hash; } Type ISupportsTypeCaching.CachedType { get { return _cachedType; } + set { _cachedType = value; } } } @@ -8387,6 +8498,7 @@ private string GetName(bool includeAssemblyName) { sb.Append(',', Rank - 1); } + sb.Append(']'); if (includeAssemblyName) { @@ -8417,6 +8529,7 @@ public string FullName { Interlocked.CompareExchange(ref _cachedFullName, GetName(includeAssemblyName: true), null); } + return _cachedFullName; } } @@ -8488,6 +8601,7 @@ public Type GetReflectionType() { return type; } + Interlocked.CompareExchange(ref _cachedType, type, null); } } @@ -8535,6 +8649,7 @@ public override int GetHashCode() Type ISupportsTypeCaching.CachedType { get { return _cachedType; } + set { _cachedType = value; } } } @@ -8635,6 +8750,7 @@ public override int GetHashCode() Type ISupportsTypeCaching.CachedType { get { return _type; } + set { throw new InvalidOperationException(); } } } @@ -8751,6 +8867,7 @@ public VariableExpressionAst(IScriptExtent extent, VariablePath variablePath, bo { throw PSTraceSource.NewArgumentNullException("variablePath"); } + this.VariablePath = variablePath; this.Splatted = splatted; } @@ -8784,6 +8901,7 @@ public bool IsConstantVariable() return true; } } + return false; } @@ -8881,6 +8999,7 @@ Expression IAssignableValue.SetValue(Compiler compiler, Expression rhs) { rhs = DynamicExpression.Dynamic(PSVariableAssignmentBinder.Get(), typeof(object), rhs); } + rhs = rhs.Convert(targetType); if (!localInTuple) @@ -9094,6 +9213,7 @@ internal static StringConstantType MapTokenKindToStringConstantKind(Token token) case TokenKind.Generic: return StringConstantType.BareWord; } + throw PSTraceSource.NewInvalidOperationException(); } @@ -9170,6 +9290,7 @@ public ExpandableStringExpressionAst(IScriptExtent extent, { this.NestedExpressions[i].ClearParent(); } + SetParents(this.NestedExpressions); this.Value = value; @@ -9261,6 +9382,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } @@ -9404,6 +9526,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } @@ -9503,6 +9626,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action != AstVisitAction.Continue) break; } } + return visitor.CheckForPostAction(this, action); } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index d99353eb201..def6b8d0dc1 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1403,6 +1403,7 @@ internal static void ToDebugString(ReadOnlyCollection nestedTokens, public ReadOnlyCollection NestedTokens { get { return _nestedTokens; } + internal set { _nestedTokens = value; } } @@ -1417,6 +1418,7 @@ internal override string ToDebugString(int indent) { ToDebugString(_nestedTokens, sb, indent); } + return sb.ToString(); } } diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 94e7aee9781..9c837612d06 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -96,6 +96,7 @@ private static Stack> DynamicKeywordsStack (t_dynamicKeywordsStack = new Stack>()); } } + [ThreadStatic] private static Stack> t_dynamicKeywordsStack; @@ -193,6 +194,7 @@ public static void RemoveKeyword(string name) PSArgumentNullException e = PSTraceSource.NewArgumentNullException("name"); throw e; } + DynamicKeyword.DynamicKeywords.Remove(name); } @@ -247,10 +249,12 @@ public DynamicKeyword Copy() { keyword.Properties.Add(entry.Key, entry.Value); } + foreach (KeyValuePair entry in this.Parameters) { keyword.Parameters.Add(entry.Key, entry.Value); } + return keyword; } @@ -320,6 +324,7 @@ public Dictionary Properties (_properties = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } + private Dictionary _properties; /// @@ -333,6 +338,7 @@ public Dictionary Parameters (_parameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } + private Dictionary _parameters; /// @@ -361,6 +367,7 @@ internal static bool IsMetaDSCResource(this DynamicKeyword keyword) { return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase); } + return false; } @@ -394,6 +401,7 @@ internal static IEnumerable GetAllowedKeywords(this DynamicKeywo else return allowedKeywords; } + return null; } } @@ -420,6 +428,7 @@ public List Attributes { get { return _attributes ?? (_attributes = new List()); } } + private List _attributes; /// @@ -429,6 +438,7 @@ public List Values { get { return _values ?? (_values = new List()); } } + private List _values; /// @@ -438,6 +448,7 @@ public Dictionary ValueMap { get { return _valueMap ?? (_valueMap = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } + private Dictionary _valueMap; /// @@ -688,12 +699,17 @@ internal Tokenizer(Parser parser) internal bool InWorkflowContext { get; set; } internal List TokenList { get; set; } internal Token FirstToken { get; private set; } + internal Token LastToken { get; private set; } + private List RequiresTokens { get; set; } private bool InCommandMode() { return Mode == TokenizerMode.Command; } + private bool InExpressionMode() { return Mode == TokenizerMode.Expression; } + private bool InTypeNameMode() { return Mode == TokenizerMode.TypeName; } + private bool InSignatureMode() { return Mode == TokenizerMode.Signature; } internal void Initialize(string fileName, string input, List tokenList) @@ -717,13 +733,16 @@ internal void Initialize(string fileName, string input, List tokenList) { i += 1; } + lineStartMap.Add(i + 1); } + if (c == '\n') { lineStartMap.Add(i + 1); } } + _currentIndex = 0; Mode = TokenizerMode.Command; @@ -779,6 +798,7 @@ private char GetChar() { return '\0'; } + return _script[current]; } @@ -797,6 +817,7 @@ private char PeekChar() { return '\0'; } + return _script[_currentIndex]; } @@ -818,10 +839,12 @@ internal static bool IsKeyword(string str) { return true; } + if (DynamicKeyword.ContainsKeyword(str) && !DynamicKeyword.IsHiddenKeyword(str)) { return true; } + return false; } @@ -852,6 +875,7 @@ internal void SkipNewlines(bool skipSemis, bool v3) ScanNewline(c); NewToken(TokenKind.NewLine); } + goto again; case ';': @@ -862,8 +886,10 @@ internal void SkipNewlines(bool skipSemis, bool v3) _tokenStart = _currentIndex - 1; NewToken(TokenKind.Semi); } + goto again; } + break; case '#': @@ -879,6 +905,7 @@ internal void SkipNewlines(bool skipSemis, bool v3) ScanBlockComment(); goto again; } + break; case '`': @@ -890,11 +917,13 @@ internal void SkipNewlines(bool skipSemis, bool v3) NewToken(TokenKind.LineContinuation); goto again; } + if (char.IsWhiteSpace(c1)) { SkipWhiteSpace(); goto again; } + UngetChar(); break; @@ -904,8 +933,10 @@ internal void SkipNewlines(bool skipSemis, bool v3) SkipWhiteSpace(); goto again; } + break; } + UngetChar(); } @@ -918,6 +949,7 @@ private void SkipWhiteSpace() { break; } + SkipChar(); } } @@ -949,6 +981,7 @@ internal void Resync(int start) } } } + _currentIndex = start - adjustment; if (_currentIndex > _script.Length + 1) { @@ -985,6 +1018,7 @@ internal void RemoveTokensFromListDuringResync(List tokenList, int start) { i -= 1; } + for (; i >= 0; i--) { if (((InternalScriptExtent)tokenList[i].Extent).EndOffset <= start) @@ -1009,6 +1043,7 @@ internal void ReplaceSavedTokens(Token firstOldToken, Token lastOldToken, Token lastTokenToReplace = i; continue; } + if (((InternalScriptExtent)TokenList[i].Extent).StartOffset == startOffset) { TokenList.RemoveRange(i, lastTokenToReplace - i + 1); @@ -1089,6 +1124,7 @@ internal InternalScriptExtent CurrentExtent() end += 1; } } + for (; i < end && i < _skippedCharOffsets.Length; ++i) { if (_skippedCharOffsets[i]) @@ -1097,6 +1133,7 @@ internal InternalScriptExtent CurrentExtent() } } } + return new InternalScriptExtent(_positionHelper, start, end); } @@ -1132,9 +1169,11 @@ private T SaveToken(T token) where T : Token { FirstToken = token; } + LastToken = token; break; } + return token; } @@ -1204,6 +1243,7 @@ private Token NewFileRedirectionToken(int from, bool append, bool fromSpecifiedE { UngetChar(); } + return NewNumberToken(from); } @@ -1250,6 +1290,7 @@ private bool OnlyWhitespaceOrCommentsAfterExtent(InternalScriptExtent extent) return false; } } + return true; } @@ -1360,6 +1401,7 @@ private char ScanUnicodeEscape(out char surrogateCharacter) nameof(ParserStrings.MissingUnicodeEscapeSequenceTerminator), ParserStrings.MissingUnicodeEscapeSequenceTerminator); } + return s_invalidChar; } else if (i == s_maxNumberOfUnicodeHexDigits) @@ -1492,6 +1534,7 @@ private void ScanToEndOfCommentLine(out bool sawBeginSig, out bool matchedRequir { goto case '\n'; } + goto default; case '\r': case '\n': @@ -1612,6 +1655,7 @@ private void ScanBlockComment() SkipChar(); break; } + if (c == '\r' || c == '\n') { ScanNewline(c); @@ -1735,6 +1779,7 @@ internal ScriptRequirements GetScriptRequirements() { requiredSnapins = new List(); } + break; } } @@ -1755,6 +1800,7 @@ internal ScriptRequirements GetScriptRequirements() DiscoveryExceptions.ScriptRequiresInvalidFormat); } } + if (snapinName != null) { Diagnostics.Assert(PSSnapInInfo.IsPSSnapinIdValid(snapinName), "we shouldn't set snapinName if it wasn't valid"); @@ -1816,6 +1862,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, ParserStrings.ParameterCannotHaveArgument, parameter.ParameterName); } + return; } @@ -1848,6 +1895,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, shellIDToken); return; } + if (!(argumentValue is string)) { ReportError(argumentAst.Extent, @@ -1856,6 +1904,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, shellIDToken); return; } + requiredShellId = (string)argumentValue; } else if (PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) @@ -1868,6 +1917,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, PSSnapinToken); return; } + if (snapinName != null) { ReportError(parameter.Extent, @@ -1877,6 +1927,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, PSSnapinToken); return; } + if (!PSSnapInInfo.IsPSSnapinIdValid((string)argumentValue)) { ReportError(argumentAst.Extent, @@ -1934,6 +1985,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, versionToken); return; } + snapinVersion = version; } else @@ -1947,6 +1999,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, versionToken); return; } + requiredVersion = version; } } @@ -1990,6 +2043,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, e.Message); return; } + if (requiredModules == null) requiredModules = new List(); requiredModules.Add(moduleSpecification); @@ -2022,6 +2076,7 @@ private List HandleRequiresAssemblyArgument(Ast argumentAst, object arg, requiredAssemblies.Add((string)arg); } } + return requiredAssemblies; } @@ -2060,6 +2115,7 @@ private List HandleRequiresPSEditionArgument(Ast argumentAst, object arg editionToken); } } + return requiredEditions; } #endregion Requires @@ -2120,8 +2176,10 @@ private TokenFlags ScanStringLiteral(StringBuilder sb) { break; } + c = GetChar(); } + sb.Append(c); c = GetChar(); } @@ -2173,6 +2231,7 @@ private Token ScanSubExpression(bool hereString) { scanning = false; } + break; case '`': @@ -2191,6 +2250,7 @@ private Token ScanSubExpression(bool hereString) { sb.Append(c); } + break; case '\0': @@ -2274,6 +2334,7 @@ private TokenFlags ScanStringExpandable(StringBuilder sb, StringBuilder formatSb } } } + if (c == '{' || c == '}') { // In the format string, we need to double up the curlies because we're @@ -2281,6 +2342,7 @@ private TokenFlags ScanStringExpandable(StringBuilder sb, StringBuilder formatSb // format expression for string.Format. formatSb.Append(c); } + sb.Append(c); formatSb.Append(c); } @@ -2404,6 +2466,7 @@ private bool ScanAfterHereStringHeader(string header) SkipChar(); break; } + if (c == '\r' || c == '\n' || (c == '\0' && AtEof())) { UngetChar(); @@ -2452,6 +2515,7 @@ private bool ScanPossibleHereStringFooter(Func test, Action ap // to give a helpful error message. falseFooterOffset = _currentIndex - 1; } + appendChar(GetChar()); // append the '@' } else @@ -2460,6 +2524,7 @@ private bool ScanPossibleHereStringFooter(Func test, Action ap // handle the character. UngetChar(); } + return false; } @@ -2523,6 +2588,7 @@ private Token ScanHereStringLiteral() ParserStrings.TerminatorExpectedAtEndOfString, "'@"); } + flags = TokenFlags.TokenInError; break; } @@ -2569,6 +2635,7 @@ private Token ScanHereStringExpandable() sb.Append('\n'); formatSb.Append('\n'); } + if (ScanPossibleHereStringFooter(CharExtensions.IsDoubleQuote, appendChar, ref falseFooterOffset)) { // Remove the last newline appended. @@ -2576,6 +2643,7 @@ private Token ScanHereStringExpandable() formatSb.Length = formatLength; break; } + continue; } @@ -2602,6 +2670,7 @@ private Token ScanHereStringExpandable() } } } + if (c == '{' || c == '}') { // In the format string, we need to double up the curlies because we're @@ -2609,6 +2678,7 @@ private Token ScanHereStringExpandable() // format expression for string.Format. formatSb.Append(c); } + if (c != '\0' || !AtEof()) { sb.Append(c); @@ -2630,6 +2700,7 @@ private Token ScanHereStringExpandable() ParserStrings.TerminatorExpectedAtEndOfString, "\"@"); } + flags = TokenFlags.TokenInError; break; } @@ -2673,12 +2744,14 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) UngetChar(); goto end_braced_variable_scan; } + c = Backtick(c1, out char surrogateCharacter); if (surrogateCharacter != s_invalidChar) { sb.Append(c).Append(surrogateCharacter); continue; } + break; } case '"': @@ -2693,6 +2766,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) UngetChar(); goto end_braced_variable_scan; } + if (c1.IsDoubleQuote()) { c = c1; @@ -2702,6 +2776,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) UngetChar(); } } + break; case '{': ReportError(_currentIndex, @@ -2714,6 +2789,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) UngetChar(); goto end_braced_variable_scan; } + break; } @@ -2729,6 +2805,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) nameof(ParserStrings.IncompleteDollarVariableReference), ParserStrings.IncompleteDollarVariableReference); } + if (name.Length == 0) { if (c == '}') @@ -2737,6 +2814,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) nameof(ParserStrings.EmptyVariableReference), ParserStrings.EmptyVariableReference); } + name = ":Error:"; } @@ -2763,6 +2841,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) //{ // return NewToken(TokenKind.Unknown); //} + ReportError(NewScriptExtent(_tokenStart, _currentIndex), nameof(ParserStrings.InvalidBracedVariableReference), ParserStrings.InvalidBracedVariableReference); @@ -2868,6 +2947,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) { sb.Append(c); } + break; case '\0': @@ -2911,6 +2991,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) UngetChar(); scanning = false; } + break; } } @@ -2937,6 +3018,7 @@ private Token ScanVariable(bool splatted, bool inStringExpandable) errorId = nameof(ParserStrings.InvalidVariableReference); errorMsg = ParserStrings.InvalidVariableReference; } + ReportError(NewScriptExtent(_tokenStart, _currentIndex), errorId, errorMsg); } @@ -2988,6 +3070,7 @@ private Token ScanParameter() { UngetChar(); } + break; case 'a': @@ -3061,6 +3144,7 @@ private Token ScanParameter() sb.Insert(0, _script[_tokenStart]); // Insert the '-' that we skipped. return ScanGenericToken(sb); } + UngetChar(); scanning = false; break; @@ -3075,6 +3159,7 @@ private Token ScanParameter() UngetChar(); scanning = false; } + break; } } @@ -3104,6 +3189,7 @@ private Token CheckOperatorInCommandMode(char c, TokenKind tokenKind) { return ScanGenericToken(c); } + return NewToken(tokenKind); } @@ -3116,6 +3202,7 @@ private Token CheckOperatorInCommandMode(char c1, char c2, TokenKind tokenKind) sb.Append(c2); return ScanGenericToken(sb); } + return NewToken(tokenKind); } @@ -3134,6 +3221,7 @@ private Token ScanGenericToken(char firstChar, char surrogateCharacter) { sb.Append(surrogateCharacter); } + return ScanGenericToken(sb); } @@ -3194,6 +3282,7 @@ private Token ScanGenericToken(StringBuilder sb) { formatSb.Append(sb[i]); } + continue; } else if (c.IsDoubleQuote()) @@ -3208,6 +3297,7 @@ private Token ScanGenericToken(StringBuilder sb) continue; } } + sb.Append(c); formatSb.Append(c); if (c == '{' || c == '}') @@ -3215,6 +3305,7 @@ private Token ScanGenericToken(StringBuilder sb) formatSb.Append(c); } } + UngetChar(); var str = GetStringAndRelease(sb); @@ -3222,12 +3313,14 @@ private Token ScanGenericToken(StringBuilder sb) { return NewGenericExpandableToken(str, GetStringAndRelease(formatSb), nestedTokens); } + Release(formatSb); if (DynamicKeyword.ContainsKeyword(str) && !DynamicKeyword.IsHiddenKeyword(str)) { return NewToken(TokenKind.DynamicKeyword); } + return NewGenericToken(str); } @@ -3271,6 +3364,7 @@ private void ScanExponent(StringBuilder sb, ref int signIndex, ref bool notNumbe signIndex = sb.Length; sb.Append(c); } + if (ScanDecimalDigits(sb) == 0) { notNumber = true; @@ -3807,11 +3901,14 @@ internal Token GetMemberAccessOperator(bool allowLBracket) UngetChar(); return null; } + return NewToken(TokenKind.Dot); } + UngetChar(); return null; } + if (c == ':') { _tokenStart = _currentIndex; @@ -3827,11 +3924,14 @@ internal Token GetMemberAccessOperator(bool allowLBracket) UngetChar(); return null; } + return NewToken(TokenKind.ColonColon); } + UngetChar(); return null; } + if (c == '[' && allowLBracket) { _tokenStart = _currentIndex; @@ -3852,12 +3952,14 @@ internal Token GetInvokeMemberOpenParen() SkipChar(); return NewToken(TokenKind.LParen); } + if (c == '{') { _tokenStart = _currentIndex; SkipChar(); return NewToken(TokenKind.LCurly); } + return null; } @@ -3903,6 +4005,7 @@ internal Token GetLBracket() ScanBlockComment(); goto again; } + UngetChar(); break; @@ -3924,6 +4027,7 @@ internal Token GetLBracket() { UngetChar(); } + break; default: @@ -3933,6 +4037,7 @@ internal Token GetLBracket() SkipWhiteSpace(); goto again; } + UngetChar(); break; } @@ -3952,8 +4057,10 @@ private Token ScanDot() UngetChar(); // Unget the second dot, let ScanGenericToken consume it. return ScanGenericToken('.'); } + return NewToken(TokenKind.DotDot); } + if (c.IsDecimalDigit()) { return ScanNumber('.'); @@ -4019,6 +4126,7 @@ private Token ScanIdentifier(char firstChar) if (tokenKind != TokenKind.InlineScript || InWorkflowContext) return NewToken(tokenKind); } + if (DynamicKeyword.ContainsKeyword(ident) && !DynamicKeyword.IsHiddenKeyword(ident)) { return NewToken(TokenKind.DynamicKeyword); @@ -4052,6 +4160,7 @@ private Token ScanTypeName() { continue; } + break; } @@ -4079,6 +4188,7 @@ private void ScanAssemblyNameSpecToken(StringBuilder sb) UngetChar(); break; } + sb.Append(c); } @@ -4156,6 +4266,7 @@ private Token ScanLabel() UngetChar(); return NewGenericToken(GetStringAndRelease(sb)); } + UngetChar(); return ScanGenericToken(sb); } @@ -4217,18 +4328,22 @@ internal Token NextToken() { return NewToken(TokenKind.AtCurly); } + if (c1 == '(') { return NewToken(TokenKind.AtParen); } + if (c1.IsSingleQuote()) { return ScanHereStringLiteral(); } + if (c1.IsDoubleQuote()) { return ScanHereStringExpandable(); } + UngetChar(); if (c1.IsVariableStart()) { @@ -4257,11 +4372,13 @@ internal Token NextToken() NewToken(TokenKind.LineContinuation); goto again; } + if (char.IsWhiteSpace(c1)) { SkipWhiteSpace(); goto again; } + if (c1 == '\0' && AtEof()) { ReportIncompleteInput(_currentIndex, @@ -4286,15 +4403,18 @@ internal Token NextToken() SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.PlusPlus); } + if (c1 == '=') { SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.PlusEquals); } + if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) { return ScanNumber(c); } + return CheckOperatorInCommandMode(c, TokenKind.Plus); case '-': @@ -4307,19 +4427,23 @@ internal Token NextToken() SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.MinusMinus); } + if (c1 == '=') { SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.MinusEquals); } + if (char.IsLetter(c1) || c1 == '_' || c1 == '?') { return ScanParameter(); } + if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) { return ScanNumber(c); } + return CheckOperatorInCommandMode(c, TokenKind.Minus); case '*': @@ -4329,6 +4453,7 @@ internal Token NextToken() SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.MultiplyEquals); } + if (c1 == '>') { SkipChar(); @@ -4338,6 +4463,7 @@ internal Token NextToken() SkipChar(); return NewFileRedirectionToken(0, append: true, fromSpecifiedExplicitly: false); } + if (c1 == '&') { SkipChar(); @@ -4347,6 +4473,7 @@ internal Token NextToken() SkipChar(); return NewMergingRedirectionToken(0, 1); } + UngetChar(); } @@ -4362,6 +4489,7 @@ internal Token NextToken() SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.DivideEquals); } + return CheckOperatorInCommandMode(c, TokenKind.Divide); case '%': @@ -4371,6 +4499,7 @@ internal Token NextToken() SkipChar(); return CheckOperatorInCommandMode(c, c1, TokenKind.RemainderEquals); } + return CheckOperatorInCommandMode(c, TokenKind.Rem); case '$': @@ -4379,6 +4508,7 @@ internal Token NextToken() SkipChar(); return NewToken(TokenKind.DollarParen); } + return ScanVariable(false, false); case '<': @@ -4388,6 +4518,7 @@ internal Token NextToken() ScanBlockComment(); goto again; } + return NewInputRedirectionToken(); case '>': @@ -4396,6 +4527,7 @@ internal Token NextToken() SkipChar(); return NewFileRedirectionToken(1, append: true, fromSpecifiedExplicitly: false); } + return NewFileRedirectionToken(1, append: false, fromSpecifiedExplicitly: false); case 'a': @@ -4462,6 +4594,7 @@ internal Token NextToken() { return ScanGenericToken('['); } + return NewToken(TokenKind.LBracket); case ']': return NewToken(TokenKind.RBracket); @@ -4497,6 +4630,7 @@ internal Token NextToken() SkipChar(); return NewFileRedirectionToken(c - '0', append: true, fromSpecifiedExplicitly: true); } + if (c1 == '&') { SkipChar(); @@ -4506,11 +4640,13 @@ internal Token NextToken() SkipChar(); return NewMergingRedirectionToken(c - '0', c1 - '0'); } + UngetChar(); } return NewFileRedirectionToken(c - '0', append: false, fromSpecifiedExplicitly: true); } + return ScanNumber(c); case '&': @@ -4519,6 +4655,7 @@ internal Token NextToken() SkipChar(); return NewToken(TokenKind.AndAnd); } + return NewToken(TokenKind.Ampersand); case '|': @@ -4527,6 +4664,7 @@ internal Token NextToken() SkipChar(); return NewToken(TokenKind.OrOr); } + return NewToken(TokenKind.Pipe); case '!': @@ -4564,12 +4702,15 @@ internal Token NextToken() sb.Append("::"); return ScanGenericToken(sb); } + return NewToken(TokenKind.ColonColon); } + if (InCommandMode()) { return ScanLabel(); } + return this.NewToken(TokenKind.Colon); case '\0': @@ -4577,6 +4718,7 @@ internal Token NextToken() { return SaveToken(new Token(NewScriptExtent(_tokenStart + 1, _tokenStart + 1), TokenKind.EndOfInput, TokenFlags.None)); } + return ScanGenericToken(c); default: @@ -4590,6 +4732,7 @@ internal Token NextToken() { return ScanIdentifier(c); } + return ScanGenericToken(c); } } From 6a091e4789ea77202bda6ec262a263f7b83f614a Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:10 -0800 Subject: [PATCH 67/81] Update runtime --- .../engine/runtime/CompiledScriptBlock.cs | 45 +++ .../engine/runtime/MutableTuple.cs | 278 ++++++++++++++++++ .../engine/runtime/ScriptBlockToPowerShell.cs | 7 + 3 files changed, 330 insertions(+) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 98cfdd837fa..644302a2481 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -116,8 +116,10 @@ private void InitializeMetadata() DebuggerStepThrough = true; } } + _usesCmdletBinding = cmdletBindingAttribute != null; } + bool automaticPosition = cmdletBindingAttribute == null || cmdletBindingAttribute.PositionalBinding; var runtimeDefinedParameterDictionary = Ast.GetParameterMetadata(automaticPosition, ref _usesCmdletBinding); @@ -270,6 +272,7 @@ bool IsScriptBlockInFactASafeHashtable() // We delay parsing scripts loaded on startup, so we save the text. private string _scriptText; internal IParameterMetadataProvider Ast { get { return _ast ?? DelayParseScriptText(); } } + private IParameterMetadataProvider _ast; private IParameterMetadataProvider DelayParseScriptText() @@ -317,8 +320,10 @@ private IParameterMetadataProvider DelayParseScriptText() internal bool DebuggerHidden { get; set; } internal bool DebuggerStepThrough { get; set; } internal Guid Id { get; private set; } + internal bool HasLogged { get; set; } internal bool IsFilter { get; private set; } + internal bool IsProductCode { get @@ -327,6 +332,7 @@ internal bool IsProductCode { _isProductCode = SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File); } + return _isProductCode.Value; } } @@ -347,6 +353,7 @@ internal bool HasSuspiciousContent Diagnostics.Assert(_compiledOptimized || _compiledUnoptimized, "HasSuspiciousContent is not set correctly before being compiled"); return _hasSuspiciousContent; } + set { _hasSuspiciousContent = value; } } @@ -384,6 +391,7 @@ internal RuntimeDefinedParameterDictionary RuntimeDefinedParameters { InitializeMetadata(); } + return _runtimeDefinedParameterDictionary; } } @@ -432,6 +440,7 @@ internal ExperimentalAttribute ExperimentalAttribute return _expAttribute; } } + private ExperimentalAttribute _expAttribute = ExperimentalAttribute.None; public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlock) @@ -447,6 +456,7 @@ public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlo } } } + return _parameterMetadata; } @@ -537,6 +547,7 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file "A cached scriptblock should not have it's session state bound, that causes a memory leak."); return scriptBlock.Clone(); } + return null; } @@ -579,6 +590,7 @@ internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, { s_cachedScripts.Clear(); } + var key = Tuple.Create(fileName, fileContents); s_cachedScripts.TryAdd(key, scriptBlock); } @@ -715,10 +727,12 @@ private PipelineAst GetSimplePipeline(Func errorHandler) { return errorHandler(AutomationExceptions.CantConvertEmptyPipeline); } + if (statements.Count > 1) { return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline); } + if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Any()) { return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap); @@ -779,6 +793,7 @@ internal bool HasDynamicParameters public bool DebuggerHidden { get { return _scriptBlockData.DebuggerHidden; } + set { _scriptBlockData.DebuggerHidden = value; } } @@ -793,6 +808,7 @@ public Guid Id internal bool DebuggerStepThrough { get { return _scriptBlockData.DebuggerStepThrough; } + set { _scriptBlockData.DebuggerStepThrough = value; } } @@ -804,6 +820,7 @@ internal RuntimeDefinedParameterDictionary RuntimeDefinedParameters internal bool HasLogged { get { return _scriptBlockData.HasLogged; } + set { _scriptBlockData.HasLogged = value; } } @@ -966,14 +983,17 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, { locals.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnder, context); } + if (input != AutomationNull.Value) { locals.SetAutomaticVariable(AutomaticVariable.Input, input, context); } + if (scriptThis != AutomationNull.Value) { locals.SetAutomaticVariable(AutomaticVariable.This, scriptThis, context); } + SetPSScriptRootAndPSCommandPath(locals, context); var oldShellFunctionErrorOutputPipe = context.ShellFunctionErrorOutputPipe; @@ -1043,6 +1063,7 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, e.SetErrorId("EmptyFunctionNameInFunctionDefinitionDictionary"); throw e; } + if (def.Value == null) { PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( @@ -1051,6 +1072,7 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, e.SetErrorId("NullFunctionBodyInFunctionDefinitionDictionary"); throw e; } + newScope.FunctionTable.Add(def.Key, new FunctionInfo(def.Key, def.Value, context)); } } @@ -1069,6 +1091,7 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, e.SetErrorId("NullEntryInVariablesDefinitionList"); throw e; } + string name = psvar.Name; Diagnostics.Assert(!(string.Equals(name, "this") || string.Equals(name, "_") || string.Equals(name, "input")), "The list of variables to set in the scriptblock's scope cannot contain 'this', '_' or 'input'. These variables should be removed before passing the collection to this routine."); @@ -1191,6 +1214,7 @@ internal MutableTuple MakeLocalsTuple(bool createLocalScope) : Compiler.DottedLocalsNameIndexMap, _scriptBlockData.UnoptimizedLocalsMutableTupleCreator); } + return locals; } @@ -1222,6 +1246,7 @@ internal static object[] BindArgumentsForScriptblockInvoke( // We pass in a null SessionStateInternal because the current scope is already set correctly. valueToBind = ((Compiler.DefaultValueExpressionWrapper)valueToBind).GetValue(context, null); } + wasDefaulted = true; } else @@ -1293,6 +1318,7 @@ private Action GetCodeToInvoke(ref bool optimized, ScriptBlockC return HasProcessBlock ? _scriptBlockData.ProcessBlock : _scriptBlockData.EndBlock; } } + switch (clauseToInvoke) { case ScriptBlockClauseToInvoke.Begin: @@ -1864,6 +1890,7 @@ char ToLower(char c) { c = (char) (c | 0x20); } + return c; } @@ -1919,21 +1946,31 @@ internal static void LogScriptBlockEnd(ScriptBlock scriptBlock, Guid runspaceId) /// Returns the AST corresponding to the script block. /// public Ast Ast { get { return (Ast)_scriptBlockData.Ast; } } + internal IParameterMetadataProvider AstInternal { get { return _scriptBlockData.Ast; } } internal IScriptExtent[] SequencePoints { get { return _scriptBlockData.SequencePoints; } } internal Action DynamicParamBlock { get { return _scriptBlockData.DynamicParamBlock; } } + internal Action UnoptimizedDynamicParamBlock { get { return _scriptBlockData.UnoptimizedDynamicParamBlock; } } + internal Action BeginBlock { get { return _scriptBlockData.BeginBlock; } } + internal Action UnoptimizedBeginBlock { get { return _scriptBlockData.UnoptimizedBeginBlock; } } + internal Action ProcessBlock { get { return _scriptBlockData.ProcessBlock; } } + internal Action UnoptimizedProcessBlock { get { return _scriptBlockData.UnoptimizedProcessBlock; } } + internal Action EndBlock { get { return _scriptBlockData.EndBlock; } } + internal Action UnoptimizedEndBlock { get { return _scriptBlockData.UnoptimizedEndBlock; } } internal bool HasBeginBlock { get { return AstInternal.Body.BeginBlock != null; } } + internal bool HasProcessBlock { get { return AstInternal.Body.ProcessBlock != null; } } + internal bool HasEndBlock { get { return AstInternal.Body.EndBlock != null; } } } @@ -2046,6 +2083,7 @@ internal override void DoProcessRecord() dollarUnder = CurrentPipelineObject; _input.Add(dollarUnder); } + if (_scriptBlock.HasProcessBlock) { RunClause(_runOptimized ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, dollarUnder, _input); @@ -2175,6 +2213,7 @@ public object GetDynamicParameters() throw PSTraceSource.NewInvalidOperationException(AutomationExceptions.DynamicParametersWrongType, PSObject.ToStringParser(this.Context, resultList)); } + return resultList.Count == 0 ? null : PSObject.Base(resultList[0]); } @@ -2220,27 +2259,33 @@ private void SetPreferenceVariables() _localsTuple.SetPreferenceVariable(PreferenceVariable.Debug, _commandRuntime.Debug ? ActionPreference.Continue : ActionPreference.SilentlyContinue); } + if (_commandRuntime.IsVerboseFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Verbose, _commandRuntime.Verbose ? ActionPreference.Continue : ActionPreference.SilentlyContinue); } + if (_commandRuntime.IsErrorActionSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Error, _commandRuntime.ErrorAction); } + if (_commandRuntime.IsWarningActionSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Warning, _commandRuntime.WarningPreference); } + if (_commandRuntime.IsInformationActionSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Information, _commandRuntime.InformationPreference); } + if (_commandRuntime.IsWhatIfFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.WhatIf, _commandRuntime.WhatIf); } + if (_commandRuntime.IsConfirmFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Confirm, diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index f0e5c240b94..a1ee8e9d8bb 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -52,6 +52,7 @@ internal bool IsValueSet(int index) { nestedTuple = (MutableTuple)nestedTuple.GetValueImpl(accessPath[i]); } + return nestedTuple._valuesSet[accessPath[length-1]]; } @@ -61,12 +62,15 @@ internal void SetAutomaticVariable(AutomaticVariable auto, object value, Executi { context.Debugger.CheckVariableWrite(SpecialVariables.AutomaticVariables[(int)auto]); } + SetValue((int)auto, value); } + internal object GetAutomaticVariable(AutomaticVariable auto) { return GetValue((int)auto); } + internal void SetPreferenceVariable(PreferenceVariable pref, object value) { SetValue((int)pref, value); @@ -81,6 +85,7 @@ internal bool TryGetLocalVariable(string name, bool fromNewOrSet, out PSVariable result = new LocalVariable(name, this, index); return true; } + result = null; return false; } @@ -94,6 +99,7 @@ internal bool TrySetParameter(string name, object value) SetValue(index, value); return true; } + return false; } @@ -106,6 +112,7 @@ internal PSVariable TrySetVariable(string name, object value) SetValue(index, value); return new LocalVariable(name, this, index); } + return null; } @@ -165,8 +172,10 @@ private void SetNestedValue(int size, int index, object value) { res = (MutableTuple)res.GetValueImpl(lastAccess); } + lastAccess = i; } + res.SetValueImpl(lastAccess, value); } } @@ -190,6 +199,7 @@ private object GetNestedValue(int size, int index) { res = ((MutableTuple)res).GetValueImpl(i); } + return res; } } @@ -282,6 +292,7 @@ public static int GetSize(Type tupleType) { types.Push(subtype); } + continue; } @@ -423,6 +434,7 @@ private static MutableTuple MakeTuple(Func creator, Type tupleType { size = (size + MutableTuple.MaxSize - 1) / MutableTuple.MaxSize; } + for (int i = 0; i < size; i++) { PropertyInfo pi = tupleType.GetProperty("Item" + String.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); @@ -450,6 +462,7 @@ private static Type MakeTupleType(Type[] types, int start, int end) { typeArr[index++] = typeof(DynamicNull); } + return type.MakeGenericType(typeArr); } @@ -469,6 +482,7 @@ private static Type MakeTupleType(Type[] types, int start, int end) int newEnd = System.Math.Min(end, start + ((i + 1) * multiplier)); nestedTypes[i] = MakeTupleType(types, newStart, newEnd); } + for (int i = size; i < nestedTypes.Length; i++) { nestedTypes[i] = typeof(DynamicNull); @@ -516,6 +530,7 @@ internal static Expression CreateNew(Type tupleType, int start, int end, Express size = (size + MutableTuple.MaxSize - 1) / MutableTuple.MaxSize; multiplier *= MutableTuple.MaxSize; } + newValues = new Expression[PowerOfTwoRound(size)]; for (int i = 0; i < size; i++) { @@ -571,6 +586,7 @@ public MutableTuple(T0 item0) public T0 Item000 { get { return _item0; } + set { _item0 = value; _valuesSet[0] = true; } } @@ -591,6 +607,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -599,6 +616,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -615,6 +633,7 @@ public MutableTuple(T0 item0, T1 item1) public T1 Item001 { get { return _item1; } + set { _item1 = value; _valuesSet[1] = true; } } @@ -637,6 +656,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -645,6 +665,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -663,11 +684,14 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3) public T2 Item002 { get { return _item2; } + set { _item2 = value; _valuesSet[2] = true; } } + public T3 Item003 { get { return _item3; } + set { _item3 = value; _valuesSet[3] = true; } } @@ -694,6 +718,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -702,6 +727,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -724,21 +750,28 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, public T4 Item004 { get { return _item4; } + set { _item4 = value; _valuesSet[4] = true; } } + public T5 Item005 { get { return _item5; } + set { _item5 = value; _valuesSet[5] = true; } } + public T6 Item006 { get { return _item6; } + set { _item6 = value; _valuesSet[6] = true; } } + public T7 Item007 { get { return _item7; } + set { _item7 = value; _valuesSet[7] = true; } } @@ -773,6 +806,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -781,6 +815,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -811,41 +846,56 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, public T8 Item008 { get { return _item8; } + set { _item8 = value; _valuesSet[8] = true; } } + public T9 Item009 { get { return _item9; } + set { _item9 = value; _valuesSet[9] = true; } } + public T10 Item010 { get { return _item10; } + set { _item10 = value; _valuesSet[10] = true; } } + public T11 Item011 { get { return _item11; } + set { _item11 = value; _valuesSet[11] = true; } } + public T12 Item012 { get { return _item12; } + set { _item12 = value; _valuesSet[12] = true; } } + public T13 Item013 { get { return _item13; } + set { _item13 = value; _valuesSet[13] = true; } } + public T14 Item014 { get { return _item14; } + set { _item14 = value; _valuesSet[14] = true; } } + public T15 Item015 { get { return _item15; } + set { _item15 = value; _valuesSet[15] = true; } } @@ -896,6 +946,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -904,6 +955,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -950,81 +1002,112 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, public T16 Item016 { get { return _item16; } + set { _item16 = value; _valuesSet[16] = true; } } + public T17 Item017 { get { return _item17; } + set { _item17 = value; _valuesSet[17] = true; } } + public T18 Item018 { get { return _item18; } + set { _item18 = value; _valuesSet[18] = true; } } + public T19 Item019 { get { return _item19; } + set { _item19 = value; _valuesSet[19] = true; } } + public T20 Item020 { get { return _item20; } + set { _item20 = value; _valuesSet[20] = true; } } + public T21 Item021 { get { return _item21; } + set { _item21 = value; _valuesSet[21] = true; } } + public T22 Item022 { get { return _item22; } + set { _item22 = value; _valuesSet[22] = true; } } + public T23 Item023 { get { return _item23; } + set { _item23 = value; _valuesSet[23] = true; } } + public T24 Item024 { get { return _item24; } + set { _item24 = value; _valuesSet[24] = true; } } + public T25 Item025 { get { return _item25; } + set { _item25 = value; _valuesSet[25] = true; } } + public T26 Item026 { get { return _item26; } + set { _item26 = value; _valuesSet[26] = true; } } + public T27 Item027 { get { return _item27; } + set { _item27 = value; _valuesSet[27] = true; } } + public T28 Item028 { get { return _item28; } + set { _item28 = value; _valuesSet[28] = true; } } + public T29 Item029 { get { return _item29; } + set { _item29 = value; _valuesSet[29] = true; } } + public T30 Item030 { get { return _item30; } + set { _item30 = value; _valuesSet[30] = true; } } + public T31 Item031 { get { return _item31; } + set { _item31 = value; _valuesSet[31] = true; } } @@ -1107,6 +1190,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -1115,6 +1199,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -1193,161 +1278,224 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, public T32 Item032 { get { return _item32; } + set { _item32 = value; _valuesSet[32] = true; } } + public T33 Item033 { get { return _item33; } + set { _item33 = value; _valuesSet[33] = true; } } + public T34 Item034 { get { return _item34; } + set { _item34 = value; _valuesSet[34] = true; } } + public T35 Item035 { get { return _item35; } + set { _item35 = value; _valuesSet[35] = true; } } + public T36 Item036 { get { return _item36; } + set { _item36 = value; _valuesSet[36] = true; } } + public T37 Item037 { get { return _item37; } + set { _item37 = value; _valuesSet[37] = true; } } + public T38 Item038 { get { return _item38; } + set { _item38 = value; _valuesSet[38] = true; } } + public T39 Item039 { get { return _item39; } + set { _item39 = value; _valuesSet[39] = true; } } + public T40 Item040 { get { return _item40; } + set { _item40 = value; _valuesSet[40] = true; } } + public T41 Item041 { get { return _item41; } + set { _item41 = value; _valuesSet[41] = true; } } + public T42 Item042 { get { return _item42; } + set { _item42 = value; _valuesSet[42] = true; } } + public T43 Item043 { get { return _item43; } + set { _item43 = value; _valuesSet[43] = true; } } + public T44 Item044 { get { return _item44; } + set { _item44 = value; _valuesSet[44] = true; } } + public T45 Item045 { get { return _item45; } + set { _item45 = value; _valuesSet[45] = true; } } + public T46 Item046 { get { return _item46; } + set { _item46 = value; _valuesSet[46] = true; } } + public T47 Item047 { get { return _item47; } + set { _item47 = value; _valuesSet[47] = true; } } + public T48 Item048 { get { return _item48; } + set { _item48 = value; _valuesSet[48] = true; } } + public T49 Item049 { get { return _item49; } + set { _item49 = value; _valuesSet[49] = true; } } + public T50 Item050 { get { return _item50; } + set { _item50 = value; _valuesSet[50] = true; } } + public T51 Item051 { get { return _item51; } + set { _item51 = value; _valuesSet[51] = true; } } + public T52 Item052 { get { return _item52; } + set { _item52 = value; _valuesSet[52] = true; } } + public T53 Item053 { get { return _item53; } + set { _item53 = value; _valuesSet[53] = true; } } + public T54 Item054 { get { return _item54; } + set { _item54 = value; _valuesSet[54] = true; } } + public T55 Item055 { get { return _item55; } + set { _item55 = value; _valuesSet[55] = true; } } + public T56 Item056 { get { return _item56; } + set { _item56 = value; _valuesSet[56] = true; } } + public T57 Item057 { get { return _item57; } + set { _item57 = value; _valuesSet[57] = true; } } + public T58 Item058 { get { return _item58; } + set { _item58 = value; _valuesSet[58] = true; } } + public T59 Item059 { get { return _item59; } + set { _item59 = value; _valuesSet[59] = true; } } + public T60 Item060 { get { return _item60; } + set { _item60 = value; _valuesSet[60] = true; } } + public T61 Item061 { get { return _item61; } + set { _item61 = value; _valuesSet[61] = true; } } + public T62 Item062 { get { return _item62; } + set { _item62 = value; _valuesSet[62] = true; } } + public T63 Item063 { get { return _item63; } + set { _item63 = value; _valuesSet[63] = true; } } @@ -1494,6 +1642,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get @@ -1502,6 +1651,7 @@ public override int Capacity } } } + [GeneratedCode("DLR", "2.0")] internal class MutableTuple : MutableTuple { @@ -1644,321 +1794,448 @@ public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, public T64 Item064 { get { return _item64; } + set { _item64 = value; _valuesSet[64] = true; } } + public T65 Item065 { get { return _item65; } + set { _item65 = value; _valuesSet[65] = true; } } + public T66 Item066 { get { return _item66; } + set { _item66 = value; _valuesSet[66] = true; } } + public T67 Item067 { get { return _item67; } + set { _item67 = value; _valuesSet[67] = true; } } + public T68 Item068 { get { return _item68; } + set { _item68 = value; _valuesSet[68] = true; } } + public T69 Item069 { get { return _item69; } + set { _item69 = value; _valuesSet[69] = true; } } + public T70 Item070 { get { return _item70; } + set { _item70 = value; _valuesSet[70] = true; } } + public T71 Item071 { get { return _item71; } + set { _item71 = value; _valuesSet[71] = true; } } + public T72 Item072 { get { return _item72; } + set { _item72 = value; _valuesSet[72] = true; } } + public T73 Item073 { get { return _item73; } + set { _item73 = value; _valuesSet[73] = true; } } + public T74 Item074 { get { return _item74; } + set { _item74 = value; _valuesSet[74] = true; } } + public T75 Item075 { get { return _item75; } + set { _item75 = value; _valuesSet[75] = true; } } + public T76 Item076 { get { return _item76; } + set { _item76 = value; _valuesSet[76] = true; } } + public T77 Item077 { get { return _item77; } + set { _item77 = value; _valuesSet[77] = true; } } + public T78 Item078 { get { return _item78; } + set { _item78 = value; _valuesSet[78] = true; } } + public T79 Item079 { get { return _item79; } + set { _item79 = value; _valuesSet[79] = true; } } + public T80 Item080 { get { return _item80; } + set { _item80 = value; _valuesSet[80] = true; } } + public T81 Item081 { get { return _item81; } + set { _item81 = value; _valuesSet[81] = true; } } + public T82 Item082 { get { return _item82; } + set { _item82 = value; _valuesSet[82] = true; } } + public T83 Item083 { get { return _item83; } + set { _item83 = value; _valuesSet[83] = true; } } + public T84 Item084 { get { return _item84; } + set { _item84 = value; _valuesSet[84] = true; } } + public T85 Item085 { get { return _item85; } + set { _item85 = value; _valuesSet[85] = true; } } + public T86 Item086 { get { return _item86; } + set { _item86 = value; _valuesSet[86] = true; } } + public T87 Item087 { get { return _item87; } + set { _item87 = value; _valuesSet[87] = true; } } + public T88 Item088 { get { return _item88; } + set { _item88 = value; _valuesSet[88] = true; } } + public T89 Item089 { get { return _item89; } + set { _item89 = value; _valuesSet[89] = true; } } + public T90 Item090 { get { return _item90; } + set { _item90 = value; _valuesSet[90] = true; } } + public T91 Item091 { get { return _item91; } + set { _item91 = value; _valuesSet[91] = true; } } + public T92 Item092 { get { return _item92; } + set { _item92 = value; _valuesSet[92] = true; } } + public T93 Item093 { get { return _item93; } + set { _item93 = value; _valuesSet[93] = true; } } + public T94 Item094 { get { return _item94; } + set { _item94 = value; _valuesSet[94] = true; } } + public T95 Item095 { get { return _item95; } + set { _item95 = value; _valuesSet[95] = true; } } + public T96 Item096 { get { return _item96; } + set { _item96 = value; _valuesSet[96] = true; } } + public T97 Item097 { get { return _item97; } + set { _item97 = value; _valuesSet[97] = true; } } + public T98 Item098 { get { return _item98; } + set { _item98 = value; _valuesSet[98] = true; } } + public T99 Item099 { get { return _item99; } + set { _item99 = value; _valuesSet[99] = true; } } + public T100 Item100 { get { return _item100; } + set { _item100 = value; _valuesSet[100] = true; } } + public T101 Item101 { get { return _item101; } + set { _item101 = value; _valuesSet[101] = true; } } + public T102 Item102 { get { return _item102; } + set { _item102 = value; _valuesSet[102] = true; } } + public T103 Item103 { get { return _item103; } + set { _item103 = value; _valuesSet[103] = true; } } + public T104 Item104 { get { return _item104; } + set { _item104 = value; _valuesSet[104] = true; } } + public T105 Item105 { get { return _item105; } + set { _item105 = value; _valuesSet[105] = true; } } + public T106 Item106 { get { return _item106; } + set { _item106 = value; _valuesSet[106] = true; } } + public T107 Item107 { get { return _item107; } + set { _item107 = value; _valuesSet[107] = true; } } + public T108 Item108 { get { return _item108; } + set { _item108 = value; _valuesSet[108] = true; } } + public T109 Item109 { get { return _item109; } + set { _item109 = value; _valuesSet[109] = true; } } + public T110 Item110 { get { return _item110; } + set { _item110 = value; _valuesSet[110] = true; } } + public T111 Item111 { get { return _item111; } + set { _item111 = value; _valuesSet[111] = true; } } + public T112 Item112 { get { return _item112; } + set { _item112 = value; _valuesSet[112] = true; } } + public T113 Item113 { get { return _item113; } + set { _item113 = value; _valuesSet[113] = true; } } + public T114 Item114 { get { return _item114; } + set { _item114 = value; _valuesSet[114] = true; } } + public T115 Item115 { get { return _item115; } + set { _item115 = value; _valuesSet[115] = true; } } + public T116 Item116 { get { return _item116; } + set { _item116 = value; _valuesSet[116] = true; } } + public T117 Item117 { get { return _item117; } + set { _item117 = value; _valuesSet[117] = true; } } + public T118 Item118 { get { return _item118; } + set { _item118 = value; _valuesSet[118] = true; } } + public T119 Item119 { get { return _item119; } + set { _item119 = value; _valuesSet[119] = true; } } + public T120 Item120 { get { return _item120; } + set { _item120 = value; _valuesSet[120] = true; } } + public T121 Item121 { get { return _item121; } + set { _item121 = value; _valuesSet[121] = true; } } + public T122 Item122 { get { return _item122; } + set { _item122 = value; _valuesSet[122] = true; } } + public T123 Item123 { get { return _item123; } + set { _item123 = value; _valuesSet[123] = true; } } + public T124 Item124 { get { return _item124; } + set { _item124 = value; _valuesSet[124] = true; } } + public T125 Item125 { get { return _item125; } + set { _item125 = value; _valuesSet[125] = true; } } + public T126 Item126 { get { return _item126; } + set { _item126 = value; _valuesSet[126] = true; } } + public T127 Item127 { get { return _item127; } + set { _item127 = value; _valuesSet[127] = true; } } @@ -2233,6 +2510,7 @@ protected override void SetValueImpl(int index, object value) default: throw new ArgumentOutOfRangeException("index"); } } + public override int Capacity { get diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 1e35eadf68b..f9b39cff49c 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -17,6 +17,7 @@ internal class ScriptBlockToPowerShellChecker : AstVisitor internal ScriptBlockAst ScriptBeingConverted { get; set; } internal bool UsesParameter { get; private set; } + internal bool HasUsingExpr { get; private set; } public override AstVisitAction VisitParameter(ParameterAst parameterAst) @@ -251,6 +252,7 @@ internal static PowerShell Convert(ScriptBlockAst body, parameter.InternalVisit(checker); } } + body.InternalVisit(checker); // When the context is null (or they haven't supplied any variables), throw, but only if we really need the @@ -298,6 +300,7 @@ internal static PowerShell Convert(ScriptBlockAst body, converter._powershell.AddStatement(); converter.ConvertPipeline(pipeline, isTrustedInput); } + return converter._powershell; } finally @@ -630,6 +633,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) { _powershell.AddArgument(usingValue); } + continue; } @@ -676,6 +680,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) argument = GetExpressionValue(exprAst, isTrustedInput); } } + _powershell.AddArgument(argument); } } @@ -757,10 +762,12 @@ private object GetExpressionValue(ExpressionAst exprAst, bool isTrustedInput) rs.Open(); _context = rs.ExecutionContext; } + if (!isTrustedInput) // if it's not trusted, call the safe value visitor { return GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell); } + return Compiler.GetExpressionValue(exprAst, isTrustedInput, _context, _usingValueMap); } From 8c3b80f54a8e67441df81330e99920a3a2076cec Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:12 -0800 Subject: [PATCH 68/81] Update client --- .../remoting/client/ClientRemotePowerShell.cs | 9 +++ .../engine/remoting/client/Job.cs | 57 +++++++++++++++++++ .../engine/remoting/client/Job2.cs | 33 +++++++++++ .../engine/remoting/client/JobManager.cs | 3 + .../remoting/client/JobSourceAdapter.cs | 11 ++++ .../engine/remoting/client/PSProxyJob.cs | 35 ++++++++++++ .../remoting/client/PowerShellStreams.cs | 8 +++ .../client/RemoteRunspacePoolInternal.cs | 22 +++++++ .../remoting/client/RemotingErrorRecord.cs | 9 +++ .../remoting/client/RemotingProtocol2.cs | 24 ++++++++ .../engine/remoting/client/ThrottlingJob.cs | 31 ++++++++++ .../remoting/client/clientremotesession.cs | 2 + ...clientremotesessionprotocolstatemachine.cs | 14 +++++ .../engine/remoting/client/remotepipeline.cs | 7 +++ .../engine/remoting/client/remoterunspace.cs | 15 +++++ .../client/remotingprotocolimplementation.cs | 4 ++ 16 files changed, 284 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 7b290909446..c69d853a6b3 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -99,6 +99,7 @@ internal ObjectStreamBase InputStream { return inputstream; } + set { inputstream = value; @@ -123,6 +124,7 @@ internal ObjectStreamBase OutputStream { return outputstream; } + set { outputstream = value; @@ -526,18 +528,21 @@ private void HandleInformationalMessageReceived(object sender, { informationalBuffers.AddDebug((DebugRecord)infoMessage.Message); } + break; case RemotingDataType.PowerShellVerbose: { informationalBuffers.AddVerbose((VerboseRecord)infoMessage.Message); } + break; case RemotingDataType.PowerShellWarning: { informationalBuffers.AddWarning((WarningRecord)infoMessage.Message); } + break; case RemotingDataType.PowerShellProgress: @@ -546,12 +551,14 @@ private void HandleInformationalMessageReceived(object sender, typeof(ProgressRecord), System.Globalization.CultureInfo.InvariantCulture); informationalBuffers.AddProgress(progress); } + break; case RemotingDataType.PowerShellInformationStream: { informationalBuffers.AddInformation((InformationRecord)infoMessage.Message); } + break; } } @@ -821,6 +828,7 @@ private void HandleRobustConnectionNotification( new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); } + break; case ConnectionStatus.AutoDisconnectSucceeded: @@ -845,6 +853,7 @@ private void HandleRobustConnectionNotification( new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort, this.computerName, maxRetryConnectionTimeMinutes, errorRecord); } + break; } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 6be8bb56d84..6b96c98f831 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -333,6 +333,7 @@ public JobStateEventArgs(JobStateInfo jobStateInfo, JobStateInfo previousJobStat { throw PSTraceSource.NewArgumentNullException("jobStateInfo"); } + JobStateInfo = jobStateInfo; PreviousJobStateInfo = previousJobStateInfo; } @@ -369,6 +370,7 @@ internal JobIdentifier(int id, Guid instanceId) } internal int Id { get; private set; } + internal Guid InstanceId { get; private set; } } @@ -608,6 +610,7 @@ public string Name { return _name; } + set { AssertNotDisposed(); @@ -632,6 +635,7 @@ public IList ChildJobs } } } + return _childJobs; } } @@ -663,6 +667,7 @@ public IList ChildJobs public string PSJobTypeName { get { return _jobTypeName; } + protected internal set { _jobTypeName = value ?? this.GetType().ToString(); @@ -682,12 +687,14 @@ internal PSDataCollection Results { return _results; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Results"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -770,6 +777,7 @@ internal virtual void WriteError(ErrorRecord errorRecord) return; } } + Results.Add(new PSStreamObject(PSStreamObjectType.Error, errorRecord)); } @@ -909,6 +917,7 @@ private T InvokeCmdletMethodAndWaitForResults(Func invokeCmdletMet { closureSafeExceptionThrownOnCmdletThread = new OperationCanceledException(); } + gotResultEvent.Set(); } }; @@ -1007,6 +1016,7 @@ public void LoadJobStreams() _jobStreamsLoaded = true; } + try { DoLoadJobStreams(); @@ -1022,6 +1032,7 @@ public void LoadJobStreams() } } } + private bool _jobStreamsLoaded; /// @@ -1071,12 +1082,14 @@ public PSDataCollection Output LoadJobStreams(); // for delayed loading return _output; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Output"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1105,12 +1118,14 @@ public PSDataCollection Error LoadJobStreams(); // for delayed loading return _error; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Error"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1139,12 +1154,14 @@ public PSDataCollection Progress LoadJobStreams(); // for delayed loading return _progress; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Progress"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1170,12 +1187,14 @@ public PSDataCollection Verbose LoadJobStreams(); // for delayed loading return _verbose; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Verbose"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1204,12 +1223,14 @@ public PSDataCollection Debug LoadJobStreams(); // for delayed loading return _debug; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Debug"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1237,12 +1258,14 @@ public PSDataCollection Warning LoadJobStreams(); // for delayed loading return _warning; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Warning"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1271,12 +1294,14 @@ public PSDataCollection Information LoadJobStreams(); // for delayed loading return _information; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Information"); } + lock (syncObject) { AssertChangesAreAccepted(); @@ -1544,12 +1569,19 @@ internal void CloseAllStreams() // handle and potentially throw exceptions on the notification thread. We don't want to // propagate those exceptions because it prevents this thread from completing its processing. if (_resultsOwner) { try { _results.Complete(); } catch (Exception e) { TraceException(e); } } + if (_outputOwner) { try { _output.Complete(); } catch (Exception e) { TraceException(e); } } + if (_errorOwner) { try { _error.Complete(); } catch (Exception e) { TraceException(e); } } + if (_progressOwner) { try { _progress.Complete(); } catch (Exception e) { TraceException(e); } } + if (_verboseOwner) { try { _verbose.Complete(); } catch (Exception e) { TraceException(e); } } + if (_warningOwner) { try { _warning.Complete(); } catch (Exception e) { TraceException(e); } } + if (_debugOwner) { try { _debug.Complete(); } catch (Exception e) { TraceException(e); } } + if (_informationOwner) { try { _information.Complete(); } catch (Exception e) { TraceException(e); } } } @@ -1635,6 +1667,7 @@ protected virtual void Dispose(bool disposing) } } } + private bool _isDisposed; #endregion IDisposable Members @@ -1793,6 +1826,7 @@ internal PSRemotingJob(PSSession[] remoteRunspaceInfos, //Add the child job to list of child jobs ChildJobs.Add(job); } + CommonInit(throttleLimit, runspaceHelpers); } @@ -1904,6 +1938,7 @@ internal List GetJobsForRunspace(PSSession runspace) returnJobList.Add(child); } } + return returnJobList; } @@ -2145,6 +2180,7 @@ internal void InternalStopJob() { return; } + _stopIsCalled = true; } @@ -2256,6 +2292,7 @@ public override string StatusMessage internal bool HideComputerName { get { return _hideComputerName; } + set { _hideComputerName = value; @@ -2269,6 +2306,7 @@ internal bool HideComputerName } } } + private bool _hideComputerName = true; //ISSUE: Implement StatusMessage @@ -2389,6 +2427,7 @@ private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) { return; } + if (e.JobStateInfo.State == JobState.Failed) { //If any of the child job failed, we set status to failed @@ -2407,6 +2446,7 @@ private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) allChildJobsFinished = true; } } + if (allChildJobsFinished) { //if any child job failed, set status to failed @@ -2517,10 +2557,12 @@ protected override void Dispose(bool disposing) { StopJob(); } + foreach (Job job in ChildJobs) { job.Dispose(); } + _throttleManager.Dispose(); } finally @@ -2543,6 +2585,7 @@ private string ConstructLocation() location.Append(job.Location); location.Append(","); } + location.Remove(location.Length - 1, 1); } @@ -2587,6 +2630,7 @@ internal override IEnumerable GetRunspaces() { runspaces.Add(job.Runspace as RemoteRunspace); } + return runspaces; } @@ -2897,6 +2941,7 @@ public override string Location internal bool HideComputerName { get { return _hideComputerName; } + set { _hideComputerName = value; @@ -2910,6 +2955,7 @@ internal bool HideComputerName } } } + private bool _hideComputerName = true; /// @@ -2965,6 +3011,7 @@ public Debugger Debugger public bool IsAsync { get { return _isAsync; } + set { _isAsync = true; } } @@ -3126,6 +3173,7 @@ protected virtual void HandlePipelineStateChanged(object sender, PipelineStateEv { SetJobState(JobState.Running); } + break; case PipelineState.Disconnected: @@ -3181,6 +3229,7 @@ protected virtual void HandleOperationComplete(object sender, OperationStateEven DeterminedAndSetJobState(helper); } + private bool _doFinishCalled = false; /// @@ -3265,6 +3314,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai "{0},{1}", errorId, failureException.Source); } } + failureErrorRecord = new ErrorRecord(helper.InternalException, errorId, ErrorCategory.OperationStopped, helper); @@ -3317,6 +3367,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai errorDetails += transException.TransportMessage; } } + if (failureException == null) { failureException = new RuntimeException( @@ -3324,6 +3375,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, runspace.RunspaceStateInfo.State)); } + failureErrorRecord = new ErrorRecord(failureException, targetObject, fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); @@ -3378,12 +3430,14 @@ protected override void Dispose(bool disposing) { return; } + lock (SyncObject) { if (_isDisposed) { return; } + _isDisposed = true; } @@ -3419,6 +3473,7 @@ protected virtual void DoCleanupOnFinished() } } } + if (!doCleanup) return; StopAggregateResultsFromHelper(Helper); @@ -4064,6 +4119,7 @@ internal PSInvokeExpressionSyncJob(List operations, Throttle remoteRS.URIRedirectionReported += HandleURIDirectionReported; } } + _helpers.Add(helper); AggregateResultsFromHelper(helper); @@ -4331,6 +4387,7 @@ internal Collection GetPowerShells() { powershellsToReturn.Add(ps); } + return powershellsToReturn; } diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index 0d23fadf5a2..b069d80664c 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -305,31 +305,37 @@ private void RaiseCompletedHandler(int operation, AsyncCompletedEventArgs eventA { handler = StartJobCompleted; } + break; case StopJobOperation: { handler = StopJobCompleted; } + break; case SuspendJobOperation: { handler = SuspendJobCompleted; } + break; case ResumeJobOperation: { handler = ResumeJobCompleted; } + break; case UnblockJobOperation: { handler = UnblockJobCompleted; } + break; default: { Dbg.Assert(false, "this condition should not be hit, check the value of operation that you passed"); } + break; } #pragma warning disable 56500 @@ -527,6 +533,7 @@ public sealed class ContainerParentJob : Job2 internal PSEventManager EventManager { get { return _eventManager; } + set { _tracer.WriteMessage("Setting event manager for Job ", InstanceId); @@ -577,6 +584,7 @@ private ManualResetEvent JobSuspendedOrAborted } } } + return _jobSuspendedOrAborted; } } @@ -697,6 +705,7 @@ public void AddChildJob(Job2 childJob) { throw new ArgumentNullException("childJob"); } + _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); JobStateInfo childJobStateInfo; @@ -707,6 +716,7 @@ public void AddChildJob(Job2 childJob) childJobStateInfo = childJob.JobStateInfo; childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); } + ChildJobs.Add(childJob); ParentJobStateCalculation(new JobStateEventArgs(childJobStateInfo, new JobStateInfo(JobState.NotStarted))); } @@ -850,6 +860,7 @@ public override void StartJob() ScriptDebugger.SetDebugJobAsync(job as IJobDebugger, false); job.StartJobAsync(); } + completed.WaitOne(); foreach (Job2 job in ChildJobs) { @@ -884,6 +895,7 @@ public override void StartJobAsync() OnStartJobCompleted(new AsyncCompletedEventArgs(new ObjectDisposedException(TraceClassName), false, null)); return; } + _tracer.WriteMessage(TraceClassName, "StartJobAsync", Guid.Empty, this, "Entering method", null); s_structuredTracer.BeginContainerParentJobExecution(InstanceId); foreach (Job2 job in this.ChildJobs) @@ -1025,6 +1037,7 @@ public override void ResumeJob() "Child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); job.ResumeJobAsync(); } + completed.WaitOne(); Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) @@ -1033,6 +1046,7 @@ public override void ResumeJob() job.ResumeJobCompleted -= eventHandler; } + _tracer.WriteMessage(TraceClassName, "ResumeJob", Guid.Empty, this, "Exiting method", null); // Errors are taken from the Error collection by the cmdlet for ContainerParentJob. @@ -1048,6 +1062,7 @@ public override void ResumeJobAsync() OnResumeJobCompleted(new AsyncCompletedEventArgs(new ObjectDisposedException(TraceClassName), false, null)); return; } + _tracer.WriteMessage(TraceClassName, "ResumeJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { @@ -1260,6 +1275,7 @@ public override void UnblockJob() "Child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); job.UnblockJobAsync(); } + completed.WaitOne(); Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) @@ -1268,6 +1284,7 @@ public override void UnblockJob() job.UnblockJobCompleted -= eventHandler; } + _tracer.WriteMessage(TraceClassName, "UnblockJob", Guid.Empty, this, "Exiting method", null); // Errors are taken from the Error collection by the cmdlet for ContainerParentJob. @@ -1284,6 +1301,7 @@ public override void UnblockJobAsync() OnUnblockJobCompleted(new AsyncCompletedEventArgs(new ObjectDisposedException(TraceClassName), false, null)); return; } + _tracer.WriteMessage(TraceClassName, "UnblockJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { @@ -1433,6 +1451,7 @@ private void SuspendJobInternal(bool? force, string reason) else job.SuspendJobAsync(); } + completed.WaitOne(); Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) @@ -1441,6 +1460,7 @@ private void SuspendJobInternal(bool? force, string reason) job.SuspendJobCompleted -= eventHandler; } + _tracer.WriteMessage(TraceClassName, "SuspendJob", Guid.Empty, this, "Exiting method", null); // Errors are taken from the Error collection by the cmdlet for ContainerParentJob. @@ -1458,6 +1478,7 @@ private void SuspendJobAsyncInternal(bool? force, string reason) OnSuspendJobCompleted(new AsyncCompletedEventArgs(new ObjectDisposedException(TraceClassName), false, null)); return; } + _tracer.WriteMessage(TraceClassName, "SuspendJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { @@ -1607,6 +1628,7 @@ private void StopJobInternal(bool? force, string reason) else job.StopJobAsync(); } + completed.WaitOne(); Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) @@ -1615,6 +1637,7 @@ private void StopJobInternal(bool? force, string reason) job.StopJobCompleted -= eventHandler; } + _tracer.WriteMessage(TraceClassName, "StopJob", Guid.Empty, this, "Exiting method", null); // Errors are taken from the Error collection by the cmdlet for ContainerParentJob. @@ -1632,6 +1655,7 @@ private void StopJobAsyncInternal(bool? force, string reason) OnStopJobCompleted(new AsyncCompletedEventArgs(new ObjectDisposedException(TraceClassName), false, null)); return; } + _tracer.WriteMessage(TraceClassName, "StopJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) @@ -1707,6 +1731,7 @@ private void HandleMyStateChanged(object sender, JobStateEventArgs e) JobSuspendedOrAborted.Reset(); } } + break; case JobState.Suspended: @@ -1717,6 +1742,7 @@ private void HandleMyStateChanged(object sender, JobStateEventArgs e) JobRunning.Reset(); } } + break; case JobState.Failed: case JobState.Completed: @@ -1732,6 +1758,7 @@ private void HandleMyStateChanged(object sender, JobStateEventArgs e) JobRunning.Set(); } } + break; } } @@ -1758,6 +1785,7 @@ private void ParentJobStateCalculation(JobStateEventArgs e) { PSBeginTime = DateTime.Now; } + if (!IsFinishedState(JobStateInfo.State) && IsPersistentState(computedState)) { PSEndTime = DateTime.Now; @@ -1893,6 +1921,7 @@ internal static bool ComputeJobStateFromChildJobStates(string traceClassName, Jo // if the job state is blocked, we have already returned. return false; } + if (e.JobStateInfo.State == JobState.Failed) { // If any of the child job failed, we set status to failed @@ -1928,12 +1957,14 @@ internal static bool ComputeJobStateFromChildJobStates(string traceClassName, Jo computedJobState = JobState.Failed; return true; } + if (stoppedChildJobsCount > 0) { tracer.WriteMessage(traceClassName, ": JobState is stopped, stop is called."); computedJobState = JobState.Stopped; return true; } + tracer.WriteMessage(traceClassName, ": JobState is completed."); computedJobState = JobState.Completed; return true; @@ -2131,12 +2162,14 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte /// The actual exception that caused this error. /// public Exception Reason { get { return _reason; } } + private Exception _reason; /// /// The user-focused location from where this error originated. /// public ScriptExtent DisplayScriptPosition { get { return _displayScriptPosition; } } + private ScriptExtent _displayScriptPosition; /// diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 068fd76edd2..a1a711366dc 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -272,6 +272,7 @@ public void PersistJob(Job2 job, JobDefinition definition) { throw new PSArgumentNullException("job"); } + if (definition == null) { throw new PSArgumentNullException("definition"); @@ -348,6 +349,7 @@ private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition) { adapterFound = _sourceAdapters.TryGetValue(adapterTypeName, out adapter); } + if (!adapterFound) { if (!string.IsNullOrEmpty(definition.ModuleName)) @@ -773,6 +775,7 @@ private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErro { cmdlet.WriteObject(job); } + return job; } } diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index 0d6df081335..d34a26a0184 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -31,6 +31,7 @@ public class JobDefinition : ISerializable public string Name { get { return _name; } + set { _name = value; } } @@ -50,6 +51,7 @@ public string Name public string ModuleName { get { return _moduleName; } + set { _moduleName = value; } } @@ -61,6 +63,7 @@ public string ModuleName public string JobSourceAdapterTypeName { get { return _jobSourceAdapterTypeName; } + set { _jobSourceAdapterTypeName = value; } } @@ -81,6 +84,7 @@ public Guid InstanceId { return _instanceId; } + set { _instanceId = value; @@ -132,6 +136,7 @@ public JobDefinition(Type jobSourceAdapterType, string command, string name) { _jobSourceAdapterTypeName = jobSourceAdapterType.Name; } + Command = command; _name = name; _instanceId = Guid.NewGuid(); @@ -179,6 +184,7 @@ public string Name { return _name; } + set { if (value == null) @@ -186,6 +192,7 @@ public string Name _name = value; } } + private string _name = string.Empty; private string _command; @@ -199,6 +206,7 @@ public string Command { return _command ?? _definition.Command; } + set { _command = value; @@ -216,6 +224,7 @@ public JobDefinition Definition { return _definition; } + set { _definition = value; @@ -356,6 +365,7 @@ private static CommandParameterCollection ConvertDictionaryToParameterCollection { paramCollection.Add(paramItem); } + return paramCollection; } } @@ -397,6 +407,7 @@ public void StoreJobIdForReuse(Job2 job, bool recurse) { PSTraceSource.NewArgumentNullException("job", RemotingErrorIdStrings.JobSourceAdapterCannotSaveNullJob); } + JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name); if (recurse && job.ChildJobs != null && job.ChildJobs.Count > 0) { diff --git a/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs b/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs index 09b091c6bac..3ca1d2c20eb 100644 --- a/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs @@ -452,6 +452,7 @@ public void RemoveJob(bool removeRemoteJob, bool force) { AssertNotDisposed(); } + try { DoRemove(force); @@ -466,6 +467,7 @@ public void RemoveJob(bool removeRemoteJob, bool force) return; } } + RemoveComplete.WaitOne(); } catch (Exception error) @@ -575,12 +577,14 @@ public bool RemoveRemoteJobOnCompletion { return _removeRemoteJobOnCompletion; } + set { AssertChangesCanBeAccepted(); _removeRemoteJobOnCompletion = value; } } + private bool _removeRemoteJobOnCompletion; /// @@ -602,6 +606,7 @@ public Runspace Runspace { return _runspace; } + set { if (value == null) @@ -627,6 +632,7 @@ public RunspacePool RunspacePool { return _runspacePool; } + set { if (value == null) @@ -798,6 +804,7 @@ private static ICollection Create(Runspace runspace, RunspacePool ru { Dbg.Assert(false, "Job object did not contain command when creating proxy."); } + PSJobProxy job = new PSJobProxy(command); job.InitializeExistingJobProxy(deserializedJob, runspace, runspacePool); @@ -931,8 +938,10 @@ internal void InitializeExistingJobProxy(PSObject o, Runspace runspace, Runspace { psPrivateMetadata = p.Value; } + childJobCol.Add(p.Name, p.Value); } + psParamCollection.Add(childJobCol); } @@ -942,6 +951,7 @@ internal void InitializeExistingJobProxy(PSObject o, Runspace runspace, Runspace { newStartParameters.Add(new CommandParameter("PSPrivateMetadata", psPrivateMetadata)); } + StartParameters.Add(newStartParameters); } @@ -1118,6 +1128,7 @@ private void ProcessQueueWorker(object state) // Transfer exception via event arguments. OnStopJobCompleted(new AsyncCompletedEventArgs(e, false, null)); } + break; case QueueOperation.Suspend: try @@ -1130,6 +1141,7 @@ private void ProcessQueueWorker(object state) // Transfer exception via event arguments. OnSuspendJobCompleted(new AsyncCompletedEventArgs(e, false, null)); } + break; case QueueOperation.Resume: try @@ -1214,6 +1226,7 @@ private void DoStartPrepare() // not proceed with the operation. This is an error. throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.JobProxyAsJobMustBeTrue); } + found = true; } } @@ -1392,6 +1405,7 @@ private void DoRemove(object state) { _remoteJobRemoved = true; } + if (!IsFinishedState(JobStateInfo.State)) { DoSetJobState(JobState.Stopped); @@ -1519,6 +1533,7 @@ private void HandleMyStateChange(object sender, JobStateEventArgs e) OnResumeJobCompleted(new AsyncCompletedEventArgs(null, false, null)); } } + break; case JobState.Suspended: @@ -1532,6 +1547,7 @@ private void HandleMyStateChange(object sender, JobStateEventArgs e) OnSuspendJobCompleted(new AsyncCompletedEventArgs(null, false, null)); } } + break; case JobState.Failed: case JobState.Completed: @@ -1555,6 +1571,7 @@ private void HandleMyStateChange(object sender, JobStateEventArgs e) OnStopJobCompleted(new AsyncCompletedEventArgs(e.JobStateInfo.Reason, false, null)); } } + break; } @@ -1593,6 +1610,7 @@ private void ReceivePowerShellInvocationStateChanged(object sender, PSInvocation "Setting job state to {0} old state was {1} and reason is {2}.", newState.ToString(), JobStateInfo.State.ToString(), reason); DoSetJobState(newState, e.InvocationStateInfo.Reason); } + break; case PSInvocationState.Stopped: @@ -1634,6 +1652,7 @@ private void PopulateJobProperties(PSObject o) Dbg.Assert(false, "ChildJobs should be serialized to include InstanceID, cannot interact with them otherwise."); continue; } + var childProxyJob = new PSChildJobProxy(Command, job); // All have the same workflow name. _childJobsMapping.Add(childJobInstanceId, childProxyJob); @@ -1653,6 +1672,7 @@ private void PopulateJobProperties(PSObject o) { PopulateStartParametersOnChild(childJobStartParametersObject, childProxyJob); } + ChildJobs.Add(childProxyJob); } } @@ -1680,9 +1700,11 @@ private void PopulateStartParametersOnChild(PSObject childJobStartParametersObje newComParCol.Add(cp); } } + listComParCol.Add(newComParCol); } } + childProxyJob.StartParameters = listComParCol; } } @@ -2089,6 +2111,7 @@ private void DataAddedToOutput(object sender, DataAddedEventArgs e) Diagnostics.Assert(false, "We should not get an unidentified source job id in non interop scenarios"); } + return; } @@ -2109,6 +2132,7 @@ private void DataAddedToOutput(object sender, DataAddedEventArgs e) "Finished updating child job {0} state to {1} ", sourceJobId.ToString(), jobStateEventArgs.JobStateInfo.State.ToString()); } + return; } @@ -2316,6 +2340,7 @@ private static string RemoveIdentifierInformation(string message, out Guid jobIn return parts[2]; } } + return message; } @@ -2338,6 +2363,7 @@ protected override void Dispose(bool disposing) _isDisposed = true; } + if (_receivePowerShell != null) { _receivePowerShell.Stop(); @@ -2380,6 +2406,7 @@ protected override void Dispose(bool disposing) private enum QueueOperation { Stop, Suspend, Resume } + private ConcurrentQueue _pendingOperations = new ConcurrentQueue(); private ManualResetEvent _removeComplete; @@ -2451,6 +2478,7 @@ private ManualResetEvent JobSuspendedOrFinished } } } + return _jobSuspendedOrFinished; } } @@ -2561,26 +2589,32 @@ private void OutputAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Output, e.Index)); } + private void ErrorAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Error, e.Index)); } + private void WarningAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Warning, e.Index)); } + private void VerboseAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Verbose, e.Index)); } + private void ProgressAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Progress, e.Index)); } + private void DebugAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Debug, e.Index)); } + private void InformationAdded(object sender, DataAddedEventArgs e) { OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Information, e.Index)); @@ -2672,6 +2706,7 @@ protected override void Dispose(bool disposing) Debug.DataAdded -= DebugAdded; Information.DataAdded -= InformationAdded; } + base.Dispose(disposing); } diff --git a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs index 8125842ffd7..038a8fc1763 100644 --- a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs +++ b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs @@ -151,6 +151,7 @@ private void Dispose(bool disposing) public PSDataCollection InputStream { get { return _inputStream; } + set { _inputStream = value; } } @@ -161,6 +162,7 @@ public PSDataCollection InputStream public PSDataCollection OutputStream { get { return _outputStream; } + set { _outputStream = value; } } @@ -171,6 +173,7 @@ public PSDataCollection OutputStream public PSDataCollection ErrorStream { get { return _errorStream; } + set { _errorStream = value; } } @@ -181,6 +184,7 @@ public PSDataCollection ErrorStream public PSDataCollection WarningStream { get { return _warningStream; } + set { _warningStream = value; } } @@ -191,6 +195,7 @@ public PSDataCollection WarningStream public PSDataCollection ProgressStream { get { return _progressStream; } + set { _progressStream = value; } } @@ -201,6 +206,7 @@ public PSDataCollection ProgressStream public PSDataCollection VerboseStream { get { return _verboseStream; } + set { _verboseStream = value; } } @@ -211,6 +217,7 @@ public PSDataCollection VerboseStream public PSDataCollection DebugStream { get { return _debugStream; } + set { _debugStream = value; } } @@ -221,6 +228,7 @@ public PSDataCollection DebugStream public PSDataCollection InformationStream { get { return _informationStream; } + set { _informationStream = value; } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 47fb1a7d90f..73597347c7e 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -113,10 +113,12 @@ internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconn { throw PSTraceSource.NewArgumentNullException("RunspacePool Guid"); } + if (connectCommands == null) { throw PSTraceSource.NewArgumentNullException("ConnectCommandInfo[]"); } + if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); @@ -229,6 +231,7 @@ public override RunspaceConnectionInfo ConnectionInfo internal string Name { get { return _friendlyName; } + set { _friendlyName = value ?? string.Empty; } } @@ -1315,6 +1318,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con throw; } + foreach (PSObject cmdObject in commandItems) { PSPropertyInfo pspCommandId = cmdObject.Properties["CommandId"]; @@ -1376,6 +1380,7 @@ private static void UpdateWSManConnectionInfo( wsmanConnectionInfo.IdleTimeout = idleTimeout; } } + if (pspBufferMode != null) { string bufferingMode = pspBufferMode.Value as string; @@ -1389,6 +1394,7 @@ private static void UpdateWSManConnectionInfo( } } } + if (pspResourceUri != null) { string strShellUri = pspResourceUri.Value as string; @@ -1397,6 +1403,7 @@ private static void UpdateWSManConnectionInfo( wsmanConnectionInfo.ShellUri = strShellUri; } } + if (pspLocale != null) { string localString = pspLocale.Value as string; @@ -1410,6 +1417,7 @@ private static void UpdateWSManConnectionInfo( { } } } + if (pspDataLocale != null) { string dataLocalString = pspDataLocale.Value as string; @@ -1423,6 +1431,7 @@ private static void UpdateWSManConnectionInfo( { } } } + if (pspCompressionMode != null) { string compressionModeString = pspCompressionMode.Value as string; @@ -1432,6 +1441,7 @@ private static void UpdateWSManConnectionInfo( ? false : true; } } + if (pspEncoding != null) { string encodingString = pspEncoding.Value as string; @@ -1441,6 +1451,7 @@ private static void UpdateWSManConnectionInfo( ? true : false; } } + if (pspProfile != null) { string machineProfileLoadedString = pspProfile.Value as string; @@ -1450,6 +1461,7 @@ private static void UpdateWSManConnectionInfo( ? false : true; } } + if (pspMaxIdleTimeout != null) { int maxIdleTimeout; @@ -1994,24 +2006,29 @@ internal static Collection GetRemotePools(WSManConnectionInfo wsmanCon { powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential); } + if (wsmanConnectionInfo.CertificateThumbprint != null) { powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } + if (wsmanConnectionInfo.PortSetting != -1) { powerShell.AddParameter("Port", wsmanConnectionInfo.Port); } + if (CheckForSSL(wsmanConnectionInfo)) { powerShell.AddParameter("UseSSL", true); } + if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName)) { // Remove prepended path character. string appName = wsmanConnectionInfo.AppName.TrimStart('/'); powerShell.AddParameter("ApplicationName", appName); } + powerShell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo)); result = powerShell.Invoke(); @@ -2049,24 +2066,29 @@ internal static Collection GetRemoteCommands(Guid shellId, WSManConnec { powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential); } + if (wsmanConnectionInfo.CertificateThumbprint != null) { powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } + if (wsmanConnectionInfo.PortSetting != -1) { powerShell.AddParameter("Port", wsmanConnectionInfo.Port); } + if (CheckForSSL(wsmanConnectionInfo)) { powerShell.AddParameter("UseSSL", true); } + if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName)) { // Remove prepended path character. string appName = wsmanConnectionInfo.AppName.TrimStart('/'); powerShell.AddParameter("ApplicationName", appName); } + powerShell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo)); result = powerShell.Invoke(); diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index dff2dbf693c..0f385b21948 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -24,6 +24,7 @@ public OriginInfo OriginInfo return _originInfo; } } + private OriginInfo _originInfo; /// @@ -114,6 +115,7 @@ public OriginInfo OriginInfo { get { return _originInfo; } } + [DataMemberAttribute()] private readonly OriginInfo _originInfo; @@ -159,6 +161,7 @@ public OriginInfo OriginInfo { get { return _originInfo; } } + [DataMemberAttribute()] private readonly OriginInfo _originInfo; @@ -199,6 +202,7 @@ public OriginInfo OriginInfo { get { return _originInfo; } } + [DataMemberAttribute()] private readonly OriginInfo _originInfo; @@ -226,6 +230,7 @@ public OriginInfo OriginInfo { get { return _originInfo; } } + [DataMemberAttribute()] private readonly OriginInfo _originInfo; @@ -253,6 +258,7 @@ public OriginInfo OriginInfo { get { return _originInfo; } } + [DataMemberAttribute()] private readonly OriginInfo _originInfo; @@ -295,6 +301,7 @@ public string PSComputerName return _computerName; } } + [DataMemberAttribute()] private string _computerName; @@ -309,6 +316,7 @@ public Guid RunspaceID return _runspaceID; } } + [DataMemberAttribute()] private Guid _runspaceID; @@ -328,6 +336,7 @@ public Guid InstanceID _instanceId = value; } } + [DataMemberAttribute()] private Guid _instanceId; diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index c49535ddd3d..ba0e734d9c1 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -140,6 +140,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) RemoteHostCall remoteHostCall = RemoteHostCall.Decode(receivedData.Data); RemoteHostCallReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostCall)); } + break; case RemotingDataType.RunspacePoolInitData: @@ -151,6 +152,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) RSPoolInitInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(initInfo)); } + break; case RemotingDataType.RunspacePoolStateInfo: @@ -165,6 +167,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) NotifyAssociatedPowerShells(stateInfo); } + break; case RemotingDataType.ApplicationPrivateData: @@ -175,6 +178,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) ApplicationPrivateDataReceived.SafeInvoke(this, new RemoteDataEventArgs(applicationPrivateData)); } + break; case RemotingDataType.RunspacePoolOperationResponse: @@ -184,6 +188,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) SetMaxMinRunspacesResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; case RemotingDataType.PSEventArgs: @@ -195,6 +200,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) PSEventArgsReceived.SafeInvoke(this, new RemoteDataEventArgs(psEventArgs)); } + break; } } @@ -227,6 +233,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) { _associatedPowerShellDSHandlers.Add(shell.InstanceId, shell.DataStructureHandler); } + shell.DataStructureHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); @@ -494,6 +501,7 @@ private void HandleClientRemoteSessionStateChanged( // occur multiple time in v2 remoting. return; } + _createRunspaceCalled = true; } @@ -505,6 +513,7 @@ private void HandleClientRemoteSessionStateChanged( _clientRunspacePoolId, _minRunspaces, _maxRunspaces, RemoteSession.RemoteRunspacePoolInternal, _host, argumentsWithVersionTable)); } + if (e.SessionStateInfo.State == RemoteSessionState.NegotiationSendingOnConnect) { // send connect message to the server. @@ -527,6 +536,7 @@ private void HandleClientRemoteSessionStateChanged( { dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } + foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { dsHandler.CloseConnectionAsync(_closingReason); @@ -615,6 +625,7 @@ private void NotifyAssociatedPowerShells(RunspacePoolStateInfo stateInfo) { dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } + foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { dsHandler.ProcessDisconnect(stateInfo); @@ -745,6 +756,7 @@ private void PrepareForAndStartDisconnect() { dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } + foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { dsHandler.TransportManager.PrepareForDisconnect(); @@ -763,6 +775,7 @@ private void PrepareForConnect() { dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } + foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { dsHandler.TransportManager.ReadyForDisconnect -= HandleReadyForDisconnect; @@ -834,6 +847,7 @@ private void HandleRobustConnectionNotification( { dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } + foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { dsHandler.ProcessRobustConnectionNotification(e); @@ -1214,6 +1228,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) InvocationStateInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(stateInfo)); } + break; case RemotingDataType.PowerShellOutput: @@ -1231,6 +1246,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) OutputReceived.SafeInvoke(this, new RemoteDataEventArgs(outputObject)); } + break; case RemotingDataType.PowerShellErrorRecord: @@ -1251,6 +1267,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) ErrorReceived.SafeInvoke(this, new RemoteDataEventArgs(errorRecord)); } + break; case RemotingDataType.PowerShellDebug: { @@ -1260,6 +1277,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) new RemoteDataEventArgs( new InformationalMessage(record, RemotingDataType.PowerShellDebug))); } + break; case RemotingDataType.PowerShellVerbose: @@ -1270,6 +1288,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) new RemoteDataEventArgs( new InformationalMessage(record, RemotingDataType.PowerShellVerbose))); } + break; case RemotingDataType.PowerShellWarning: @@ -1280,6 +1299,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) new RemoteDataEventArgs( new InformationalMessage(record, RemotingDataType.PowerShellWarning))); } + break; case RemotingDataType.PowerShellProgress: @@ -1290,6 +1310,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) new RemoteDataEventArgs( new InformationalMessage(record, RemotingDataType.PowerShellProgress))); } + break; case RemotingDataType.PowerShellInformationStream: @@ -1300,6 +1321,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) new RemoteDataEventArgs( new InformationalMessage(record, RemotingDataType.PowerShellInformationStream))); } + break; case RemotingDataType.RemoteHostCallUsingPowerShellHost: @@ -1307,12 +1329,14 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) RemoteHostCall remoteHostCall = RemoteHostCall.Decode(receivedData.Data); HostCallReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostCall)); } + break; default: { Dbg.Assert(false, "we should not be encountering this"); } + break; } } diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 550bed7dd26..1dec7181884 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -46,14 +46,17 @@ protected override void Dispose(bool disposing) childJobsToDispose = new List(this.ChildJobs); this.ChildJobs.Clear(); } + foreach (Job childJob in childJobsToDispose) { childJob.Dispose(); } + if (_jobResultsThrottlingSemaphore != null) { _jobResultsThrottlingSemaphore.Dispose(); } + _cancellationTokenSource.Dispose(); } } @@ -106,6 +109,7 @@ private void ReportProgress(bool minimizeFrequentUpdates) { return; } + if ((!_progressReportLastTime.Equals(DateTime.MinValue)) && (now - _progressReportLastTime < TimeSpan.FromMilliseconds(200))) { @@ -123,6 +127,7 @@ private void ReportProgress(bool minimizeFrequentUpdates) totalWork = _countOfAllChildJobs; workCompleted = this.CountOfFinishedChildJobs; } + if (totalWork >= 1.0) { percentComplete = (int)(100.0 * workCompleted / totalWork); @@ -131,6 +136,7 @@ private void ReportProgress(bool minimizeFrequentUpdates) { percentComplete = -1; } + percentComplete = Math.Max(-1, Math.Min(100, percentComplete)); var progressRecord = new ProgressRecord( @@ -144,6 +150,7 @@ private void ReportProgress(bool minimizeFrequentUpdates) { return; } + progressRecord.RecordType = ProgressRecordType.Completed; progressRecord.PercentComplete = 100; progressRecord.SecondsRemaining = 0; @@ -157,6 +164,7 @@ private void ReportProgress(bool minimizeFrequentUpdates) { secondsRemaining = ProgressRecord.GetSecondsRemaining(_progressStartTime, (double)percentComplete / 100.0); } + if (secondsRemaining.HasValue) { progressRecord.SecondsRemaining = secondsRemaining.Value; @@ -202,6 +210,7 @@ private bool IsEndOfChildJobs } } } + private bool IsThrottlingJobCompleted { get @@ -274,6 +283,7 @@ internal ThrottlingJob(string command, string jobName, string jobTypeName, int m { _jobResultsThrottlingSemaphore = new SemaphoreSlim(ForwardingHelper.AggregationQueueMaxCapacity); } + _progressActivityId = new Random(this.GetHashCode()).Next(); this.SetupThrottlingQueue(maximumConcurrentChildJobs); @@ -313,6 +323,7 @@ internal void DisableFlowControlForPendingJobsQueue() { return; } + _alreadyDisabledFlowControlForPendingJobsQueue = true; lock (_lockObject) @@ -337,6 +348,7 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() { return; } + _alreadyDisabledFlowControlForPendingCmdletActionsQueue = true; long slotsToRelease = (long)(int.MaxValue / 2) - (long)(_jobResultsThrottlingSemaphore.CurrentCount); @@ -372,10 +384,12 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl { newJobStateInfo = new JobStateInfo(JobState.Running); } + if (ChildJobFlags.CreatesChildJobs == (ChildJobFlags.CreatesChildJobs & flags)) { _setOfChildJobsThatCanAddMoreChildJobs.Add(childJob.InstanceId); } + this.ChildJobs.Add(childJob); _childJobLocations.Add(childJob.Location); _countOfAllChildJobs++; @@ -393,6 +407,7 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl } } } + if (newJobStateInfo != null) { this.SetJobState(newJobStateInfo.State, newJobStateInfo.Reason); @@ -406,6 +421,7 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl { childJob.Results.DataAdded += new EventHandler(childJob_ResultsAdded); } + this.EnqueueReadyToRunChildJob(childJob); this.ReportProgress(minimizeFrequentUpdates: true); @@ -451,6 +467,7 @@ private void WriteWarningAboutHighUsageOfFlowControlBuffers(long currentCount) { return; } + _alreadyWroteFlowControlBuffersHighMemoryUsageWarning = true; } @@ -604,6 +621,7 @@ private void FigureOutIfThrottlingJobIsCompleted() } } } + if (finalJobStateInfo != null) { this.SetJobState(finalJobStateInfo.State, finalJobStateInfo.Reason); @@ -621,6 +639,7 @@ internal void EndOfChildJobs() { _ownerWontSubmitNewChildJobs = true; } + this.FigureOutIfThrottlingJobIsCompleted(); } @@ -678,6 +697,7 @@ private void childJob_StateChanged(object sender, JobStateEventArgs e) parentJobGotUnblocked = true; } } + if (parentJobGotUnblocked) { this.SetJobState(JobState.Running); @@ -692,6 +712,7 @@ private void childJob_StateChanged(object sender, JobStateEventArgs e) { _countOfBlockedChildJobs++; } + this.SetJobState(JobState.Blocked); break; @@ -731,11 +752,13 @@ private void childJob_StateChanged(object sender, JobStateEventArgs e) { this.Results.Add(streamObject); } + this.ChildJobs.Remove(childJob); _setOfChildJobsThatCanAddMoreChildJobs.Remove(childJob.InstanceId); childJob.Dispose(); } } + this.ReportProgress(minimizeFrequentUpdates: !this.IsThrottlingJobCompleted); break; @@ -781,6 +804,7 @@ public override string Location } } } + private readonly HashSet _childJobLocations = new HashSet(StringComparer.OrdinalIgnoreCase); /// @@ -864,15 +888,18 @@ private void StartMonitoringJob(Job job) { return; } + if (_monitoredJobs.Contains(job)) { return; } + _monitoredJobs.Add(job); job.Results.DataAdded += this.MonitoredJobResults_DataAdded; job.StateChanged += MonitoredJob_StateChanged; } + this.AggregateJobResults(job.Results); this.CheckIfMonitoredJobIsComplete(job); } @@ -974,10 +1001,12 @@ private void CheckIfThrottlingJobIsComplete() { resultsToAggregate.Add(registeredJob.Results); } + foreach (Job throttledJob in _throttlingJob.GetChildJobsSnapshot()) { resultsToAggregate.Add(throttledJob.Results); } + resultsToAggregate.Add(_throttlingJob.Results); } @@ -1135,6 +1164,7 @@ private void StopMonitoringAllJobs() { this.StopMonitoringJob(monitoredJob); } + Dbg.Assert(_monitoredJobs.Count == 0, "No monitored jobs should be left after ForwardingHelper is disposed"); if (!_disposed && !_aggregatedResults.IsAddingCompleted) @@ -1179,6 +1209,7 @@ public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet { cancellationTokenRegistration = cancellationToken.Value.Register(helper.CancelForwarding); } + try { Interlocked.MemoryBarrier(); diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index fe9455bb6ff..061ca82d2da 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -144,6 +144,7 @@ internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal { return _remoteRunspacePool; } + set { Dbg.Assert(_remoteRunspacePool == null, @"RunspacePool should be @@ -592,6 +593,7 @@ public void Dispose(bool disposing) _waitHandleForConfigurationReceived.Dispose(); _waitHandleForConfigurationReceived = null; } + ((ClientRemoteSessionDSHandlerImpl)SessionDataStructureHandler).Dispose(); SessionDataStructureHandler = null; _cryptoHelper.Dispose(); diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index ecdec3e7cff..6052a7e0df1 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -98,6 +98,7 @@ private void ProcessEvents() _eventsInProcess = false; break; } + eventArgs = _processPendingEventsQueue.Dequeue(); } @@ -179,6 +180,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e "State can be set to Established only when current state is NegotiationReceived"); SetState(RemoteSessionState.Established, null); } + break; case RemoteSessionEvent.NegotiationReceived: @@ -192,6 +194,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.NegotiationReceived, null); } + break; case RemoteSessionEvent.NegotiationSendCompleted: @@ -201,6 +204,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.NegotiationSent, null); } + break; case RemoteSessionEvent.ConnectFailed: @@ -210,18 +214,21 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.ClosingConnection, eventArgs.Reason); } + break; case RemoteSessionEvent.CloseFailed: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } + break; case RemoteSessionEvent.CloseCompleted: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } + break; case RemoteSessionEvent.KeyRequested: @@ -234,6 +241,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason); } } + break; case RemoteSessionEvent.KeyReceived: @@ -260,6 +268,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e } } } + break; case RemoteSessionEvent.KeySent: @@ -278,6 +287,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ClientDefaultOperationTimeoutMs, Timeout.Infinite); } } + break; case RemoteSessionEvent.DisconnectCompleted: { @@ -289,6 +299,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.Disconnected, eventArgs.Reason); } } + break; case RemoteSessionEvent.DisconnectFailed: { @@ -300,6 +311,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.Disconnected, eventArgs.Reason); //set state to disconnected even TODO. Put some ETW event describing the disconnect process failure } } + break; case RemoteSessionEvent.ReconnectCompleted: { @@ -311,6 +323,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e SetState(RemoteSessionState.Established, eventArgs.Reason); } } + break; } } @@ -508,6 +521,7 @@ internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueue { _processPendingEventsQueue.Clear(); } + _processPendingEventsQueue.Enqueue(arg); if (!_eventsInProcess) diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index 69758949958..dd07a56fc4b 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -174,6 +174,7 @@ private RemotePipeline(RemotePipeline pipeline) : { throw PSTraceSource.NewArgumentNullException("pipeline"); } + if (pipeline._disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); @@ -335,6 +336,7 @@ internal string HistoryString { return _historyString; } + set { _historyString = value; @@ -426,6 +428,7 @@ public override Collection Invoke(System.Collections.IEnumerable input { this.InputStream.Close(); } + InitPowerShell(true); Collection results; @@ -666,6 +669,7 @@ protected override void Dispose(bool disposing) _powershell.Dispose(); _powershell = null; } + _inputCollection.Dispose(); _inputStream.Dispose(); _outputCollection.Dispose(); @@ -746,6 +750,7 @@ private void SetPipelineState(PipelineState state, Exception reason) return; } } + break; case PipelineState.Stopping: { @@ -758,8 +763,10 @@ private void SetPipelineState(PipelineState state, Exception reason) copyState = PipelineState.Stopped; } } + break; } + _pipelineStateInfo = new PipelineStateInfo(copyState, reason); copyStateInfo = _pipelineStateInfo; diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index cfd4a3cdc19..d8305db306a 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -91,6 +91,7 @@ protected bool ByPassRunspaceStateCheck { return _bypassRunspaceStateCheck; } + set { _bypassRunspaceStateCheck = value; @@ -309,6 +310,7 @@ public override PSThreadOptions ThreadOptions } } } + private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// @@ -317,8 +319,10 @@ public override PSThreadOptions ThreadOptions public override RunspaceAvailability RunspaceAvailability { get { return _runspaceAvailability; } + protected set { _runspaceAvailability = value; } } + private RunspaceAvailability _runspaceAvailability = RunspaceAvailability.None; /// @@ -468,6 +472,7 @@ internal ConnectCommandInfo RemoteCommand internal string PSSessionName { get { return RunspacePool.RemoteRunspacePoolInternal.Name; } + set { RunspacePool.RemoteRunspacePoolInternal.Name = value; } } @@ -1139,6 +1144,7 @@ internal void AddToRunningPipelineList(RemotePipeline pipeline) { e.Source = this.ConnectionInfo.ComputerName; } + throw e; } @@ -1247,8 +1253,10 @@ private void HandleRunspacePoolStateChanged(object sender, RunspacePoolStateChan _applicationPrivateData = GetApplicationPrivateData(); SetDebugInfo(_applicationPrivateData); } + break; } + break; case RunspaceState.Disconnected: @@ -1848,6 +1856,7 @@ public RemoteDebugger(RemoteRunspace runspace) { throw new PSArgumentNullException("runspace"); } + _runspace = runspace; _unhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; @@ -2041,6 +2050,7 @@ public override DebuggerStopEventArgs GetDebuggerStopArgs() foreach (var item in output) { if (item == null) { continue; } + rtnArgs = item.BaseObject as DebuggerStopEventArgs; if (rtnArgs != null) { break; } } @@ -2166,6 +2176,7 @@ internal override UnhandledBreakpointProcessingMode UnhandledBreakpointMode { return _unhandledBreakpointMode; } + set { CheckForValidateState(); @@ -2565,6 +2576,7 @@ private void SetIsActive(int breakpointCount) { // Debugger is always inactive if RemoteScript is not selected. if (_isActive) { _isActive = false; } + return; } @@ -2649,6 +2661,7 @@ public override void SetVariable(string name, object value) } else throw; } + if (remotePipeline.Error.Count > 0) { // Don't cache these errors, as they are related to the actual variable being set. @@ -2708,6 +2721,7 @@ public override object GetVariable(string name) } else throw; } + if (remotePipeline.Error.Count > 0) { // Don't cache these errors, as they are related to the actual variable being set. @@ -2876,6 +2890,7 @@ public override PSLanguageMode LanguageMode return (PSLanguageMode)LanguagePrimitives.ConvertTo(result[0], typeof(PSLanguageMode), CultureInfo.InvariantCulture); } + set { throw new PSNotSupportedException(); diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index aec37cdeeb3..064c3dee7f0 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -584,11 +584,13 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg) { StateMachine.RaiseEvent(msgRcvArg); } + break; default: { Dbg.Assert(false, "we should not be encountering this"); } + break; } } @@ -652,12 +654,14 @@ private void ProcessSessionMessages(RemoteDataEventArgs arg) string encryptedSessionKey = RemotingDecoder.GetEncryptedSessionKey(rcvdData.Data); EncryptedSessionKeyReceived.SafeInvoke(this, new RemoteDataEventArgs(encryptedSessionKey)); } + break; case RemotingDataType.PublicKeyRequest: { PublicKeyRequestReceived.SafeInvoke(this, new RemoteDataEventArgs(String.Empty)); } + break; default: From 55aa6504b49b9bc5e2b599fcb96912fd1b998316 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:13 -0800 Subject: [PATCH 69/81] Update commands --- .../remoting/commands/ConnectPSSession.cs | 18 +++ .../remoting/commands/CustomShellCommands.cs | 97 ++++++++++++++++ .../remoting/commands/DisconnectPSSession.cs | 4 + .../commands/EnterPSHostProcessCommand.cs | 2 + .../engine/remoting/commands/GetJob.cs | 7 ++ .../remoting/commands/InvokeCommandCommand.cs | 38 +++++++ .../engine/remoting/commands/JobRepository.cs | 2 + .../commands/NewPSSessionConfigurationFile.cs | 107 ++++++++++++++++++ .../NewPSSessionConfigurationOptionCommand.cs | 42 +++++++ .../commands/NewPSSessionOptionCommand.cs | 30 +++++ .../remoting/commands/PSRemotingCmdlet.cs | 41 +++++++ .../remoting/commands/PushRunspaceCommand.cs | 7 ++ .../engine/remoting/commands/ReceiveJob.cs | 37 ++++++ .../remoting/commands/ReceivePSSession.cs | 22 ++++ .../engine/remoting/commands/RemoveJob.cs | 27 +++++ .../engine/remoting/commands/ResumeJob.cs | 10 ++ .../engine/remoting/commands/StartJob.cs | 26 +++++ .../engine/remoting/commands/StopJob.cs | 13 +++ .../engine/remoting/commands/SuspendJob.cs | 14 +++ .../TestPSSessionConfigurationFile.cs | 2 + .../engine/remoting/commands/WaitJob.cs | 4 + .../remoting/commands/getrunspacecommand.cs | 14 +++ .../remoting/commands/newrunspacecommand.cs | 19 ++++ .../commands/removerunspacecommand.cs | 2 + 24 files changed, 585 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index f66574ff497..a0757103851 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -92,11 +92,13 @@ public class ConnectPSSessionCommand : PSRunspaceCmdlet, IDisposable public string ApplicationName { get { return _appName; } + set { _appName = ResolveAppName(value); } } + private string _appName; /// @@ -115,11 +117,13 @@ public string ApplicationName public string ConfigurationName { get { return _shell; } + set { _shell = ResolveShell(value); } } + private string _shell; /// @@ -145,8 +149,10 @@ public string ConfigurationName public SwitchParameter AllowRedirection { get { return _allowRedirection; } + set { _allowRedirection = value; } } + private bool _allowRedirection = false; /// @@ -164,6 +170,7 @@ public SwitchParameter AllowRedirection public override Guid[] InstanceId { get { return base.InstanceId; } + set { base.InstanceId = value; } } @@ -178,6 +185,7 @@ public override Guid[] InstanceId public override string[] Name { get { return base.Name; } + set { base.Name = value; } } @@ -194,6 +202,7 @@ public override string[] Name public PSCredential Credential { get { return _psCredential; } + set { _psCredential = value; @@ -201,6 +210,7 @@ public PSCredential Credential PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private PSCredential _psCredential; /// @@ -213,6 +223,7 @@ public PSCredential Credential public AuthenticationMechanism Authentication { get { return _authentication; } + set { _authentication = value; @@ -220,6 +231,7 @@ public AuthenticationMechanism Authentication PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private AuthenticationMechanism _authentication; /// @@ -233,6 +245,7 @@ public AuthenticationMechanism Authentication public string CertificateThumbprint { get { return _thumbprint; } + set { _thumbprint = value; @@ -240,6 +253,7 @@ public string CertificateThumbprint PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private string _thumbprint; /// @@ -617,6 +631,7 @@ private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { _retryList.Add(_session); } + writeError = false; } } @@ -710,6 +725,7 @@ private void WriteConnectFailed( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null); } + ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null); Action errorWriter = delegate (Cmdlet cmdlet) { @@ -925,6 +941,7 @@ private Collection GetConnectionObjects() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -947,6 +964,7 @@ private Collection GetConnectionObjects() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index bc2d47acd33..677127f729d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -187,6 +187,7 @@ function Register-PSSessionConfiguration $securityIdentifierToPurge = $_.securityidentifier }} }} + if (([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Local.Equals($accessMode) -or [System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Remote.Equals($accessMode)) -and $haveDisableACE) {{ @@ -194,6 +195,7 @@ function Register-PSSessionConfiguration $sd.DiscretionaryAcl.AddAccess(""deny"", $networkSID, 268435456, ""None"", ""None"") $newSDDL = $sd.GetSddlForm(""all"") }} + if ([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Remote.Equals($accessMode) -and $haveDisableACE) {{ # Remove the specific ACE @@ -284,10 +286,12 @@ function Register-PSSessionConfiguration XmlRenderingType='text' {2} {6} {7} {8} {9} {10}> {3} + {5} + @@ -348,11 +352,13 @@ public PSSessionType SessionType { return sessionType; } + set { sessionType = value; } } + internal PSSessionType sessionType = PSSessionType.DefaultRemoteShell; #endregion @@ -421,6 +427,7 @@ protected override void BeginProcessing() descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, networkSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None); sddl = descriptor.GetSddlForm(AccessControlSections.All); } + break; case PSSessionConfigurationAccessMode.Remote: if (networkDenyAllExists) @@ -446,8 +453,10 @@ protected override void BeginProcessing() SecurityIdentifier iaSidIdentifier = new SecurityIdentifier(InteractiveUsersSID); descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, iaSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None); } + sddl = descriptor.GetSddlForm(AccessControlSections.All); } + break; case PSSessionConfigurationAccessMode.Disabled: break; @@ -1355,6 +1364,7 @@ internal static void MoveWinRmToIsolatedServiceHost(bool forVirtualAccount) { $requiredPrivileges += @('SeTcbPrivilege') } + Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\winrm -Name RequiredPrivileges -Value $requiredPrivileges Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\winrm -Name ObjectName -Value 'LocalSystem'"; } @@ -1476,9 +1486,11 @@ internal static string GetModulePathAsString(object[] modulePath) } } } + sb.Remove(sb.Length - 1, 1); return sb.ToString(); } + return string.Empty; } @@ -1565,6 +1577,7 @@ internal static string ComputeSDDLFromConfiguration( { sddl = PSSessionConfigurationCommandBase.GetRemoteSddl(); } + CommonSecurityDescriptor descriptor = new CommonSecurityDescriptor(false, false, sddl); // Purge all existing access rules so that only role definition principals are granted access. @@ -1573,6 +1586,7 @@ internal static string ComputeSDDLFromConfiguration( { sidsToRemove.Add(ace.SecurityIdentifier); } + foreach (var sidToRemove in sidsToRemove) { descriptor.PurgeAccessControl(sidToRemove); @@ -1691,6 +1705,7 @@ internal static string UpdateSDDLUsersWithGroupConditional( { sb.Append(components[i] + ACESeparator); } + sb.Append(conditionalGroupACE); sb.Append(CloseParenChar); @@ -1736,6 +1751,7 @@ private static Collection ParseDACLACEs( epilogue = string.Empty; return sddlACEs; } + prologue = sddl.Substring(0, index); int sddlLength = sddl.Length; @@ -1797,6 +1813,7 @@ internal static string CreateConditionalACEFromConfig( { throw new PSInvalidOperationException(RemotingErrorIdStrings.RequiredGroupsNotHashTable); } + if (requiredGroupsHash.Count == 0) { return null; @@ -1988,8 +2005,10 @@ internal static string GetRemoteSddl() public string Name { get { return shellName; } + set { shellName = value; } } + internal string shellName; /// @@ -2000,12 +2019,14 @@ public string Name public string AssemblyName { get { return assemblyName; } + set { assemblyName = value; isAssemblyNameSpecified = true; } } + internal string assemblyName; internal bool isAssemblyNameSpecified; @@ -2020,12 +2041,14 @@ public string AssemblyName public string ApplicationBase { get { return applicationBase; } + set { applicationBase = value; isApplicationBaseSpecified = true; } } + internal string applicationBase; internal bool isApplicationBaseSpecified; @@ -2038,12 +2061,14 @@ public string ApplicationBase public string ConfigurationTypeName { get { return configurationTypeName; } + set { configurationTypeName = value; isConfigurationTypeNameSpecified = true; } } + internal string configurationTypeName; internal bool isConfigurationTypeNameSpecified; @@ -2057,12 +2082,14 @@ public PSCredential RunAsCredential { return runAsCredential; } + set { runAsCredential = value; isRunAsCredentialSpecified = true; } } + internal PSCredential runAsCredential; internal bool isRunAsCredentialSpecified; @@ -2085,6 +2112,7 @@ public ApartmentState ThreadApartmentState set { threadAptState = value; } } + internal ApartmentState? threadAptState; #endif @@ -2106,6 +2134,7 @@ public PSThreadOptions ThreadOptions set { threadOptions = value; } } + internal PSThreadOptions? threadOptions; /// @@ -2115,12 +2144,14 @@ public PSThreadOptions ThreadOptions public PSSessionConfigurationAccessMode AccessMode { get { return _accessMode; } + set { _accessMode = value; accessModeSpecified = true; } } + private PSSessionConfigurationAccessMode _accessMode = PSSessionConfigurationAccessMode.Remote; internal bool accessModeSpecified = false; @@ -2134,12 +2165,14 @@ public SwitchParameter UseSharedProcess { return _useSharedProcess; } + set { _useSharedProcess = value; isUseSharedProcessSpecified = true; } } + private bool _useSharedProcess; internal bool isUseSharedProcessSpecified; @@ -2150,12 +2183,14 @@ public SwitchParameter UseSharedProcess public string StartupScript { get { return configurationScript; } + set { configurationScript = value; isConfigurationScriptSpecified = true; } } + internal string configurationScript; internal bool isConfigurationScriptSpecified; @@ -2168,6 +2203,7 @@ public string StartupScript public double? MaximumReceivedDataSizePerCommandMB { get { return maxCommandSizeMB; } + set { if ((value.HasValue) && (value.Value < 0)) @@ -2177,10 +2213,12 @@ public double? MaximumReceivedDataSizePerCommandMB value.Value, "MaximumReceivedDataSizePerCommandMB") ); } + maxCommandSizeMB = value; isMaxCommandSizeMBSpecified = true; } } + internal double? maxCommandSizeMB; internal bool isMaxCommandSizeMBSpecified; @@ -2192,6 +2230,7 @@ public double? MaximumReceivedDataSizePerCommandMB public double? MaximumReceivedObjectSizeMB { get { return maxObjectSizeMB; } + set { if ((value.HasValue) && (value.Value < 0)) @@ -2201,10 +2240,12 @@ public double? MaximumReceivedObjectSizeMB value.Value, "MaximumReceivedObjectSizeMB") ); } + maxObjectSizeMB = value; isMaxObjectSizeMBSpecified = true; } } + internal double? maxObjectSizeMB; internal bool isMaxObjectSizeMBSpecified; @@ -2217,6 +2258,7 @@ public double? MaximumReceivedObjectSizeMB public string SecurityDescriptorSddl { get { return sddl; } + set { if (!string.IsNullOrEmpty(value)) @@ -2235,6 +2277,7 @@ public string SecurityDescriptorSddl isSddlSpecified = true; } } + internal string sddl; internal bool isSddlSpecified; @@ -2245,12 +2288,14 @@ public string SecurityDescriptorSddl public SwitchParameter ShowSecurityDescriptorUI { get { return _showUI; } + set { _showUI = value; showUISpecified = true; } } + private bool _showUI; internal bool showUISpecified; @@ -2263,8 +2308,10 @@ public SwitchParameter ShowSecurityDescriptorUI public SwitchParameter Force { get { return force; } + set { force = value; } } + internal bool force; /// @@ -2276,8 +2323,10 @@ public SwitchParameter Force public SwitchParameter NoServiceRestart { get { return noRestart; } + set { noRestart = value; } } + internal bool noRestart; /// @@ -2291,6 +2340,7 @@ public SwitchParameter NoServiceRestart public Version PSVersion { get { return psVersion; } + set { RemotingCommandUtil.CheckPSVersion(value); @@ -2302,6 +2352,7 @@ public Version PSVersion isPSVersionSpecified = true; } } + internal Version psVersion; internal bool isPSVersionSpecified; @@ -2316,11 +2367,13 @@ public PSSessionTypeOption SessionTypeOption { return sessionTypeOption; } + set { sessionTypeOption = value; } } + internal PSSessionTypeOption sessionTypeOption; /// @@ -2333,11 +2386,13 @@ public PSTransportOption TransportOption { return transportOption; } + set { transportOption = value; } } + internal PSTransportOption transportOption; /// @@ -2352,6 +2407,7 @@ public object[] ModulesToImport { return modulesToImport; } + set { List modulesToImportList = new List(); @@ -2395,6 +2451,7 @@ public object[] ModulesToImport modulePathSpecified = true; } } + internal object[] modulesToImport; internal bool modulePathSpecified = false; @@ -2551,11 +2608,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -2570,11 +2629,13 @@ public SwitchParameter NoServiceRestart { return _noRestart; } + set { _noRestart = value; } } + private bool _noRestart; #endregion @@ -2693,6 +2754,7 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) $s = $s.Replace(""'"", ""'""); $s = $s.Replace(""&"", ""&""); }} + return $s; }} @@ -2849,11 +2911,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; #endregion @@ -2957,6 +3021,7 @@ public sealed class SetPSSessionConfigurationCommand : PSSessionConfigurationCom if (!$value) {{ $value = [string]::empty; }} + set-item -WarningAction SilentlyContinue ('WSMan:\localhost\Plugin\{0}\Quotas\' + $name) -Value $value -confirm:$false }} }} @@ -2984,6 +3049,7 @@ public sealed class SetPSSessionConfigurationCommand : PSSessionConfigurationCom set-item -WarningAction SilentlyContinue 'WSMan:\localhost\Plugin\{0}\UseSharedProcess' -Value $value -confirm:$false $options.Remove(""UseSharedProcess""); }} + foreach($v in $options.GetEnumerator()) {{ $name = $v.Name; $value = $v.Value @@ -3150,6 +3216,7 @@ function Set-RunAsCredential{{ $sd.DiscretionaryAcl.AddAccess(""deny"", $networkSID, 268435456, ""None"", ""None"") $newSDDL = $sd.GetSddlForm(""all"") }} + if ([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Remote.Equals($accessMode) -and $disableNetworkExists) {{ # Remove the specific ACE @@ -3340,6 +3407,7 @@ protected override void BeginProcessing() descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, networkSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None); sddl = descriptor.GetSddlForm(AccessControlSections.All); } + break; case PSSessionConfigurationAccessMode.Remote: if (networkDenyAllExists) @@ -3357,6 +3425,7 @@ protected override void BeginProcessing() sddl = descriptor.GetSddlForm(AccessControlSections.All); } } + break; case PSSessionConfigurationAccessMode.Disabled: break; @@ -3547,6 +3616,7 @@ private void SetRunAs() if (this.runAsCredential == null) { if (string.IsNullOrEmpty(_gmsaAccount)) { return; } + runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(_gmsaAccount); } @@ -3705,6 +3775,7 @@ private void SetSessionConfigurationTypeOptions() { Dbg.Assert(false, "This should never happen. Plugin must exist because caller code has already checked this."); } + PSSessionConfigurationData scd = PSSessionConfigurationData.Create(psObjectCollection[0] == null ? string.Empty : PSSessionConfigurationData.Unescape(psObjectCollection[0].BaseObject.ToString())); PSSessionTypeOption original = sessionTypeOption.ConstructObjectFromPrivateData(scd.PrivateData); original.CopyUpdatedValuesFrom(sessionTypeOption); @@ -3774,6 +3845,7 @@ private void SetSessionConfigurationTypeOptions() { sessionConfigurationData.Append(string.Format(CultureInfo.InvariantCulture, privateDataFormat, privateData)); } + if (sessionConfigurationData.Length > 0) { string sessionConfigData = string.Format(CultureInfo.InvariantCulture, @@ -3810,6 +3882,7 @@ protected override void EndProcessing() string action = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction, this.CommandInfo.Name); WriteWarning(StringUtil.Format(RemotingErrorIdStrings.WinRMRequiresRestart, action)); } + System.Management.Automation.Tracing.Tracer tracer = new System.Management.Automation.Tracing.Tracer(); tracer.EndpointModified(this.Name, WindowsIdentity.GetCurrent().Name); } @@ -3942,6 +4015,7 @@ private PSObject ConstructPropertiesForUpdate() { Dbg.Assert(false, "This should never happen. ps.Invoke always return a Collection"); } + StringBuilder sessionConfigurationData = new StringBuilder(); // SessionConfigurationData doesn't exist in InitializationParameters @@ -4186,6 +4260,7 @@ function Enable-PSSessionConfiguration {{ {0} -force }} + if ($svc.Status -match ""Running"") {{ Restart-Service winrm -force -confirm:$false @@ -4315,11 +4390,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -4334,6 +4411,7 @@ public string SecurityDescriptorSddl { return sddl; } + set { if (!string.IsNullOrEmpty(value)) @@ -4352,6 +4430,7 @@ public string SecurityDescriptorSddl isSddlSpecified = true; } } + internal string sddl; internal bool isSddlSpecified; @@ -4363,8 +4442,10 @@ public string SecurityDescriptorSddl public SwitchParameter SkipNetworkProfileCheck { get { return _skipNetworkProfileCheck; } + set { _skipNetworkProfileCheck = value; } } + private bool _skipNetworkProfileCheck; /// @@ -4376,8 +4457,10 @@ public SwitchParameter SkipNetworkProfileCheck public SwitchParameter NoServiceRestart { get { return _noRestart; } + set { _noRestart = value; } } + private bool _noRestart; #endregion @@ -4595,11 +4678,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -4611,8 +4696,10 @@ public SwitchParameter Force public SwitchParameter NoServiceRestart { get { return _noRestart; } + set { _noRestart = value; } } + private bool _noRestart; #endregion @@ -4752,6 +4839,7 @@ function Copy-PluginToEndpoint {{ $resolvedPluginInstallPath = Resolve-Path $pluginInstallPath }} + if (!(Test-Path $resolvedPluginInstallPath\{5})) {{ Copy-Item -Path $PSHOME\{5} -Destination $resolvedPluginInstallPath -Force -ErrorAction Stop @@ -4761,6 +4849,7 @@ function Copy-PluginToEndpoint return $null }} }} + return $resolvedPluginInstallPath }} @@ -4880,6 +4969,7 @@ function Enable-PSRemoting {{ $powershellVersionMajor += ""-preview"" }} + Register-EndpointIfNotPresent -Name (""PowerShell."" + $powershellVersionMajor) $Force $queryForRegisterDefault $captionForRegisterDefault # PowerShell Workflow and WOW are not supported for PowerShell Core @@ -4915,6 +5005,7 @@ function Enable-PSRemoting # available in processor_architew6432 variable $pa = $env:PROCESSOR_ARCHITEW6432 }} + if ((($pa -eq ""amd64"")) -and (test-path $env:windir\syswow64\pwrshplugin.dll)) {{ # Check availability of WOW64 endpoint. Register if not available. @@ -5088,11 +5179,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -5103,8 +5196,10 @@ public SwitchParameter Force public SwitchParameter SkipNetworkProfileCheck { get { return _skipNetworkProfileCheck; } + set { _skipNetworkProfileCheck = value; } } + private bool _skipNetworkProfileCheck; #endregion @@ -5303,11 +5398,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; #endregion Parameters diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index a2c66f152a4..6ad693519ba 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -67,6 +67,7 @@ public class DisconnectPSSessionCommand : PSRunspaceCmdlet, IDisposable public int IdleTimeoutSec { get { return this.PSSessionOption.IdleTimeout.Seconds; } + set { this.PSSessionOption.IdleTimeout = TimeSpan.FromSeconds(value); } } @@ -80,6 +81,7 @@ public int IdleTimeoutSec public OutputBufferingMode OutputBufferingMode { get { return this.PSSessionOption.OutputBufferingMode; } + set { this.PSSessionOption.OutputBufferingMode = value; } } @@ -109,6 +111,7 @@ private PSSessionOption PSSessionOption return _sessionOption ?? (_sessionOption = new PSSessionOption()); } } + private PSSessionOption _sessionOption; /// @@ -499,6 +502,7 @@ private void WriteDisconnectFailed(Exception e = null) { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, _remoteSession.InstanceId); } + Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, _remoteSession); Action errorWriter = delegate (Cmdlet cmdlet) diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 54bd3e07e39..45b5ba5baa3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -143,6 +143,7 @@ protected override void EndProcessing() Process = GetProcessByHostProcessInfo(HostProcessInfo); break; } + VerifyProcess(Process); // Create named pipe runspace for selected process and open. @@ -697,6 +698,7 @@ private PSHostProcessInfo() { } internal PSHostProcessInfo(string processName, int processId, string appDomainName) { if (string.IsNullOrEmpty(processName)) { throw new PSArgumentNullException("processName"); } + if (string.IsNullOrEmpty(appDomainName)) { throw new PSArgumentNullException("appDomainName"); } #if !CORECLR diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index ea147508cbc..0d686f4d46b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -91,6 +91,7 @@ public override int[] Id { return base.Id; } + set { base.Id = value; @@ -131,12 +132,14 @@ protected List FindJobs() { jobList.AddRange(FindJobsMatchingByName(true, false, true, false)); } + break; case InstanceIdParameterSet: { jobList.AddRange(FindJobsMatchingByInstanceId(true, false, true, false)); } + break; case SessionIdParameterSet: @@ -152,24 +155,28 @@ protected List FindJobs() jobList.AddRange(JobManager.GetJobs(this, true, false, null)); } } + break; case CommandParameterSet: { jobList.AddRange(FindJobsMatchingByCommand(false)); } + break; case StateParameterSet: { jobList.AddRange(FindJobsMatchingByState(false)); } + break; case FilterParameterSet: { jobList.AddRange(FindJobsMatchingByFilter(false)); } + break; default: diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 48dfb87941a..fd21505b8d0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -143,6 +143,7 @@ public override PSSession[] Session { return base.Session; } + set { base.Session = value; @@ -168,6 +169,7 @@ public override string[] ComputerName { return base.ComputerName; } + set { base.ComputerName = value; @@ -202,6 +204,7 @@ public override PSCredential Credential { return base.Credential; } + set { base.Credential = value; @@ -229,6 +232,7 @@ public override int Port { return base.Port; } + set { base.Port = value; @@ -251,6 +255,7 @@ public override SwitchParameter UseSSL { return base.UseSSL; } + set { base.UseSSL = value; @@ -292,6 +297,7 @@ public override string ConfigurationName { return base.ConfigurationName; } + set { base.ConfigurationName = value; @@ -314,6 +320,7 @@ public override string ApplicationName { return base.ApplicationName; } + set { base.ApplicationName = value; @@ -343,6 +350,7 @@ public override int ThrottleLimit { base.ThrottleLimit = value; } + get { return base.ThrottleLimit; @@ -365,6 +373,7 @@ public override Uri[] ConnectionUri { return base.ConnectionUri; } + set { base.ConnectionUri = value; @@ -396,11 +405,13 @@ public SwitchParameter AsJob { return _asjob; } + set { _asjob = value; } } + private bool _asjob = false; /// @@ -415,6 +426,7 @@ public SwitchParameter AsJob public SwitchParameter InDisconnectedSession { get { return InvokeAndDisconnect; } + set { InvokeAndDisconnect = value; } } @@ -429,6 +441,7 @@ public SwitchParameter InDisconnectedSession public string[] SessionName { get { return DisconnectedSessionName; } + set { DisconnectedSessionName = value; } } @@ -455,8 +468,10 @@ public string[] SessionName public SwitchParameter HideComputerName { get { return _hideComputerName; } + set { _hideComputerName = value; } } + private bool _hideComputerName; /// @@ -476,6 +491,7 @@ public string JobName { return _name; } + set { if (!String.IsNullOrEmpty(value)) @@ -485,6 +501,7 @@ public string JobName } } } + private string _name = String.Empty; /// @@ -525,6 +542,7 @@ public override ScriptBlock ScriptBlock { return base.ScriptBlock; } + set { base.ScriptBlock = value; @@ -572,6 +590,7 @@ public override string FilePath { return base.FilePath; } + set { base.FilePath = value; @@ -589,6 +608,7 @@ public override SwitchParameter AllowRedirection { return base.AllowRedirection; } + set { base.AllowRedirection = value; @@ -609,6 +629,7 @@ public override PSSessionOption SessionOption { return base.SessionOption; } + set { base.SessionOption = value; @@ -628,6 +649,7 @@ public override AuthenticationMechanism Authentication { return base.Authentication; } + set { base.Authentication = value; @@ -647,6 +669,7 @@ public override AuthenticationMechanism Authentication public override SwitchParameter EnableNetworkAccess { get { return base.EnableNetworkAccess; } + set { base.EnableNetworkAccess = value; } } @@ -661,6 +684,7 @@ public override SwitchParameter EnableNetworkAccess public override SwitchParameter RunAsAdministrator { get { return base.RunAsAdministrator; } + set { base.RunAsAdministrator = value; } } @@ -677,6 +701,7 @@ public override SwitchParameter RunAsAdministrator public override string[] HostName { get { return base.HostName; } + set { base.HostName = value; } } @@ -689,6 +714,7 @@ public override string[] HostName public override string UserName { get { return base.UserName; } + set { base.UserName = value; } } @@ -702,6 +728,7 @@ public override string UserName public override string KeyFilePath { get { return base.KeyFilePath; } + set { base.KeyFilePath = value; } } @@ -717,6 +744,7 @@ public override string KeyFilePath public override SwitchParameter SSHTransport { get { return base.SSHTransport; } + set { base.SSHTransport = value; } } @@ -981,6 +1009,7 @@ protected override void BeginProcessing() // or not...there is no mix. break; } + ecHelper.ShouldUseSteppablePipelineOnServer = true; } } @@ -1054,6 +1083,7 @@ protected override void ProcessRecord() WriteObject(job); } } + break; case InvokeCommandCommand.SessionParameterSet: @@ -1066,6 +1096,7 @@ protected override void ProcessRecord() this.JobRepository.Add(job); WriteObject(job); } + break; case InvokeCommandCommand.UriParameterSet: @@ -1087,6 +1118,7 @@ protected override void ProcessRecord() WriteObject(job); } } + break; } } @@ -1405,6 +1437,7 @@ private void AddConnectionRetryHandler(PSInvokeExpressionSyncJob job) { return; } + Collection powershells = job.GetPowerShells(); foreach (var ps in powershells) { @@ -1425,6 +1458,7 @@ private void RemoveConnectionRetryHandler(PSInvokeExpressionSyncJob job) { return; } + Collection powershells = job.GetPowerShells(); foreach (var ps in powershells) { @@ -1805,6 +1839,7 @@ private void HandlePipelinesStopped() break; } } + if (retryCanceled && this.Host != null) { @@ -1870,6 +1905,7 @@ private void DetermineThrowStatementBehavior() // in proc parameter set - just return return; } + if (!_asjob) { if (ParameterSetName.Equals(InvokeCommandCommand.ComputerNameParameterSet) || @@ -2075,10 +2111,12 @@ public void StartProgress( { return; } + if (secondsTotal < 1) { return; } + if (string.IsNullOrEmpty(computerName)) { throw new ArgumentNullException("computerName"); diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index e51fc32bae1..4a5141d1037 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -23,6 +23,7 @@ public void Add(T item) { throw new ArgumentNullException(_identifier); } + lock (_syncObject) { Guid instanceId = GetKey(item); @@ -48,6 +49,7 @@ public void Remove(T item) { throw new ArgumentNullException(_identifier); } + lock (_syncObject) { Guid instanceId = GetKey(item); diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 6a0d9fe0337..80419064404 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -37,11 +37,13 @@ public string Path { return _path; } + set { _path = value; } } + private string _path; /// @@ -55,11 +57,13 @@ public Version SchemaVersion { return _schemaVersion; } + set { _schemaVersion = value; } } + private Version _schemaVersion = new Version("2.0.0.0"); /// @@ -72,11 +76,13 @@ public Guid Guid { return _guid; } + set { _guid = value; } } + private Guid _guid = Guid.NewGuid(); /// @@ -89,11 +95,13 @@ public string Author { return _author; } + set { _author = value; } } + private string _author; /// @@ -106,11 +114,13 @@ public string Description { return _description; } + set { _description = value; } } + private string _description; /// @@ -123,11 +133,13 @@ public string CompanyName { return _companyName; } + set { _companyName = value; } } + private string _companyName; /// @@ -140,11 +152,13 @@ public string Copyright { return _copyright; } + set { _copyright = value; } } + private string _copyright; /// @@ -157,11 +171,13 @@ public SessionType SessionType { return _sessionType; } + set { _sessionType = value; } } + private SessionType _sessionType = SessionType.Default; /// @@ -174,11 +190,13 @@ public string TranscriptDirectory { return _transcriptDirectory; } + set { _transcriptDirectory = value; } } + private string _transcriptDirectory = null; /// @@ -244,11 +262,13 @@ public string[] ScriptsToProcess { return _scriptsToProcess; } + set { _scriptsToProcess = value; } } + private string[] _scriptsToProcess = Utils.EmptyArray(); /// @@ -262,11 +282,13 @@ public IDictionary RoleDefinitions { return _roleDefinitions; } + set { _roleDefinitions = value; } } + private IDictionary _roleDefinitions; /// @@ -277,8 +299,10 @@ public IDictionary RoleDefinitions public IDictionary RequiredGroups { get { return _requiredGroups; } + set { _requiredGroups = value; } } + private IDictionary _requiredGroups; /// @@ -291,12 +315,14 @@ public PSLanguageMode LanguageMode { return _languageMode; } + set { _languageMode = value; _isLanguageModeSpecified = true; } } + private PSLanguageMode _languageMode = PSLanguageMode.NoLanguage; private bool _isLanguageModeSpecified; @@ -310,11 +336,13 @@ public ExecutionPolicy ExecutionPolicy { return _executionPolicy; } + set { _executionPolicy = value; } } + private ExecutionPolicy _executionPolicy = ExecutionPolicy.Restricted; /// @@ -327,11 +355,13 @@ public Version PowerShellVersion { return _powerShellVersion; } + set { _powerShellVersion = value; } } + private Version _powerShellVersion; /// @@ -345,11 +375,13 @@ public object[] ModulesToImport { return _modulesToImport; } + set { _modulesToImport = value; } } + private object[] _modulesToImport; /// @@ -363,11 +395,13 @@ public string[] VisibleAliases { return _visibleAliases; } + set { _visibleAliases = value; } } + private string[] _visibleAliases = Utils.EmptyArray(); /// @@ -381,11 +415,13 @@ public Object[] VisibleCmdlets { return _visibleCmdlets; } + set { _visibleCmdlets = value; } } + private Object[] _visibleCmdlets = null; /// @@ -399,11 +435,13 @@ public Object[] VisibleFunctions { return _visibleFunctions; } + set { _visibleFunctions = value; } } + private Object[] _visibleFunctions = null; /// @@ -417,11 +455,13 @@ public string[] VisibleExternalCommands { return _visibleExternalCommands; } + set { _visibleExternalCommands = value; } } + private string[] _visibleExternalCommands = Utils.EmptyArray(); /// @@ -435,11 +475,13 @@ public string[] VisibleProviders { return _visibleProviders; } + set { _visibleProviders = value; } } + private string[] _visibleProviders = Utils.EmptyArray(); /// @@ -453,11 +495,13 @@ public IDictionary[] AliasDefinitions { return _aliasDefinitions; } + set { _aliasDefinitions = value; } } + private IDictionary[] _aliasDefinitions; /// @@ -471,11 +515,13 @@ public IDictionary[] FunctionDefinitions { return _functionDefinitions; } + set { _functionDefinitions = value; } } + private IDictionary[] _functionDefinitions; /// @@ -489,11 +535,13 @@ public object VariableDefinitions { return _variableDefinitions; } + set { _variableDefinitions = value; } } + private object _variableDefinitions; /// @@ -508,11 +556,13 @@ public IDictionary EnvironmentVariables { return _environmentVariables; } + set { _environmentVariables = value; } } + private IDictionary _environmentVariables; /// @@ -526,11 +576,13 @@ public string[] TypesToProcess { return _typesToProcess; } + set { _typesToProcess = value; } } + private string[] _typesToProcess = Utils.EmptyArray(); /// @@ -544,11 +596,13 @@ public string[] FormatsToProcess { return _formatsToProcess; } + set { _formatsToProcess = value; } } + private string[] _formatsToProcess = Utils.EmptyArray(); /// @@ -562,11 +616,13 @@ public string[] AssembliesToLoad { return _assembliesToLoad; } + set { _assembliesToLoad = value; } } + private string[] _assembliesToLoad; /// @@ -638,6 +694,7 @@ protected override void ProcessRecord() { _author = Environment.UserName; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment, SessionConfigurationUtils.QuoteName(_author), streamWriter, false)); @@ -652,6 +709,7 @@ protected override void ProcessRecord() { _companyName = Modules.DefaultCompanyName; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false)); } @@ -663,6 +721,7 @@ protected override void ProcessRecord() { _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, _author); } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false)); } @@ -766,6 +825,7 @@ protected override void ProcessRecord() _languageMode = PSLanguageMode.FullLanguage; } } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, SessionConfigurationUtils.QuoteName(_languageMode), streamWriter, false)); } @@ -787,6 +847,7 @@ protected override void ProcessRecord() isExample = true; _powerShellVersion = PSVersionInfo.PSVersion; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, SessionConfigurationUtils.QuoteName(_powerShellVersion), streamWriter, isExample)); } @@ -1039,6 +1100,7 @@ protected override void ProcessRecord() isExample = true; _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample)); } @@ -1087,11 +1149,13 @@ public string Path { return _path; } + set { _path = value; } } + private string _path; /// @@ -1104,11 +1168,13 @@ public Guid Guid { return _guid; } + set { _guid = value; } } + private Guid _guid = Guid.NewGuid(); /// @@ -1121,11 +1187,13 @@ public string Author { return _author; } + set { _author = value; } } + private string _author; /// @@ -1138,11 +1206,13 @@ public string Description { return _description; } + set { _description = value; } } + private string _description; /// @@ -1155,11 +1225,13 @@ public string CompanyName { return _companyName; } + set { _companyName = value; } } + private string _companyName; /// @@ -1172,11 +1244,13 @@ public string Copyright { return _copyright; } + set { _copyright = value; } } + private string _copyright; /// @@ -1190,11 +1264,13 @@ public object[] ModulesToImport { return _modulesToImport; } + set { _modulesToImport = value; } } + private object[] _modulesToImport; /// @@ -1208,11 +1284,13 @@ public string[] VisibleAliases { return _visibleAliases; } + set { _visibleAliases = value; } } + private string[] _visibleAliases = Utils.EmptyArray(); /// @@ -1226,11 +1304,13 @@ public Object[] VisibleCmdlets { return _visibleCmdlets; } + set { _visibleCmdlets = value; } } + private Object[] _visibleCmdlets = null; /// @@ -1244,11 +1324,13 @@ public Object[] VisibleFunctions { return _visibleFunctions; } + set { _visibleFunctions = value; } } + private Object[] _visibleFunctions = null; /// @@ -1262,11 +1344,13 @@ public string[] VisibleExternalCommands { return _visibleExternalCommands; } + set { _visibleExternalCommands = value; } } + private string[] _visibleExternalCommands = Utils.EmptyArray(); /// @@ -1280,11 +1364,13 @@ public string[] VisibleProviders { return _visibleProviders; } + set { _visibleProviders = value; } } + private string[] _visibleProviders = Utils.EmptyArray(); /// @@ -1298,11 +1384,13 @@ public string[] ScriptsToProcess { return _scriptsToProcess; } + set { _scriptsToProcess = value; } } + private string[] _scriptsToProcess = Utils.EmptyArray(); /// @@ -1316,11 +1404,13 @@ public IDictionary[] AliasDefinitions { return _aliasDefinitions; } + set { _aliasDefinitions = value; } } + private IDictionary[] _aliasDefinitions; /// @@ -1334,11 +1424,13 @@ public IDictionary[] FunctionDefinitions { return _functionDefinitions; } + set { _functionDefinitions = value; } } + private IDictionary[] _functionDefinitions; /// @@ -1352,11 +1444,13 @@ public object VariableDefinitions { return _variableDefinitions; } + set { _variableDefinitions = value; } } + private object _variableDefinitions; /// @@ -1371,11 +1465,13 @@ public IDictionary EnvironmentVariables { return _environmentVariables; } + set { _environmentVariables = value; } } + private IDictionary _environmentVariables; /// @@ -1389,11 +1485,13 @@ public string[] TypesToProcess { return _typesToProcess; } + set { _typesToProcess = value; } } + private string[] _typesToProcess = Utils.EmptyArray(); /// @@ -1407,11 +1505,13 @@ public string[] FormatsToProcess { return _formatsToProcess; } + set { _formatsToProcess = value; } } + private string[] _formatsToProcess = Utils.EmptyArray(); /// @@ -1425,11 +1525,13 @@ public string[] AssembliesToLoad { return _assembliesToLoad; } + set { _assembliesToLoad = value; } } + private string[] _assembliesToLoad; #endregion @@ -1490,6 +1592,7 @@ protected override void ProcessRecord() { _author = Environment.UserName; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment, SessionConfigurationUtils.QuoteName(_author), streamWriter, false)); @@ -1502,6 +1605,7 @@ protected override void ProcessRecord() { _companyName = Modules.DefaultCompanyName; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false)); @@ -1510,6 +1614,7 @@ protected override void ProcessRecord() { _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, _author); } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false)); @@ -1728,6 +1833,7 @@ protected override void ProcessRecord() isExample = true; _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; } + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample)); @@ -2018,6 +2124,7 @@ internal static string CombineHashTableOrStringArray(object[] values, StreamWrit PSArgumentException e = new PSArgumentException(message); caller.ThrowTerminatingError(e.ErrorRecord); } + sb.Append(CombineHashtable(hashVal, writer)); } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs index 2362fbe61a1..5b635ec3468 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs @@ -76,6 +76,7 @@ protected internal override void LoadFromDefaults(PSSessionType sessionType, boo { _outputBufferingMode = DefaultOutputBufferingMode; } + if (!keepAssigned || !_processIdleTimeoutSec.HasValue) { _processIdleTimeoutSec @@ -83,34 +84,42 @@ protected internal override void LoadFromDefaults(PSSessionType sessionType, boo ? DefaultProcessIdleTimeout_ForWorkflow : DefaultProcessIdleTimeout_ForPSRemoting; } + if (!keepAssigned || !_maxIdleTimeoutSec.HasValue) { _maxIdleTimeoutSec = DefaultMaxIdleTimeout; } + if (!keepAssigned || !_idleTimeoutSec.HasValue) { _idleTimeoutSec = DefaultIdleTimeout; } + if (!keepAssigned || !_maxConcurrentUsers.HasValue) { _maxConcurrentUsers = DefaultMaxConcurrentUsers; } + if (!keepAssigned || !_maxProcessesPerSession.HasValue) { _maxProcessesPerSession = DefaultMaxProcessesPerSession; } + if (!keepAssigned || !_maxMemoryPerSessionMB.HasValue) { _maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB; } + if (!keepAssigned || !_maxSessions.HasValue) { _maxSessions = DefaultMaxSessions; } + if (!keepAssigned || !_maxSessionsPerUser.HasValue) { _maxSessionsPerUser = DefaultMaxSessionsPerUser; } + if (!keepAssigned || !_maxConcurrentCommandsPerSession.HasValue) { _maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession; @@ -126,6 +135,7 @@ public int? ProcessIdleTimeoutSec { return _processIdleTimeoutSec; } + internal set { _processIdleTimeoutSec = value; @@ -141,6 +151,7 @@ public int? MaxIdleTimeoutSec { return _maxIdleTimeoutSec; } + internal set { _maxIdleTimeoutSec = value; @@ -156,6 +167,7 @@ public int? MaxSessions { return _maxSessions; } + internal set { _maxSessions = value; @@ -171,6 +183,7 @@ public int? MaxConcurrentCommandsPerSession { return _maxConcurrentCommandsPerSession; } + internal set { _maxConcurrentCommandsPerSession = value; @@ -186,6 +199,7 @@ public int? MaxSessionsPerUser { return _maxSessionsPerUser; } + internal set { _maxSessionsPerUser = value; @@ -201,6 +215,7 @@ public int? MaxMemoryPerSessionMB { return _maxMemoryPerSessionMB; } + internal set { _maxMemoryPerSessionMB = value; @@ -216,6 +231,7 @@ public int? MaxProcessesPerSession { return _maxProcessesPerSession; } + internal set { _maxProcessesPerSession = value; @@ -231,6 +247,7 @@ public int? MaxConcurrentUsers { return _maxConcurrentUsers; } + internal set { _maxConcurrentUsers = value; @@ -246,6 +263,7 @@ public int? IdleTimeoutSec { return _idleTimeoutSec; } + internal set { _idleTimeoutSec = value; @@ -261,6 +279,7 @@ public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferi { return _outputBufferingMode; } + internal set { _outputBufferingMode = value; @@ -275,6 +294,7 @@ internal override Hashtable ConstructQuotasAsHashtable() { quotas[AttribIdleTimeout] = (1000 * _idleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } + if (_maxConcurrentUsers.HasValue) { quotas[AttribMaxConcurrentUsers] = _maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture); @@ -284,26 +304,32 @@ internal override Hashtable ConstructQuotasAsHashtable() { quotas[AttribMaxProcessesPerSession] = _maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture); } + if (_maxMemoryPerSessionMB.HasValue) { quotas[AttribMaxMemoryPerSessionMB] = _maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture); } + if (_maxSessionsPerUser.HasValue) { quotas[AttribMaxSessionsPerUser] = _maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture); } + if (_maxConcurrentCommandsPerSession.HasValue) { quotas[AttribMaxConcurrentCommandsPerSession] = _maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture); } + if (_maxSessions.HasValue) { quotas[AttribMaxSessions] = _maxSessions.Value.ToString(CultureInfo.InvariantCulture); } + if (_maxIdleTimeoutSec.HasValue) { quotas[AttribMaxIdleTimeout] = (1000 * _maxIdleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } + return quotas; } @@ -319,6 +345,7 @@ internal override string ConstructQuotas() { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribIdleTimeout, 1000 * _idleTimeoutSec)); } + if (_maxConcurrentUsers.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, _maxConcurrentUsers)); @@ -328,22 +355,27 @@ internal override string ConstructQuotas() { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, _maxProcessesPerSession)); } + if (_maxMemoryPerSessionMB.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, _maxMemoryPerSessionMB)); } + if (_maxSessionsPerUser.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, _maxSessionsPerUser)); } + if (_maxConcurrentCommandsPerSession.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, _maxConcurrentCommandsPerSession)); } + if (_maxSessions.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, _maxSessions)); } + if (_maxIdleTimeoutSec.HasValue) { // Special case max int value for unbounded default. @@ -416,6 +448,7 @@ public int? MaxIdleTimeoutSec { return _option.MaxIdleTimeoutSec; } + set { _option.MaxIdleTimeoutSec = value; @@ -432,6 +465,7 @@ public int? ProcessIdleTimeoutSec { return _option.ProcessIdleTimeoutSec; } + set { _option.ProcessIdleTimeoutSec = value; @@ -448,6 +482,7 @@ public int? MaxSessions { return _option.MaxSessions; } + set { _option.MaxSessions = value; @@ -464,6 +499,7 @@ public int? MaxConcurrentCommandsPerSession { return _option.MaxConcurrentCommandsPerSession; } + set { _option.MaxConcurrentCommandsPerSession = value; @@ -480,6 +516,7 @@ public int? MaxSessionsPerUser { return _option.MaxSessionsPerUser; } + set { _option.MaxSessionsPerUser = value; @@ -496,6 +533,7 @@ public int? MaxMemoryPerSessionMB { return _option.MaxMemoryPerSessionMB; } + set { _option.MaxMemoryPerSessionMB = value; @@ -512,6 +550,7 @@ public int? MaxProcessesPerSession { return _option.MaxProcessesPerSession; } + set { _option.MaxProcessesPerSession = value; @@ -528,6 +567,7 @@ public int? MaxConcurrentUsers { return _option.MaxConcurrentUsers; } + set { _option.MaxConcurrentUsers = value; @@ -544,6 +584,7 @@ public int? IdleTimeoutSec { return _option.IdleTimeoutSec; } + set { _option.IdleTimeoutSec = value; @@ -560,6 +601,7 @@ public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferi { return _option.OutputBufferingMode; } + set { _option.OutputBufferingMode = value; diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index f0261b32d73..1ee86a3dc7c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -30,8 +30,10 @@ public sealed class NewPSSessionOptionCommand : PSCmdlet public int MaximumRedirection { get { return _maximumRedirection.Value; } + set { _maximumRedirection = value; } } + private int? _maximumRedirection; /// @@ -76,8 +78,10 @@ public int MaximumRedirection public int MaximumReceivedDataSizePerCommand { get { return _maxRecvdDataSizePerCommand.Value; } + set { _maxRecvdDataSizePerCommand = value; } } + private int? _maxRecvdDataSizePerCommand; /// @@ -88,8 +92,10 @@ public int MaximumReceivedDataSizePerCommand public int MaximumReceivedObjectSize { get { return _maxRecvdObjectSize.Value; } + set { _maxRecvdObjectSize = value; } } + private int? _maxRecvdObjectSize; /// @@ -133,8 +139,10 @@ public int OpenTimeout return _openTimeout.HasValue ? _openTimeout.Value : RunspaceConnectionInfo.DefaultOpenTimeout; } + set { _openTimeout = value; } } + private int? _openTimeout; /// @@ -156,8 +164,10 @@ public int CancelTimeout return _cancelTimeout.HasValue ? _cancelTimeout.Value : BaseTransportManager.ClientCloseTimeoutMs; } + set { _cancelTimeout = value; } } + private int? _cancelTimeout; /// @@ -176,8 +186,10 @@ public int IdleTimeout return _idleTimeout.HasValue ? _idleTimeout.Value : RunspaceConnectionInfo.DefaultIdleTimeout; } + set { _idleTimeout = value; } } + private int? _idleTimeout; #endif @@ -227,8 +239,10 @@ public int IdleTimeout public SwitchParameter SkipCACheck { get { return _skipcacheck; } + set { _skipcacheck = value; } } + private bool _skipcacheck; /// @@ -241,8 +255,10 @@ public SwitchParameter SkipCACheck public SwitchParameter SkipCNCheck { get { return _skipcncheck; } + set { _skipcncheck = value; } } + private bool _skipcncheck; #if !UNIX @@ -257,8 +273,10 @@ public SwitchParameter SkipCNCheck public SwitchParameter SkipRevocationCheck { get { return _skiprevocationcheck; } + set { _skiprevocationcheck = value; } } + private bool _skiprevocationcheck; /// @@ -275,8 +293,10 @@ public int OperationTimeout return (_operationtimeout.HasValue ? _operationtimeout.Value : BaseTransportManager.ClientDefaultOperationTimeoutMs); } + set { _operationtimeout = value; } } + private int? _operationtimeout; /// @@ -289,11 +309,13 @@ public int OperationTimeout public SwitchParameter NoEncryption { get { return _noencryption; } + set { _noencryption = value; } } + private bool _noencryption; /// @@ -306,11 +328,13 @@ public SwitchParameter NoEncryption public SwitchParameter UseUTF16 { get { return _useutf16; } + set { _useutf16 = value; } } + private bool _useutf16; /// @@ -321,8 +345,10 @@ public SwitchParameter UseUTF16 public SwitchParameter IncludePortInSPN { get { return _includePortInSPN; } + set { _includePortInSPN = value; } } + private bool _includePortInSPN; #endif @@ -351,6 +377,7 @@ protected override void BeginProcessing() { result.OperationTimeout = TimeSpan.FromMilliseconds(_operationtimeout.Value); } + result.NoEncryption = this.NoEncryption; result.UseUTF16 = this.UseUTF16; result.IncludePortInSPN = this.IncludePortInSPN; @@ -370,6 +397,7 @@ protected override void BeginProcessing() { result.Culture = this.Culture; } + if (this.UICulture != null) { result.UICulture = this.UICulture; @@ -379,10 +407,12 @@ protected override void BeginProcessing() { result.OpenTimeout = TimeSpan.FromMilliseconds(_openTimeout.Value); } + if (_cancelTimeout.HasValue) { result.CancelTimeout = TimeSpan.FromMilliseconds(_cancelTimeout.Value); } + if (_idleTimeout.HasValue) { result.IdleTimeout = TimeSpan.FromMilliseconds(_idleTimeout.Value); diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 53c0bb56af4..3832e9b6481 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -137,6 +137,7 @@ internal string GetMessage(string resourceString, params object[] args) { message = resourceString; } + return message; } @@ -522,6 +523,7 @@ public virtual PSCredential Credential { return _pscredential; } + set { _pscredential = value; @@ -592,6 +594,7 @@ public virtual string ApplicationName { return _appName; } + set { _appName = ResolveAppName(value); @@ -631,8 +634,10 @@ public virtual string ApplicationName public virtual SwitchParameter AllowRedirection { get { return _allowRedirection; } + set { _allowRedirection = value; } } + private bool _allowRedirection = false; /// @@ -654,11 +659,13 @@ public virtual PSSessionOption SessionOption _sessionOption = new PSSessionOption(); } } + return _sessionOption; } set { _sessionOption = value; } } + private PSSessionOption _sessionOption; internal const string DEFAULT_SESSION_OPTION = "PSSessionOption"; @@ -674,6 +681,7 @@ public virtual AuthenticationMechanism Authentication { return _authMechanism; } + set { _authMechanism = value; @@ -681,6 +689,7 @@ public virtual AuthenticationMechanism Authentication ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private AuthenticationMechanism _authMechanism = AuthenticationMechanism.Default; /// @@ -692,12 +701,14 @@ public virtual AuthenticationMechanism Authentication public virtual string CertificateThumbprint { get { return _thumbPrint; } + set { _thumbPrint = value; ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private string _thumbPrint = null; #region SSHHostParameters @@ -857,6 +868,7 @@ protected void ParseSshHostName(string hostname, out string host, out string use { userName = uri.UserInfo; } + if (uri.Port != -1) { port = uri.Port; @@ -908,6 +920,7 @@ internal SSHConnection[] ParseSSHConnectionHashTable() { connectionInfo.UserName = userName; } + if (port != -1) { connectionInfo.Port = port; @@ -1165,11 +1178,13 @@ public virtual ScriptBlock ScriptBlock { return _scriptBlock; } + set { _scriptBlock = value; } } + private ScriptBlock _scriptBlock; /// @@ -1193,11 +1208,13 @@ public virtual string FilePath { return _filePath; } + set { _filePath = value; } } + private string _filePath; /// @@ -1217,11 +1234,13 @@ public virtual Object[] ArgumentList { return _args; } + set { _args = value; } } + private Object[] _args; /// @@ -1352,6 +1371,7 @@ protected virtual void CreateHelpersForSpecifiedComputerNames() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -2034,6 +2054,7 @@ protected override void BeginProcessing() CreateHelpersForSpecifiedComputerNames(); } + break; case PSExecutionCmdlet.SSHHostParameterSet: @@ -2045,6 +2066,7 @@ protected override void BeginProcessing() CreateHelpersForSpecifiedSSHComputerNames(); } + break; case PSExecutionCmdlet.SSHHostHashParameterSet: @@ -2052,6 +2074,7 @@ protected override void BeginProcessing() { CreateHelpersForSpecifiedSSHHashComputerNames(); } + break; case PSExecutionCmdlet.FilePathSessionParameterSet: @@ -2061,6 +2084,7 @@ protected override void BeginProcessing() CreateHelpersForSpecifiedRunspaces(); } + break; case PSExecutionCmdlet.FilePathUriParameterSet: @@ -2068,6 +2092,7 @@ protected override void BeginProcessing() { CreateHelpersForSpecifiedUris(); } + break; case PSExecutionCmdlet.VMIdParameterSet: @@ -2077,6 +2102,7 @@ protected override void BeginProcessing() { CreateHelpersForSpecifiedVMSession(); } + break; case PSExecutionCmdlet.ContainerIdParameterSet: @@ -2084,6 +2110,7 @@ protected override void BeginProcessing() { CreateHelpersForSpecifiedContainerSession(); } + break; } } @@ -2126,6 +2153,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv2() break; } } + if (_powershellV2 != null) { return _powershellV2; } } @@ -2381,6 +2409,7 @@ private List GetUsingVariables(ScriptBlock localScriptBlo { throw new ArgumentNullException("localScriptBlock", "Caller needs to make sure the parameter value is not null"); } + var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(localScriptBlock.Ast); return allUsingExprs.Select(usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); } @@ -2429,6 +2458,7 @@ public virtual Guid[] InstanceId { return _remoteRunspaceIds; } + set { _remoteRunspaceIds = value; @@ -2460,6 +2490,7 @@ public virtual string[] Name { return _names; } + set { _names = value; @@ -2484,6 +2515,7 @@ public virtual string[] ComputerName { return _computerNames; } + set { _computerNames = value; @@ -3179,6 +3211,7 @@ internal Pipeline Pipeline return pipeline; } } + protected Pipeline pipeline; /// @@ -3192,6 +3225,7 @@ internal Exception InternalException return internalException; } } + protected Exception internalException; /// @@ -3289,6 +3323,7 @@ internal override void StartOperation() rPipeline.SetIsNested(true); rPipeline.SetIsSteppable(true); } + pipeline.InvokeAsync(); } catch (InvalidRunspaceStateException e) @@ -3542,12 +3577,14 @@ private void HandleRunspaceStateChanged(object sender, RemoteRunspace.CloseAsync(); } } + break; case RunspaceState.Broken: { RaiseOperationCompleteEvent(stateEventArgs); } + break; case RunspaceState.Closed: { @@ -3562,6 +3599,7 @@ private void HandleRunspaceStateChanged(object sender, RaiseOperationCompleteEvent(); } } + break; } } @@ -3590,6 +3628,7 @@ private void HandlePipelineStateChanged(object sender, { RemoteRunspace.CloseAsync(); } + break; } } @@ -4295,6 +4334,7 @@ public PSSessionOption() public AuthenticationMechanism ProxyAuthentication { get { return _proxyAuthentication; } + set { switch (value) @@ -4314,6 +4354,7 @@ public AuthenticationMechanism ProxyAuthentication } } } + private AuthenticationMechanism _proxyAuthentication = AuthenticationMechanism.Negotiate; /// diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index d476c0edd7a..cae860994ed 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -38,6 +38,7 @@ public class EnterPSSessionCommand : PSRemotingBaseCmdlet /// Disable ThrottleLimit parameter inherited from base class. /// public new int ThrottleLimit { set { } get { return 0; } } + private ObjectStream _stream; private RemoteRunspace _tempRunspace; @@ -153,6 +154,7 @@ public class EnterPSSessionCommand : PSRemotingBaseCmdlet public override PSCredential Credential { get { return base.Credential; } + set { base.Credential = value; } } @@ -542,6 +544,7 @@ protected override void StopProcessing() remoteRunspace.CloseAsync(); } catch (InvalidRunspaceStateException) { } + return; } @@ -556,6 +559,7 @@ protected override void StopProcessing() null)); return; } + host.PopRunspace(); } @@ -739,6 +743,7 @@ private RemoteRunspace CreateRunspaceWhenUriParameterSpecified() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = EnableNetworkAccess; @@ -897,6 +902,7 @@ private bool IsParameterSetForVMContainerSession() { remoteRunspace = (RemoteRunspace)this.Session.Runspace; } + break; case InstanceIdParameterSet: @@ -1167,6 +1173,7 @@ private void SetRunspacePrompt(RemoteRunspace remoteRunspace) { targetName = remoteRunspace.ConnectionInfo.ComputerName; } + break; default: diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index 269d84f4ead..0c6fef6d830 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -84,11 +84,13 @@ public Job[] Job { return _jobs; } + set { _jobs = value; } } + private Job[] _jobs; /// @@ -107,11 +109,13 @@ public string[] ComputerName { return _computerNames; } + set { _computerNames = value; } } + private string[] _computerNames; /// @@ -129,11 +133,13 @@ public string[] Location { return _locations; } + set { _locations = value; } } + private string[] _locations; /// @@ -151,11 +157,13 @@ public PSSession[] Session { return _remoteRunspaceInfos; } + set { _remoteRunspaceInfos = value; } } + private PSSession[] _remoteRunspaceInfos; /// @@ -169,12 +177,14 @@ public SwitchParameter Keep { return !_flush; } + set { _flush = !value; ValidateWait(); } } + private bool _flush = true; /// @@ -186,11 +196,13 @@ public SwitchParameter NoRecurse { return !_recurse; } + set { _recurse = !value; } } + private bool _recurse = true; /// @@ -239,6 +251,7 @@ public SwitchParameter Wait { return _wait; } + set { _wait = value; @@ -255,6 +268,7 @@ public SwitchParameter AutoRemoveJob { return _autoRemoveJob; } + set { _autoRemoveJob = value; @@ -267,6 +281,7 @@ public SwitchParameter AutoRemoveJob public SwitchParameter WriteEvents { get { return _writeStateChangedEvents; } + set { _writeStateChangedEvents = value; @@ -279,6 +294,7 @@ public SwitchParameter WriteEvents public SwitchParameter WriteJobInResults { get { return _outputJobFirst; } + set { _outputJobFirst = value; @@ -358,6 +374,7 @@ protected override void ProcessRecord() } } } + break; case ComputerNameParameterSet: @@ -393,6 +410,7 @@ protected override void ProcessRecord() } } } + break; case "Location": @@ -417,6 +435,7 @@ protected override void ProcessRecord() } } } + break; case ReceiveJobCommand.InstanceIdParameterSet: @@ -427,6 +446,7 @@ protected override void ProcessRecord() checkForRecurse = true; //WriteResultsForJobsInCollection(jobs, true); } + break; case ReceiveJobCommand.SessionIdParameterSet: @@ -436,6 +456,7 @@ protected override void ProcessRecord() checkForRecurse = true; //WriteResultsForJobsInCollection(jobs, true); } + break; case ReceiveJobCommand.NameParameterSet: @@ -445,6 +466,7 @@ protected override void ProcessRecord() checkForRecurse = true; //WriteResultsForJobsInCollection(jobs, true); } + break; } @@ -646,6 +668,7 @@ protected void Dispose(bool disposing) job.Debug.DataAdded -= Debug_DataAdded; job.Information.DataAdded -= Information_DataAdded; } + job.StateChanged -= HandleJobStateChanged; } } @@ -911,6 +934,7 @@ private Collection ReadAll(PSDataCollection psDataCollection) { collection.Add(t); } + return collection; } @@ -928,6 +952,7 @@ private void WriteJobResultsRecursivelyHelper(Hashtable duplicate, Job job, bool { return; } + duplicate.Add(job, job); //Write the results of child jobs @@ -1053,6 +1078,7 @@ private void ResultsAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); PSDataCollection results = sender as PSDataCollection; @@ -1092,6 +1118,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) return; } } + if (e.JobStateInfo.State == JobState.Blocked) { DoUnblockJob(job); @@ -1122,6 +1149,7 @@ private void Progress_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1148,6 +1176,7 @@ private void Error_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1174,6 +1203,7 @@ private void Debug_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1200,6 +1230,7 @@ private void Warning_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1226,6 +1257,7 @@ private void Verbose_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1252,6 +1284,7 @@ private void Information_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1278,6 +1311,7 @@ private void Output_DataAdded(object sender, DataAddedEventArgs e) { if (_isDisposed) return; } + _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try @@ -1312,6 +1346,7 @@ private T GetData(PSDataCollection collection, int index) // the data got written return default(T); } + return collection[index]; } @@ -1352,6 +1387,7 @@ private void StopAggregateResultsFromJob(Job job) job.Debug.DataAdded -= Debug_DataAdded; job.Information.DataAdded -= Information_DataAdded; } + job.StateChanged -= HandleJobStateChanged; } @@ -1368,6 +1404,7 @@ private void AutoRemoveJobIfRequired(Job job) _tracer.WriteMessage(ClassNameTrace, "AutoRemoveJobIfRequired", Guid.Empty, job, "Job has data and is being removed."); } + Job2 job2 = job as Job2; if (job2 != null) { diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index 4aa1ff9363d..f107aacbe4e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -124,11 +124,13 @@ public class ReceivePSSessionCommand : PSRemotingCmdlet public string ApplicationName { get { return _appName; } + set { _appName = ResolveAppName(value); } } + private string _appName; /// @@ -147,11 +149,13 @@ public string ApplicationName public string ConfigurationName { get { return _shell; } + set { _shell = ResolveShell(value); } } + private string _shell; /// @@ -176,8 +180,10 @@ public string ConfigurationName public SwitchParameter AllowRedirection { get { return _allowRedirection; } + set { _allowRedirection = value; } } + private bool _allowRedirection = false; /// @@ -250,6 +256,7 @@ public SwitchParameter AllowRedirection public PSCredential Credential { get { return _psCredential; } + set { _psCredential = value; @@ -257,6 +264,7 @@ public PSCredential Credential PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private PSCredential _psCredential; /// @@ -269,6 +277,7 @@ public PSCredential Credential public AuthenticationMechanism Authentication { get { return _authentication; } + set { _authentication = value; @@ -276,6 +285,7 @@ public AuthenticationMechanism Authentication PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private AuthenticationMechanism _authentication; /// @@ -289,6 +299,7 @@ public AuthenticationMechanism Authentication public string CertificateThumbprint { get { return _thumbprint; } + set { _thumbprint = value; @@ -296,6 +307,7 @@ public string CertificateThumbprint PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private string _thumbprint; /// @@ -559,6 +571,7 @@ private WSManConnectionInfo GetConnectionObject() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); } @@ -574,6 +587,7 @@ private WSManConnectionInfo GetConnectionObject() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); } @@ -827,12 +841,14 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) // Reconnect the job object and stream data to host. lock (_syncObject) { _job = job; _stopPipelineReceive = new ManualResetEvent(false); } + using (_stopPipelineReceive) using (job) { Job childJob = job.ChildJobs[0]; job.ConnectJobs(); if (CheckForDebugMode(session, true)) { return; } + do { // Retrieve and display results from child job as they become @@ -857,6 +873,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) } while (!job.IsFinishedState(job.JobStateInfo.State)); } + lock (_syncObject) { _job = null; _stopPipelineReceive = null; } return; @@ -878,6 +895,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) _remotePipeline = (RemotePipeline)session.Runspace.CreateDisconnectedPipeline(); _stopPipelineReceive = new ManualResetEvent(false); } + using (_stopPipelineReceive) { using (_remotePipeline) @@ -899,6 +917,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) _remotePipeline.ConnectAsync(); pipelineConnectedEvent.WaitOne(); } + pipelineConnectedEvent = null; if (CheckForDebugMode(session, true)) { return; } @@ -997,6 +1016,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) } } } + lock (_syncObject) { _remotePipeline = null; _stopPipelineReceive = null; } } @@ -1020,10 +1040,12 @@ private void WriteRemoteObject( { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, session.ComputerName)); } + if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] == null) { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, session.InstanceId)); } + if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true)); diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 07506b5bb46..bfab391aac1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -135,6 +135,7 @@ private bool FindJobsMatchingByNameHelper(List matches, IList jobsToSe { continue; } + duplicateDetector.Add(job.Id, job.Id); // check if the job is available in any of the @@ -212,6 +213,7 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, matches.Add(job2); } } + jobFound = jobFound || job2Found; if (jobFound || !writeErrorOnNoMatch) continue; @@ -263,6 +265,7 @@ private bool FindJobsMatchingByInstanceIdHelper(List matches, IList jo { matches.Add(job); } + break; } } @@ -324,6 +327,7 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b matches.Add(job2); } } + jobFound = jobFound || job2Found; if (jobFound || !writeErrorOnNoMatch) continue; @@ -441,6 +445,7 @@ internal List FindJobsMatchingByCommand( } } } + return matches; } @@ -481,6 +486,7 @@ internal List FindJobsMatchingByState( matches.Add(job); } } + return matches; } @@ -523,6 +529,7 @@ internal List FindJobsMatchingByFilter(bool writeobject) matches.Add(job); } } + return matches; } @@ -566,6 +573,7 @@ internal List CopyJobsToList(Job[] jobs, bool writeobject, bool checkIfJobC } } } + return matches; } @@ -605,6 +613,7 @@ public string[] Name { return _names; } + set { _names = value; @@ -629,6 +638,7 @@ public Guid[] InstanceId { return _instanceIds; } + set { _instanceIds = value; @@ -654,6 +664,7 @@ public virtual int[] Id { return _sessionIds; } + set { _sessionIds = value; @@ -676,6 +687,7 @@ public virtual JobState State { return _jobstate; } + set { _jobstate = value; @@ -698,6 +710,7 @@ public virtual string[] Command { return _commands; } + set { _commands = value; @@ -719,6 +732,7 @@ public virtual string[] Command public virtual Hashtable Filter { get { return _filter; } + set { _filter = value; } } @@ -776,11 +790,13 @@ public Job[] Job { return _jobs; } + set { _jobs = value; } } + private Job[] _jobs; /// @@ -798,11 +814,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force = false; #endregion Parameters @@ -822,42 +840,49 @@ protected override void ProcessRecord() { listOfJobsToRemove = FindJobsMatchingByName(false, false, true, !_force); } + break; case InstanceIdParameterSet: { listOfJobsToRemove = FindJobsMatchingByInstanceId(true, false, true, !_force); } + break; case SessionIdParameterSet: { listOfJobsToRemove = FindJobsMatchingBySessionId(true, false, true, !_force); } + break; case CommandParameterSet: { listOfJobsToRemove = FindJobsMatchingByCommand(false); } + break; case StateParameterSet: { listOfJobsToRemove = FindJobsMatchingByState(false); } + break; case FilterParameterSet: { listOfJobsToRemove = FindJobsMatchingByFilter(false); } + break; default: { listOfJobsToRemove = CopyJobsToList(_jobs, false, !_force); } + break; } @@ -971,6 +996,7 @@ private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs event { _pendingJobs.Remove(job.InstanceId); } + if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } @@ -1014,6 +1040,7 @@ protected void Dispose(bool disposing) { pair.Key.StopJobCompleted -= pair.Value; } + _waitForJobs.Dispose(); } #endregion Dispose diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs index 7ab03da3671..58e4c97b7c0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs @@ -41,11 +41,13 @@ public Job[] Job { return _jobs; } + set { _jobs = value; } } + private Job[] _jobs; /// @@ -83,36 +85,42 @@ protected override void ProcessRecord() { jobsToResume = FindJobsMatchingByName(true, false, true, false); } + break; case InstanceIdParameterSet: { jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); } + break; case SessionIdParameterSet: { jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); } + break; case StateParameterSet: { jobsToResume = FindJobsMatchingByState(false); } + break; case FilterParameterSet: { jobsToResume = FindJobsMatchingByFilter(false); } + break; default: { jobsToResume = CopyJobsToList(_jobs, false, false); } + break; } @@ -203,6 +211,7 @@ var e in { _pendingJobs.Remove(job.InstanceId); } + if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } @@ -263,6 +272,7 @@ protected void Dispose(bool disposing) { pair.Key.ResumeJobCompleted -= pair.Value; } + _waitForJobs.Dispose(); } #endregion Dispose diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index cce654b99fe..358dd3be5aa 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -40,8 +40,10 @@ public class StartJobCommand : PSExecutionCmdlet, IDisposable public string DefinitionName { get { return _definitionName; } + set { _definitionName = value; } } + private string _definitionName; /// @@ -53,8 +55,10 @@ public string DefinitionName public string DefinitionPath { get { return _definitionPath; } + set { _definitionPath = value; } } + private string _definitionPath; /// @@ -67,8 +71,10 @@ public string DefinitionPath public string Type { get { return _definitionType; } + set { _definitionType = value; } } + private string _definitionType; /// @@ -86,6 +92,7 @@ public virtual string Name { return _name; } + set { if (!String.IsNullOrEmpty(value)) @@ -94,6 +101,7 @@ public virtual string Name } } } + private string _name; /// @@ -115,6 +123,7 @@ public override ScriptBlock ScriptBlock { return base.ScriptBlock; } + set { base.ScriptBlock = value; @@ -203,6 +212,7 @@ public override PSCredential Credential { return base.Credential; } + set { base.Credential = value; @@ -240,6 +250,7 @@ public override string ConfigurationName { return base.ConfigurationName; } + set { base.ConfigurationName = value; @@ -293,6 +304,7 @@ public override string FilePath { return base.FilePath; } + set { base.FilePath = value; @@ -313,6 +325,7 @@ public string LiteralPath { return base.FilePath; } + set { base.FilePath = value; @@ -332,6 +345,7 @@ public override AuthenticationMechanism Authentication { return base.Authentication; } + set { base.Authentication = value; @@ -347,6 +361,7 @@ public override string CertificateThumbprint { return base.CertificateThumbprint; } + set { base.CertificateThumbprint = value; @@ -422,6 +437,7 @@ public override PSSessionOption SessionOption { return base.SessionOption; } + set { base.SessionOption = value; @@ -441,8 +457,10 @@ public override PSSessionOption SessionOption public virtual ScriptBlock InitializationScript { get { return _initScript; } + set { _initScript = value; } } + private ScriptBlock _initScript; /// @@ -455,8 +473,10 @@ public virtual ScriptBlock InitializationScript public virtual SwitchParameter RunAs32 { get { return _shouldRunAs32; } + set { _shouldRunAs32 = value; } } + private bool _shouldRunAs32; /// @@ -469,6 +489,7 @@ public virtual SwitchParameter RunAs32 public virtual Version PSVersion { get { return _psVersion; } + set { RemotingCommandUtil.CheckPSVersion(value); @@ -479,6 +500,7 @@ public virtual Version PSVersion _psVersion = value; } } + private Version _psVersion; /// @@ -494,6 +516,7 @@ public virtual Version PSVersion public override PSObject InputObject { get { return base.InputObject; } + set { base.InputObject = value; } } @@ -509,6 +532,7 @@ public override PSObject InputObject public override Object[] ArgumentList { get { return base.ArgumentList; } + set { base.ArgumentList = value; } } @@ -623,6 +647,7 @@ protected override void ProcessRecord() resolvedPath = paths[0]; } + List jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false); if (jobs.Count == 0) @@ -679,6 +704,7 @@ protected override void ProcessRecord() } } } + private bool _firstProcessRecord = true; /// diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index f8ad4d8b49d..6e937101b7f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -38,11 +38,13 @@ public Job[] Job { return _jobs; } + set { _jobs = value; } } + private Job[] _jobs; /// @@ -55,11 +57,13 @@ public SwitchParameter PassThru { return _passThru; } + set { _passThru = value; } } + private bool _passThru; /// @@ -90,36 +94,42 @@ protected override void ProcessRecord() { jobsToStop = FindJobsMatchingByName(true, false, true, false); } + break; case InstanceIdParameterSet: { jobsToStop = FindJobsMatchingByInstanceId(true, false, true, false); } + break; case SessionIdParameterSet: { jobsToStop = FindJobsMatchingBySessionId(true, false, true, false); } + break; case StateParameterSet: { jobsToStop = FindJobsMatchingByState(false); } + break; case FilterParameterSet: { jobsToStop = FindJobsMatchingByFilter(false); } + break; default: { jobsToStop = CopyJobsToList(_jobs, false, false); } + break; } @@ -132,6 +142,7 @@ protected override void ProcessRecord() { continue; } + string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); @@ -226,6 +237,7 @@ var e in { _pendingJobs.Remove(job.InstanceId); } + if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } @@ -272,6 +284,7 @@ protected void Dispose(bool disposing) { pair.Key.StopJobCompleted -= pair.Value; } + _waitForJobs.Dispose(); } #endregion Dispose diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs index 9b72594cbf2..331ce56a53e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs @@ -41,11 +41,13 @@ public Job[] Job { return _jobs; } + set { _jobs = value; } } + private Job[] _jobs; /// @@ -74,11 +76,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force = false; /// @@ -90,11 +94,13 @@ public SwitchParameter Wait { return _wait; } + set { _wait = value; } } + private bool _wait = false; #endregion Parameters @@ -115,36 +121,42 @@ protected override void ProcessRecord() { jobsToSuspend = FindJobsMatchingByName(true, false, true, false); } + break; case InstanceIdParameterSet: { jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false); } + break; case SessionIdParameterSet: { jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false); } + break; case StateParameterSet: { jobsToSuspend = FindJobsMatchingByState(false); } + break; case FilterParameterSet: { jobsToSuspend = FindJobsMatchingByFilter(false); } + break; default: { jobsToSuspend = CopyJobsToList(_jobs, false, false); } + break; } @@ -262,6 +274,7 @@ private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job) // so if job doesn't present in the _pendingJobs then just return return; } + if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } @@ -353,6 +366,7 @@ protected void Dispose(bool disposing) { pair.Key.SuspendJobCompleted -= pair.Value; } + _waitForJobs.Dispose(); } #endregion Dispose diff --git a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs index fe18cb68b5f..7f804628beb 100644 --- a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs @@ -29,8 +29,10 @@ public class TestPSSessionConfigurationFileCommand : PSCmdlet public string Path { get { return _path; } + set { _path = value; } } + private string _path; #endregion diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 9a95abfcb81..cd338571497 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -52,11 +52,13 @@ public int Timeout { return _timeoutInSeconds; } + set { _timeoutInSeconds = value; } } + private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. /// @@ -155,6 +157,7 @@ private void HandleJobStateChangedEvent(object source, JobStateEventArgs eventAr { _warnNotTerminal = true; } + _finishedJobs.Add(job); } else @@ -235,6 +238,7 @@ private List GetFinishedJobs() { jobsToOutput = _jobsToWaitFor.Where(j => ((!Force && j.IsPersistentState(j.JobStateInfo.State)) || (Force && j.IsFinishedState(j.JobStateInfo.State)))).ToList(); } + return jobsToOutput; } diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index 79add865e38..9d6e1119c9f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -78,11 +78,13 @@ public class GetPSSessionCommand : PSRunspaceCmdlet, IDisposable public string ApplicationName { get { return _appName; } + set { _appName = ResolveAppName(value); } } + private string _appName; /// @@ -139,8 +141,10 @@ public string ApplicationName public SwitchParameter AllowRedirection { get { return _allowRedirection; } + set { _allowRedirection = value; } } + private bool _allowRedirection = false; /// @@ -157,6 +161,7 @@ public SwitchParameter AllowRedirection public override string[] Name { get { return base.Name; } + set { base.Name = value; } } @@ -180,6 +185,7 @@ public override string[] Name public override Guid[] InstanceId { get { return base.InstanceId; } + set { base.InstanceId = value; } } @@ -196,6 +202,7 @@ public override Guid[] InstanceId public PSCredential Credential { get { return _psCredential; } + set { _psCredential = value; @@ -203,6 +210,7 @@ public PSCredential Credential PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private PSCredential _psCredential; /// @@ -215,6 +223,7 @@ public PSCredential Credential public AuthenticationMechanism Authentication { get { return _authentication; } + set { _authentication = value; @@ -222,6 +231,7 @@ public AuthenticationMechanism Authentication PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private AuthenticationMechanism _authentication; /// @@ -235,6 +245,7 @@ public AuthenticationMechanism Authentication public string CertificateThumbprint { get { return _thumbprint; } + set { _thumbprint = value; @@ -242,6 +253,7 @@ public string CertificateThumbprint PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } + private string _thumbprint; /// @@ -434,6 +446,7 @@ private Collection GetConnectionObjects() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -456,6 +469,7 @@ private Collection GetConnectionObjects() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index ade58912754..1f524812d87 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -91,6 +91,7 @@ public class NewPSSessionCommand : PSRemotingBaseCmdlet, IDisposable public override PSCredential Credential { get { return base.Credential; } + set { base.Credential = value; @@ -112,11 +113,13 @@ public override PSSession[] Session { return _remoteRunspaceInfos; } + set { _remoteRunspaceInfos = value; } } + private PSSession[] _remoteRunspaceInfos; /// @@ -207,18 +210,21 @@ protected override void ProcessRecord() { remoteRunspaces = CreateRunspacesWhenRunspaceParameterSpecified(); } + break; case "Uri": { remoteRunspaces = CreateRunspacesWhenUriParameterSpecified(); } + break; case NewPSSessionCommand.ComputerNameParameterSet: { remoteRunspaces = CreateRunspacesWhenComputerNameParameterSpecified(); } + break; case NewPSSessionCommand.VMIdParameterSet: @@ -226,24 +232,28 @@ protected override void ProcessRecord() { remoteRunspaces = CreateRunspacesWhenVMParameterSpecified(); } + break; case NewPSSessionCommand.ContainerIdParameterSet: { remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified(); } + break; case NewPSSessionCommand.SSHHostParameterSet: { remoteRunspaces = CreateRunspacesForSSHHostParameterSet(); } + break; case NewPSSessionCommand.SSHHostHashParameterSet: { remoteRunspaces = CreateRunspacesForSSHHostHashParameterSet(); } + break; default: @@ -251,6 +261,7 @@ protected override void ProcessRecord() Dbg.Assert(false, "Missing parameter set in switch statement"); remoteRunspaces = new List(); // added to avoid prefast warning } + break; } @@ -436,6 +447,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s writer.Write(outputWriter); } } + break; case RunspaceState.Broken: @@ -516,6 +528,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s { errorDetails += System.Environment.NewLine + String.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist); } + ErrorRecord errorRecord = new ErrorRecord(reason, remoteRunspace, fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, @@ -549,6 +562,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s _toDispose.Add(remoteRunspace); } + break; case RunspaceState.Closed: @@ -591,6 +605,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s } } } + break; } } @@ -804,6 +819,7 @@ private List CreateRunspacesWhenComputerNameParameterSpecified() { connectionInfo.Credential = Credential; } + connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -1281,6 +1297,7 @@ internal override void StartOperation() { _startComplete = false; } + OperatedRunspace.OpenAsync(); } @@ -1334,6 +1351,7 @@ internal override event EventHandler OperationComplete _internalCallbacks.Add(value); } } + remove { lock (_internalCallbacks) @@ -1413,6 +1431,7 @@ private void FireEvent(OperationStateEventArgs operationStateEventArgs) copyCallbacks = new EventHandler[_internalCallbacks.Count]; _internalCallbacks.CopyTo(copyCallbacks); } + foreach (var callbackDelegate in copyCallbacks) { // Ensure all callbacks get called to prevent ThrottleManager from not responding. diff --git a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs index 8870806597b..ac591efbee6 100644 --- a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs @@ -111,11 +111,13 @@ protected override void ProcessRecord() toRemove = matches.Values; } + break; case RemovePSSessionCommand.SessionParameterSet: { toRemove = Session; } + break; default: Diagnostics.Assert(false, "Invalid Parameter Set"); From aee1aac632ea74c56febb7363eda2651bd4dadbd Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:14 -0800 Subject: [PATCH 70/81] Update common --- .../common/RemoteSessionHyperVSocket.cs | 8 +++ .../remoting/common/RemoteSessionNamedPipe.cs | 11 ++++ .../remoting/common/RunspaceConnectionInfo.cs | 61 +++++++++++++++++++ .../engine/remoting/common/fragmentor.cs | 5 ++ .../engine/remoting/common/psstreamobject.cs | 22 +++++++ .../remoting/common/remotingexceptions.cs | 2 + .../engine/remoting/common/throttlemanager.cs | 5 ++ 7 files changed, 114 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 61a717de16c..770ad927840 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -44,12 +44,14 @@ public override System.Net.Sockets.AddressFamily AddressFamily public Guid VmId { get { return _vmId; } + set { _vmId = value; } } public Guid ServiceId { get { return _serviceId; } + set { _vmId = value; } } @@ -293,6 +295,7 @@ public void Dispose() lock (_syncObject) { if (IsDisposed) { return; } + IsDisposed = true; } @@ -300,6 +303,7 @@ public void Dispose() { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } + TextReader = null; } @@ -307,6 +311,7 @@ public void Dispose() { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } + TextWriter = null; } @@ -440,6 +445,7 @@ public void Dispose() lock (_syncObject) { if (IsDisposed) { return; } + IsDisposed = true; } @@ -447,6 +453,7 @@ public void Dispose() { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } + TextReader = null; } @@ -454,6 +461,7 @@ public void Dispose() { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } + TextWriter = null; } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 95a2bf17cbb..bff7723bb01 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -475,7 +475,9 @@ private NamedPipeServerStream CreateNamedPipe( CommonSecurityDescriptor securityDesc) { if (serverName == null) { throw new PSArgumentNullException("serverName"); } + if (namespaceName == null) { throw new PSArgumentNullException("namespaceName"); } + if (coreName == null) { throw new PSArgumentNullException("coreName"); } #if !UNIX @@ -567,6 +569,7 @@ public void Dispose() lock (_syncObject) { if (IsDisposed) { return; } + IsDisposed = true; } @@ -574,6 +577,7 @@ public void Dispose() { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } + TextReader = null; } @@ -581,6 +585,7 @@ public void Dispose() { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } + TextWriter = null; } @@ -616,6 +621,7 @@ public void StartListening( { throw new InvalidOperationException(RemotingErrorIdStrings.NamedPipeAlreadyListening); } + IsListenerRunning = true; // Create listener thread. @@ -729,6 +735,7 @@ private void ProcessListeningThread(object state) { ex = e; } + if (ex != null) { // Error during connection handling. Don't try to restart listening thread. @@ -983,6 +990,7 @@ public void Dispose() { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } + TextReader = null; } @@ -990,6 +998,7 @@ public void Dispose() { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } + TextWriter = null; } @@ -1114,7 +1123,9 @@ internal RemoteSessionNamedPipeClient( string coreName) { if (serverName == null) { throw new PSArgumentNullException("serverName"); } + if (namespaceName == null) { throw new PSArgumentNullException("namespaceName"); } + if (coreName == null) { throw new PSArgumentNullException("coreName"); } _pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 40bb700cca0..aa5922ad5d4 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -179,12 +179,14 @@ public CultureInfo Culture { return _culture; } + set { if (value == null) { throw new ArgumentNullException("value"); } + _culture = value; } } @@ -200,12 +202,14 @@ public CultureInfo UICulture { return _uiCulture; } + set { if (value == null) { throw new ArgumentNullException("value"); } + _uiCulture = value; } } @@ -221,6 +225,7 @@ public CultureInfo UICulture public int OpenTimeout { get { return _openTimeout; } + set { _openTimeout = value; @@ -241,6 +246,7 @@ public int OpenTimeout } } } + private int _openTimeout = DefaultOpenTimeout; internal const int DefaultOpenTimeout = 3 * 60 * 1000; // 3 minutes internal const int DefaultTimeout = -1; @@ -404,12 +410,14 @@ public Uri ConnectionUri { return _connectionUri; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } + UpdateUri(value); } } @@ -423,6 +431,7 @@ public override string ComputerName { return _computerName; } + set { // null or empty value allowed @@ -439,6 +448,7 @@ public string Scheme { return _scheme; } + set { // null or empty value allowed @@ -455,6 +465,7 @@ public int Port { return ConnectionUri.Port; } + set { ConstructUri(_scheme, _computerName, value, _appName); @@ -471,6 +482,7 @@ public string AppName { return _appName; } + set { //null or empty value allowed @@ -487,6 +499,7 @@ public override PSCredential Credential { return _credential; } + set { // null or empty value allowed @@ -503,6 +516,7 @@ public string ShellUri { return _shellUri; } + set { _shellUri = ResolveShellUri(value); @@ -529,6 +543,7 @@ public override AuthenticationMechanism AuthenticationMechanism { return AuthenticationMechanism.NegotiateWithImplicitCredential; } + return AuthenticationMechanism.Negotiate; case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST: return AuthenticationMechanism.Digest; @@ -539,6 +554,7 @@ public override AuthenticationMechanism AuthenticationMechanism return AuthenticationMechanism.Default; } } + set { switch (value) @@ -568,6 +584,7 @@ public override AuthenticationMechanism AuthenticationMechanism default: throw new PSNotSupportedException(); } + ValidateSpecifiedAuthentication(); } } @@ -597,12 +614,14 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return _thumbPrint; } + set { if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } + _thumbPrint = value; } } @@ -672,6 +691,7 @@ public override string CertificateThumbprint public AuthenticationMechanism ProxyAuthentication { get { return _proxyAuthentication; } + set { switch (value) @@ -698,6 +718,7 @@ public AuthenticationMechanism ProxyAuthentication public PSCredential ProxyCredential { get { return _proxyCredential; } + set { if (ProxyAccessType == ProxyAccessType.None) @@ -918,6 +939,7 @@ public WSManConnectionInfo(Uri uri, string shellUri, PSCredential credential) { ConnectionUri = uri; } + ShellUri = shellUri; Credential = credential; } @@ -1185,6 +1207,7 @@ internal void ConstructUri(string scheme, string computerName, int? port, string } } } + PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method, PSTask.CreateRunspace, PSKeyword.Runspace | PSKeyword.UseAlwaysAnalytic, _computerName); @@ -1349,6 +1372,7 @@ private void UpdateUri(Uri uri) internal bool UseDefaultWSManPort { get { return false; } + set { } } #else @@ -1496,17 +1520,20 @@ public WSManConnectionInfo(PSSessionType configurationType) : this() { // it is already the default } + break; case PSSessionType.Workflow: { ShellUri = DefaultM3PEndpoint; } + break; default: { Diagnostics.Assert(false, "Unknown value for PSSessionType"); } + break; } } @@ -1558,6 +1585,7 @@ internal sealed class NewProcessConnectionInfo : RunspaceConnectionInfo public override string ComputerName { get { return "localhost"; } + set { throw new NotImplementedException(); } } @@ -1567,6 +1595,7 @@ public override string ComputerName public override PSCredential Credential { get { return _credential; } + set { _credential = value; @@ -1584,6 +1613,7 @@ public override AuthenticationMechanism AuthenticationMechanism { return _authMechanism; } + set { if (value != AuthenticationMechanism.Default) @@ -1605,6 +1635,7 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return string.Empty; } + set { throw new NotImplementedException(); } } @@ -1684,6 +1715,7 @@ public int ProcessId public string AppDomainName { get { return _appDomainName; } + set { _appDomainName = value ?? string.Empty; @@ -1748,6 +1780,7 @@ public NamedPipeConnectionInfo( public override string ComputerName { get { return "localhost"; } + set { throw new NotImplementedException(); } } @@ -1774,6 +1807,7 @@ public override AuthenticationMechanism AuthenticationMechanism { return _authMechanism; } + set { if (value != Runspaces.AuthenticationMechanism.Default) @@ -1792,6 +1826,7 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return string.Empty; } + set { throw new NotImplementedException(); } } @@ -1955,6 +1990,7 @@ public override string ComputerName public override PSCredential Credential { get { return null; } + set { throw new NotImplementedException(); } } @@ -1964,6 +2000,7 @@ public override PSCredential Credential public override AuthenticationMechanism AuthenticationMechanism { get { return AuthenticationMechanism.Default; } + set { throw new NotImplementedException(); } } @@ -1973,6 +2010,7 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return string.Empty; } + set { throw new NotImplementedException(); } } @@ -2202,12 +2240,14 @@ internal static int StartSSHProcess( Utils.utf8NoBom, StreamBufferSize) { AutoFlush = true }; } + if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0, "Invalid Fd"); standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? Utils.utf8NoBom, true, StreamBufferSize); } + if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0, "Invalid Fd"); @@ -2241,6 +2281,7 @@ private static string[] CopyEnvVariables(ProcessStartInfo psi) { envp[index++] = pair.Key + "=" + pair.Value; } + return envp; } @@ -2268,6 +2309,7 @@ private static string[] ParseArgv(ProcessStartInfo psi) { iStart++; } + break; default: @@ -2438,7 +2480,9 @@ private static int StartSSHProcessImpl( catch (Exception) { if (stdInWriterVar != null) { stdInWriterVar.Dispose(); } else { stdInPipeServer.Dispose(); } + if (stdOutReaderVar != null) { stdInWriterVar.Dispose(); } else { stdOutPipeServer.Dispose(); } + if (stdErrReaderVar != null) { stdInWriterVar.Dispose(); } else { stdErrPipeServer.Dispose(); } throw; @@ -2491,10 +2535,15 @@ private static Process CreateProcessWithRedirectedStd( catch (Exception) { if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } + if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } + if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } + if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } + if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } + if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } throw; @@ -2557,10 +2606,15 @@ private static Process CreateProcessWithRedirectedStd( catch (Exception) { if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } + if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } + if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } + if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } + if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } + if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } throw; @@ -2683,6 +2737,7 @@ public override AuthenticationMechanism AuthenticationMechanism { return _authMechanism; } + set { if (value != AuthenticationMechanism.Default) @@ -2704,6 +2759,7 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return null; } + set { throw new NotImplementedException(); } } @@ -2713,6 +2769,7 @@ public override string CertificateThumbprint public override PSCredential Credential { get { return _credential; } + set { _credential = value; @@ -2804,6 +2861,7 @@ public override AuthenticationMechanism AuthenticationMechanism { return _authMechanism; } + set { if (value != AuthenticationMechanism.Default) @@ -2825,6 +2883,7 @@ public override AuthenticationMechanism AuthenticationMechanism public override string CertificateThumbprint { get { return null; } + set { throw new NotImplementedException(); } } @@ -2834,6 +2893,7 @@ public override string CertificateThumbprint public override PSCredential Credential { get { return _credential; } + set { _credential = value; @@ -2847,6 +2907,7 @@ public override PSCredential Credential public override string ComputerName { get { return ContainerProc.ContainerId; } + set { throw new PSNotSupportedException(); } } diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index fd4df42f5b8..af9b37deeaa 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -142,6 +142,7 @@ internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, internal int BlobLength { get { return _blobLength; } + set { Dbg.Assert(value >= 0, "BlobLength cannot be less than 0."); @@ -155,6 +156,7 @@ internal int BlobLength internal byte[] Blob { get { return _blob; } + set { Dbg.Assert(value != null, "Blob cannot be null"); @@ -897,6 +899,7 @@ protected override void Dispose(bool disposing) public override long Position { get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } } /// @@ -936,6 +939,7 @@ public override void SetLength(long value) GC.SuppressFinalize(this); _disposed = true; } + base.Dispose(); } @@ -1029,6 +1033,7 @@ internal int FragmentSize { return _fragmentSize; } + set { Dbg.Assert(value > 0, "FragmentSize cannot be less than 0."); diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index 233ea1a35b5..628a008e923 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -109,6 +109,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) { cmdlet.WriteObject(this.Value); } + break; case PSStreamObjectType.Error: @@ -121,6 +122,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteError(errorRecord, overrideInquire); } } + break; case PSStreamObjectType.Debug: @@ -133,6 +135,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); } } + break; case PSStreamObjectType.Warning: @@ -145,6 +148,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); } } + break; case PSStreamObjectType.Verbose: @@ -157,6 +161,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); } } + break; case PSStreamObjectType.Progress: @@ -167,6 +172,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteProgress((ProgressRecord)Value, overrideInquire); } } + break; case PSStreamObjectType.Information: @@ -177,6 +183,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.WriteInformation((InformationRecord)Value, overrideInquire); } } + break; case PSStreamObjectType.WarningRecord: @@ -188,6 +195,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) mshCommandRuntime.AppendWarningVarList(warningRecord); } } + break; case PSStreamObjectType.MethodExecutor: @@ -197,6 +205,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) ClientMethodExecutor methodExecutor = (ClientMethodExecutor)Value; methodExecutor.Execute(cmdlet); } + break; case PSStreamObjectType.BlockingError: @@ -204,6 +213,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker)Value; InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet); } + break; case PSStreamObjectType.ShouldMethod: @@ -211,6 +221,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker)Value; InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet); } + break; case PSStreamObjectType.Exception: @@ -263,8 +274,10 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq if (o != null) AddSourceJobNoteProperty(o, instanceId); } + cmdlet.WriteObject(Value); } + break; case PSStreamObjectType.Error: @@ -300,6 +313,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteError(errorRecord, overrideInquire); } } + break; case PSStreamObjectType.Warning: @@ -312,6 +326,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); } } + break; case PSStreamObjectType.Verbose: @@ -324,6 +339,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); } } + break; case PSStreamObjectType.Progress: @@ -351,6 +367,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteProgress(progressRecord, overrideInquire); } } + break; case PSStreamObjectType.Debug: @@ -363,6 +380,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); } } + break; case PSStreamObjectType.Information: @@ -395,6 +413,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq mshCommandRuntime.WriteInformation(informationRecord, overrideInquire); } } + break; case PSStreamObjectType.WarningRecord: @@ -404,6 +423,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq { WriteStreamObject(cmdlet, overrideInquire); } + break; } } @@ -442,6 +462,7 @@ private static void InvokeCmdletMethodAndWaitForResults(CmdletMethodInvoker EventHandler OperationComplete += new EventHandler(Operation_OperationComplete); } } + remove { InternalEvent -= value; From f8e0e301dabea9e71de925e1f24fa6ea318548ce Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:14 -0800 Subject: [PATCH 71/81] Update fanin --- .../remoting/fanin/BaseTransportManager.cs | 2 ++ .../fanin/InitialSessionStateProvider.cs | 9 ++++++++ .../fanin/OutOfProcTransportManager.cs | 16 ++++++++++++++ .../engine/remoting/fanin/PSPrincipal.cs | 1 + .../fanin/PSSessionConfigurationData.cs | 3 +++ .../remoting/fanin/PriorityCollection.cs | 4 ++++ .../engine/remoting/fanin/WSManNativeAPI.cs | 21 +++++++++++++++++++ .../engine/remoting/fanin/WSManPlugin.cs | 4 ++++ .../remoting/fanin/WSManPluginFacade.cs | 1 + .../remoting/fanin/WSManPluginShellSession.cs | 3 +++ .../fanin/WSManPluginTransportManager.cs | 2 ++ .../remoting/fanin/WSManTransportManager.cs | 12 +++++++++++ 12 files changed, 78 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 086088c0ba9..c3e5d0580b5 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -234,6 +234,7 @@ protected BaseTransportManager(PSRemotingCryptoHelper cryptoHelper) internal TypeTable TypeTable { get { return Fragmentor.TypeTable; } + set { Fragmentor.TypeTable = value; } } @@ -1137,6 +1138,7 @@ protected BaseClientCommandTransportManager(ClientRemotePowerShell shell, cmdText.Append(cmd.CommandText); cmdText.Append(" | "); } + cmdText.Remove(cmdText.Length - 3, 3); // remove ending " | " RemoteDataObject message; diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 366c48f7b3f..a0c5f9a7b1a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -141,12 +141,14 @@ private void Update(string optionName, string optionValue) AssertValueNotAssigned(SESSIONCONFIGTOKEN, SessionConfigurationData); SessionConfigurationData = PSSessionConfigurationData.Create(optionValue); } + break; case CONFIGFILEPATH: { AssertValueNotAssigned(CONFIGFILEPATH, ConfigFilePath); ConfigFilePath = optionValue.ToString(); } + break; default: // we dont need to evaluate PSVersion and other custom authz @@ -672,6 +674,7 @@ private static Assembly LoadSsnStateProviderAssembly(string applicationBase, str { return result; } + s_tracer.WriteLine("Loading assembly from path {0}", applicationBase); try { @@ -692,6 +695,7 @@ private static Assembly LoadSsnStateProviderAssembly(string applicationBase, str //Rooted path of dll is provided. assemblyPath = assemblyName; } + result = Assembly.LoadFrom(assemblyPath); } catch (FileLoadException e) @@ -715,6 +719,7 @@ private static Assembly LoadSsnStateProviderAssembly(string applicationBase, str Directory.SetCurrentDirectory(originalDirectory); } } + return result; } @@ -2098,6 +2103,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn } } } + iss.ImportPSModule(modulesToImport); } } @@ -2567,6 +2573,7 @@ private static void ProcessCommandModification(Dictionary com { currentParameterModification[parameterModification] = new HashSet(StringComparer.OrdinalIgnoreCase); } + HashSet currentParameterModificationValue = (HashSet)currentParameterModification[parameterModification]; foreach (string parameterModificationValue in TryGetStringArray(parameter[parameterModification])) @@ -2871,6 +2878,7 @@ internal static T[] TryGetObjectsOfType(object hashObj, IEnumerable typ } } } + return null; } @@ -2887,6 +2895,7 @@ internal static T[] TryGetObjectsOfType(object hashObj, IEnumerable typ return null; } } + return result; } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 69aca329a64..f88612e5d61 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -232,6 +232,7 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_DATA_TAG); } + string stream = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_STREAM_ATTRIBUTE); string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); @@ -267,12 +268,14 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_DATA_ACK received, psGuid : " + psGuid.ToString()); callbacks.DataAckPacketReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_TAG: { @@ -283,12 +286,14 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_COMMAND received, psGuid : " + psGuid.ToString()); callbacks.CommandCreationPacketReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG: { @@ -299,11 +304,13 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_COMMAND_ACK received, psGuid : " + psGuid.ToString()); callbacks.CommandCreationAckReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_TAG: { @@ -314,12 +321,14 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_CLOSE received, psGuid : " + psGuid.ToString()); callbacks.ClosePacketReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG: { @@ -330,11 +339,13 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_CLOSE_ACK received, psGuid : " + psGuid.ToString()); callbacks.CloseAckPacketReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG: { @@ -345,12 +356,14 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_SIGNAL received, psGuid : " + psGuid.ToString()); callbacks.SignalPacketReceived(psGuid); } + break; case OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG: { @@ -361,11 +374,13 @@ private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG); } + string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_SIGNAL_ACK received, psGuid : " + psGuid.ToString()); callbacks.SignalAckPacketReceived(psGuid); } + break; default: throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, @@ -1024,6 +1039,7 @@ internal override void CreateAsync() _serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); _serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); } + _serverProcess.Exited += new EventHandler(OnExited); //serverProcess.Start(); diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index 134a2c90236..1ab1a486601 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -149,6 +149,7 @@ public TimeZoneInfo ClientTimeZone public PSPrimitiveDictionary ApplicationArguments { get { return _applicationArguments; } + internal set { _applicationArguments = value; } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index d62a64483b5..feb4860d9bc 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -46,6 +46,7 @@ public string PrivateData { return _privateData; } + internal set { _privateData = value; @@ -206,11 +207,13 @@ private void Update(string optionName, string optionValue) } } } + break; default: { Dbg.Assert(false, "Unknown option specified"); } + break; } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index ea1b0c10d24..6bf1def5869 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -88,6 +88,7 @@ internal PrioritySendDataCollection() internal Fragmentor Fragmentor { get { return _fragmentor; } + set { Dbg.Assert(value != null, "Fragmentor cannot be null."); @@ -659,6 +660,7 @@ internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) { ReleaseResources(); } + _numberOfThreadsProcessing--; } } @@ -674,6 +676,7 @@ private void ResetReceiveData() { _dataToProcessStream.Dispose(); } + _currentObjectId = 0; _currentFrgId = 0; _totalReceivedObjectSizeSoFar = 0; @@ -759,6 +762,7 @@ internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByCl { _recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM); } + _isCreateByClientTM = createdByClientTM; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 7d981fc2251..bc05ee31d43 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -405,6 +405,7 @@ private struct WSManThumbprintStruct /// internal IntPtr reserved; } + private MarshalledObject _data; /// @@ -699,6 +700,7 @@ internal WSManData_ManToUn(string data) internal uint Type { get { return _internalData.type; } + set { _internalData.type = value; } } @@ -708,6 +710,7 @@ internal uint Type internal int BufferLength { get { return _internalData.binaryOrTextData.bufferLength; } + set { _internalData.binaryOrTextData.bufferLength = value; } } @@ -731,6 +734,7 @@ private void Dispose(bool isDisposing) Marshal.FreeHGlobal(_marshalledBuffer); _marshalledBuffer = IntPtr.Zero; } + if (_marshalledObject != IntPtr.Zero) { Marshal.FreeHGlobal(_marshalledObject); @@ -765,6 +769,7 @@ internal class WSManData_UnToMan internal uint Type { get { return _type; } + set { _type = value; } } @@ -775,6 +780,7 @@ internal uint Type internal int BufferLength { get { return _bufferLength; } + set { _bufferLength = value; } } @@ -822,6 +828,7 @@ internal static WSManData_UnToMan UnMarshal(WSManDataStruct dataStruct) string tempText = Marshal.PtrToStringUni(dataStruct.binaryOrTextData.data, dataStruct.binaryOrTextData.bufferLength); newData._text = tempText; } + break; case (uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_BINARY: if (dataStruct.binaryOrTextData.bufferLength > 0) @@ -835,10 +842,12 @@ internal static WSManData_UnToMan UnMarshal(WSManDataStruct dataStruct) dataStruct.binaryOrTextData.bufferLength); newData._data = dataRecvd; } + break; default: throw new NotSupportedException(); } + return newData; } @@ -1032,6 +1041,7 @@ internal static WSManStreamIDSet_UnToMan UnMarshal(IntPtr unmanagedData) result.streamIDs = idsArray; result.streamIDsCount = resultInternal.streamIDsCount; } + return result; } } @@ -1208,6 +1218,7 @@ internal struct WSManCommandArgSetInternal [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr args; } + private WSManCommandArgSetInternal _internalData; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private MarshalledObject _data; @@ -1297,6 +1308,7 @@ internal static WSManCommandArgSet UnMarshal(IntPtr unmanagedData) result.argsCount = resultInternal.argsCount; result.args = tempArgs; } + return result; } @@ -1473,6 +1485,7 @@ internal static WSManShellStartupInfo_UnToMan UnMarshal(IntPtr unmanagedData) result.environmentVariableSet = WSManEnvironmentVariableSet.UnMarshal(resultInternal.environmentVariableSet); result.name = resultInternal.name; } + return result; } } @@ -1518,6 +1531,7 @@ internal static WSManEnvironmentVariableSet UnMarshal(IntPtr unmanagedData) result.vars = varsArray; result.varsCount = resultInternal.varsCount; } + return result; } @@ -1549,6 +1563,7 @@ private struct WSManProxyInfoInternal public int proxyAccessType; public WSManUserNameAuthenticationCredentials.WSManUserNameCredentialStruct proxyAuthCredentialsStruct; } + private MarshalledObject _data; /// @@ -1738,6 +1753,7 @@ internal struct WSManShellAsyncInternal internal IntPtr operationContext; internal IntPtr asyncCallback; } + private MarshalledObject _data; private WSManShellAsyncInternal _internalData; @@ -1822,6 +1838,7 @@ internal static WSManCreateShellDataResult UnMarshal(IntPtr unmanagedData) result.data = connectData; } + return result; } @@ -2035,6 +2052,7 @@ internal static WSManPluginRequest UnMarshal(IntPtr unmanagedData) result._internalDetails = resultInternal; result.unmanagedHandle = unmanagedData; } + return result; } @@ -2089,6 +2107,7 @@ internal static WSManSenderDetails UnMarshal(IntPtr unmanagedData) result.clientToken = resultInternal.clientToken; // TODO: UnMarshaling needed here!!!! result.httpUrl = resultInternal.httpUrl; } + return result; } @@ -2138,6 +2157,7 @@ internal static WSManCertificateDetails UnMarshal(IntPtr unmanagedData) result.issuerThumbprint = resultInternal.issuerThumbprint; result.subjectName = resultInternal.subjectName; } + return result; } /// @@ -2183,6 +2203,7 @@ internal static WSManOperationInfo UnMarshal(IntPtr unmanagedData) result.selectorSet = WSManSelectorSet.UnMarshal(resultInternal.selectorSet); result.optionSet = WSManOptionSet.UnMarshal(resultInternal.optionSet); } + return result; } /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 27b5c057954..2a3fb6822b0 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -441,6 +441,7 @@ internal void CreateShell( //this will called OperationComplete PerformCloseOperation(context); } + return; } @@ -562,6 +563,7 @@ private void DeleteFromActiveShellSessions( count = _activeShellSessions.Count; } } + if (-1 != count) { // Raise session count changed event @@ -620,6 +622,7 @@ private bool validateIncomingContexts( inputFunctionName)); return false; } + return true; } @@ -1039,6 +1042,7 @@ protected internal bool EnsureOptionsComply( { return false; } + isProtocolVersionDeclared = true; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 65dffd09c68..f1c28cae988 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -303,6 +303,7 @@ private void populateDelegates() _shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin); _unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin); } + if (!Platform.IsWindows) { WSMPluginOperationShutdownDelegate pluginShutDownDelegate = new WSMPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 716a326684d..da32d13d2fb 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -318,6 +318,7 @@ internal void HandleTransportError(Object sender, TransportErrorOccuredEventArgs { reasonForClose = eventArgs.Exception; } + Close(reasonForClose); } @@ -641,6 +642,7 @@ private void CloseAndClearCommandSessions( cmdSession.SessionClosed -= new EventHandler(this.HandleCommandSessionClosed); cmdSession.Close(reasonForClose); } + copyCmdSessions.Clear(); } @@ -666,6 +668,7 @@ private void HandleServerRemoteSessionClosed( { reasonForClose = eventArgs.Reason; } + Close(reasonForClose); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index eaf52e57155..79c117cf769 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -106,6 +106,7 @@ internal void DoClose( { cmdTransportKvp.Value.Close(reasonForClose); } + _activeCmdTransportManagers.Clear(); if (_registeredShutDownWaitHandle != null) @@ -244,6 +245,7 @@ protected override void SendDataToClient( } } } + if ((int)WSManPluginErrorCodes.NoError != result) { ReportError(result, "WSManPluginReceiveResult"); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 9d929ba0aec..8613e688c9d 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -224,6 +224,7 @@ internal static string ParseEscapeWSManErrorMessage(string errorMessage) { msgSB.Insert(currentToken.EndColumn - 1, ",", 1); } + break; } } @@ -563,6 +564,7 @@ internal WSManClientSessionTransportManager(Guid runspacePoolInstanceId, throw new PSRemotingTransportException( StringUtil.Format(RemotingErrorIdStrings.WSManInitFailed, WSManAPIData.ErrorCode)); } + Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null"); CryptoHelper = cryptoHelper; @@ -1220,6 +1222,7 @@ internal override void CloseAsync() { RemoveSessionTransportManager(_sessionContextID); } + return; } @@ -1376,6 +1379,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) { additionalUriSuffixString = ";MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"; } + if (string.IsNullOrEmpty(connectionUri.Query)) { // if there is no query string already, create one..see RFC 3986 @@ -1549,6 +1553,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS, new WSManNativeApi.WSManDataDWord(1)); } + if (connectionInfo.UseUTF16) { SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UTF16, 1); @@ -2557,6 +2562,7 @@ private void DisposeWSManAPIDataAsync() { WSManAPIDataCommon tempWSManApiData = WSManAPIData; if (tempWSManApiData == null) { return; } + WSManAPIData = null; // Dispose and de-initialize the WSManAPIData instance object on separate worker thread to ensure @@ -2642,9 +2648,13 @@ internal WSManAPIDataCommon() } internal int ErrorCode { get; } + internal WSManNativeApi.WSManStreamIDSet_ManToUn InputStreamSet { get { return _inputStreamSet; } } + internal WSManNativeApi.WSManStreamIDSet_ManToUn OutputStreamSet { get { return _outputStreamSet; } } + internal List CommonOptionSet { get; } + internal IntPtr WSManAPIHandle { get { return _handle; } } /// @@ -2659,6 +2669,7 @@ public void Dispose() lock (_syncObject) { if (_isDisposed) { return; } + _isDisposed = true; } @@ -3100,6 +3111,7 @@ internal override void CloseAsync() { RemoveCmdTransportManager(_cmdContextId); } + return; } From 60349b63ab78e5f16e1126c61859d383e5e281b6 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:15 -0800 Subject: [PATCH 72/81] Update server --- .../remoting/server/OutOfProcServerMediator.cs | 3 +++ .../remoting/server/ServerPowerShellDriver.cs | 5 +++++ .../engine/remoting/server/ServerRemoteHost.cs | 3 +++ .../server/ServerRemoteHostRawUserInterface.cs | 1 + .../remoting/server/ServerRemotingProtocol2.cs | 15 +++++++++++++++ .../remoting/server/ServerRunspacePoolDriver.cs | 11 +++++++++++ .../server/ServerSteppablePipelineDriver.cs | 4 ++++ .../server/ServerSteppablePipelineSubscriber.cs | 3 +++ .../engine/remoting/server/serverremotesession.cs | 7 +++++++ .../server/serverremotesessionstatemachine.cs | 8 ++++++++ .../serverremotingprotocolimplementation.cs | 3 +++ 11 files changed, 63 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index 31ad5fa8bd8..24ee20d24b9 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -253,6 +253,7 @@ protected void OnClosePacketReceived(Guid psGuid) // changing PSRP/IPC at this point is too risky, therefore protecting about this duplication sessionTM.Close(null); } + tracer.WriteMessage("END calling close on session transport manager"); sessionTM = null; } @@ -340,6 +341,7 @@ protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoH sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper); } } + if (string.IsNullOrEmpty(data)) { lock (_syncObject) @@ -349,6 +351,7 @@ protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoH sessionTM.Close(null); sessionTM = null; } + throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived, string.Empty); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 0c2158c03a2..db9ebcc2c01 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -512,6 +512,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, { UnregisterPowerShellEventHandlers(_extraPowerShell); } + UnregisterDataStructureHandlerEventHandlers(DataStructureHandler); UnregisterPipelineOutputEventHandlers(_localPowerShellOutput); @@ -522,6 +523,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, //localPowerShell.Dispose(); } } + break; case PSInvocationState.Stopping: @@ -529,6 +531,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, // abort all pending host calls _remoteHost.ServerMethodExecutor.AbortAllCalls(); } + break; } } @@ -736,6 +739,7 @@ private void SendRemainingData() PSObject data = _localPowerShellOutput[i]; DataStructureHandler.SendOutputDataToClient(data); } + _localPowerShellOutput.Clear(); //foreach (ErrorRecord errorRecord in localPowerShell.Error) @@ -744,6 +748,7 @@ private void SendRemainingData() ErrorRecord errorRecord = LocalPowerShell.Streams.Error[i]; DataStructureHandler.SendErrorRecordToClient(errorRecord); } + LocalPowerShell.Streams.Error.Clear(); } finally diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index f15fb2ec884..78d58988be2 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -157,6 +157,7 @@ public virtual bool IsRunspacePushed internal virtual bool AllowPushRunspace { get { return (_serverDriverRemoteHost != null) ? _serverDriverRemoteHost.AllowPushRunspace : false; } + set { if (_serverDriverRemoteHost != null) { _serverDriverRemoteHost.AllowPushRunspace = value; } } } @@ -388,6 +389,7 @@ public override void PopRunspace() { _pushedRunspace.Close(); } + _pushedRunspace = null; } } @@ -402,6 +404,7 @@ public override void PopRunspace() internal Debugger ServerDebugger { get { return _debugger; } + set { _debugger = value as ServerRemoteDebugger; } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 7dedde2edc1..a111051dceb 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -346,6 +346,7 @@ public override int LengthInBufferCells(string source) { throw new ArgumentNullException("source"); } + return source.Length; } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index bb45a263cea..9420ba007ba 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -93,6 +93,7 @@ internal void ProcessConnect() { dsHandlers = new List(_associatedShells.Values); } + foreach (var dsHandler in dsHandlers) { dsHandler.ProcessConnect(); @@ -123,6 +124,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs>(receivedData)); } + break; case RemotingDataType.GetCommandMetadata: @@ -132,6 +134,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs>(receivedData)); } + break; case RemotingDataType.RemoteRunspaceHostResponseData: @@ -147,6 +150,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostResponse)); } + break; case RemotingDataType.SetMaxRunspaces: @@ -156,6 +160,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; case RemotingDataType.SetMinRunspaces: @@ -165,6 +170,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; case RemotingDataType.AvailableRunspaces: @@ -174,6 +180,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; case RemotingDataType.ResetRunspaceState: @@ -183,6 +190,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; } } @@ -242,6 +250,7 @@ internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler( } } } + return null; } @@ -282,6 +291,7 @@ internal void SendResponseToClient(long callId, object response) internal TypeTable TypeTable { get { return _transportManager.TypeTable; } + set { _transportManager.TypeTable = value; } } @@ -369,6 +379,7 @@ internal ServerPowerShellDataStructureHandler GetAssociatedPowerShellDataStructu dsHandler = null; } } + return dsHandler; } @@ -619,6 +630,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) "ServerPowerShellDriver should subscribe to all data structure handler events"); StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty); } + break; case RemotingDataType.PowerShellInput: @@ -627,6 +639,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) "ServerPowerShellDriver should subscribe to all data structure handler events"); InputReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } + break; case RemotingDataType.PowerShellInputEnd: @@ -635,6 +648,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) "ServerPowerShellDriver should subscribe to all data structure handler events"); InputEndReceived.SafeInvoke(this, EventArgs.Empty); } + break; case RemotingDataType.RemotePowerShellHostResponseData: @@ -650,6 +664,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostResponse)); } + break; } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index faa6e375515..c7222cbf5d0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -413,6 +413,7 @@ internal void Close() _rsToUseForSteppablePipeline.Dispose(); _rsToUseForSteppablePipeline = null; } + Closed.SafeInvoke(this, EventArgs.Empty); } } @@ -721,6 +722,7 @@ private void HandleRunspacePoolStateChanged(object sender, { DataStructureHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); } + break; case RunspacePoolState.Opened: @@ -728,6 +730,7 @@ private void HandleRunspacePoolStateChanged(object sender, SendApplicationPrivateDataToClient(); DataStructureHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); } + break; } } @@ -1038,6 +1041,7 @@ private void HandleGetCommandMetadata(object sender, RemoteDataEventArgs even { Input.Add(eventArgs.Data); } + CheckAndPulseForProcessing(false); if (_powershellInput != null) @@ -451,6 +452,7 @@ internal void SetState(PSInvocationState newState, Exception reason) break; } } + break; case PSInvocationState.Running: @@ -472,6 +474,7 @@ internal void SetState(PSInvocationState newState, Exception reason) break; } } + break; case PSInvocationState.Stopping: @@ -491,6 +494,7 @@ internal void SetState(PSInvocationState newState, Exception reason) throw new InvalidOperationException(); } } + break; case PSInvocationState.Stopped: diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 2c0c31cb288..258879e3455 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -53,6 +53,7 @@ internal void SubscribeEvents(ServerSteppablePipelineDriver driver) _processSubscriber = _eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true); } + _initialized = true; } } @@ -130,6 +131,7 @@ private void HandleProcessRecord(object sender, PSEventArgs args) { return; } + driver.ProcessingInput = true; driver.Pulsed = false; } @@ -174,6 +176,7 @@ private void HandleProcessRecord(object sender, PSEventArgs args) { output = driver.SteppablePipeline.Process(driver.InputEnumerator.Current); } + foreach (object o in output) { if (driver.PipelineState != PSInvocationState.Running) diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index c6f7f757d88..2d27075788d 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -203,6 +203,7 @@ internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo sende { throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId); } + string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = configurationProviderId.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); senderInfo.ConfigurationName = (index == 0) ? configurationProviderId.Substring(shellPrefix.Length) : string.Empty; @@ -328,6 +329,7 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEven { SessionDataStructureHandler.StateMachine.RaiseEvent(messageReceivedArg); } + break; case RemotingDataType.CloseSession: @@ -347,6 +349,7 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEven break; } } + break; // TODO: Directly calling an event handler in StateMachine bypassing the StateMachine's @@ -366,6 +369,7 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEven { SessionDataStructureHandler.StateMachine.RaiseEvent(messageReceivedArg); } + break; } } @@ -729,6 +733,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR { throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg"); } + RemoteDataObject rcvdData = createRunspaceEventArg.ReceivedData; Dbg.Assert(rcvdData != null, "rcvdData must be non-null"); @@ -828,6 +833,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR RemoteDataNameStrings.PSv2TabExpansionFunctionText)); } } + if (value.ContainsKey("PSVersion")) { psClientVersion = PSObject.Base(value["PSVersion"]) as Version; @@ -841,6 +847,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR _maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo); _maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo); } + SessionDataStructureHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; // MaximumReceivedDataSize is not set for session transport manager...see the constructor // for more info. diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index 09171d79fdf..ad4ea4fab9f 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -201,6 +201,7 @@ internal void RaiseEvent(RemoteSessionStateMachineEventArgs fsmEventArg) { return; } + _eventsInProcess = true; } @@ -231,6 +232,7 @@ private void ProcessEvents() _eventsInProcess = false; break; } + eventArgs = _processPendingEventsQueue.Dequeue(); } @@ -524,6 +526,7 @@ internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArg break; } } + break; case RemotingTargetInterface.RunspacePool: @@ -924,6 +927,7 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve // you need to send an encrypted session key to the client _session.SendEncryptedSessionKey(); } + break; case RemoteSessionEvent.KeySent: @@ -934,6 +938,7 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve SetState(RemoteSessionState.EstablishedAndKeyExchanged, eventArgs.Reason); } } + break; case RemoteSessionEvent.KeyRequested: @@ -947,6 +952,7 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ServerDefaultKeepAliveTimeoutMs, Timeout.Infinite); } } + break; case RemoteSessionEvent.KeyReceiveFailed: @@ -958,12 +964,14 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve DoClose(this, eventArgs); } + break; case RemoteSessionEvent.KeySendFailed: { DoClose(this, eventArgs); } + break; } } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index 15236468b83..a1590ba5320 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -190,6 +190,7 @@ internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) // need to import the clients public key CreateRunspacePoolReceived.SafeInvoke(this, dataArg); } + break; case RemotingDataType.CloseSession: @@ -222,6 +223,7 @@ internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) negotiationArg.RemoteData = rcvdData; NegotiationReceived.SafeInvoke(this, negotiationArg); } + break; case RemotingDataType.PublicKey: @@ -229,6 +231,7 @@ internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) string remotePublicKey = RemotingDecoder.GetPublicKey(rcvdData.Data); PublicKeyReceived.SafeInvoke(this, new RemoteDataEventArgs(remotePublicKey)); } + break; default: From 175510530a7179797723b51d61420f636dd4f3eb Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:15 -0800 Subject: [PATCH 73/81] Update WireDataFormat --- .../remoting/common/WireDataFormat/EncodeAndDecode.cs | 7 +++++++ .../engine/remoting/common/WireDataFormat/RemoteHost.cs | 8 ++++++++ .../remoting/common/WireDataFormat/RemoteHostEncoder.cs | 4 ++++ .../common/WireDataFormat/RemoteSessionCapability.cs | 7 +++++++ 4 files changed, 26 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index d7cc1d6116a..7cc0df7b6a1 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -224,6 +224,7 @@ internal static class RemoteDataNameStrings $(if ($_nameFound.IndexOfAny($_varsRequiringQuotes) -eq -1) {'{0}{1}{2}'} else {'{0}{{{1}{2}}}'}) -f $_prefix, $_provider, $_nameFound } + break; } @@ -284,6 +285,7 @@ internal static class RemoteDataNameStrings { if ($_n -like $_pat) { '-' + $_n } } + break; } @@ -299,6 +301,7 @@ internal static class RemoteDataNameStrings $_pattern = '*' + $_pattern + '*' Get-History -Count 32767 | Sort-Object -Descending Id| ForEach-Object { $_.CommandLine } | where { $_ -like $_pattern } } + break; } @@ -724,6 +727,7 @@ internal static RemoteDataObject GenerateConnectRunspacePool( dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MinRunspaces, minRunspaces)); propertyCount++; } + if (maxRunspaces != -1) { dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MaxRunspaces, maxRunspaces)); @@ -1012,6 +1016,7 @@ internal static RemoteDataObject GenerateGetCommandMetadata(ClientRemotePowerShe break; } } + Dbg.Assert(getCommand != null, "Whoever sets PowerShell.IsGetCommandMetadataSpecialPipeline needs to make sure Get-Command is present"); string[] name = null; @@ -1562,6 +1567,7 @@ internal static ErrorRecord GetErrorRecordFromException(Exception exception) //doesn't have stack trace. Replace it with top level exception. er = new ErrorRecord(er, exception); } + return er; } @@ -2277,6 +2283,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) { powerShell.AddParameter("Module", module); } + powerShell.AddParameter("ArgumentList", argumentList); return powerShell; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index 751d615c451..19e0ceec46a 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -283,11 +283,17 @@ private RemoteHostResponse ExecuteNonVoidMethodOnObject(object instance) private object SelectTargetObject(PSHost host) { if (host == null || host.UI == null) { return null; } + if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } + if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; } + if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; } + if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return host.UI; } + if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; } + throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString()); } @@ -611,7 +617,9 @@ private static Exception DecodeException(PSObject psObject) { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); if (result == null) { return null; } + if (result is Exception) { return (Exception)result; } + throw RemoteHostExceptions.NewDecodingFailedException(); } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index ff6e33c40a2..c1631c1670e 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -93,6 +93,7 @@ private static object DecodeClassOrStruct(PSObject psObject, Type type) { FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (propertyInfo.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } + object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType); if (fieldValue == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } @@ -447,6 +448,7 @@ internal static object DecodeObject(object obj, Type type) { cred = null; } + return cred; } else if (obj is int && type.IsEnum) @@ -684,8 +686,10 @@ private static bool IsObjectDictionaryType(Type dictionaryType) { // True if the value-type of the dictionary is object; false otherwise. if (!IsDictionary(dictionaryType)) { return false; } + Type[] elementTypes = dictionaryType.GetGenericArguments(); if (elementTypes.Length != 2) { return false; } + Type valueType = elementTypes[1]; return valueType == typeof(object); } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 1bcee10332c..bcc67ce53cc 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -35,6 +35,7 @@ internal Version ProtocolVersion { return _protocolVersion; } + set { _protocolVersion = value; @@ -42,7 +43,9 @@ internal Version ProtocolVersion } internal Version PSVersion { get { return _psversion; } } + internal Version SerializationVersion { get { return _serversion; } } + internal RemotingDestination RemotingDestination { get { return _remotingDestination; } } /// @@ -140,6 +143,7 @@ internal static byte[] GetCurrentTimeZoneInByteFormat() internal TimeZoneInfo TimeZone { get { return _timeZone; } + set { _timeZone = value; } } } @@ -397,6 +401,7 @@ internal bool IsHostRawUINull internal bool UseRunspaceHost { get { return _useRunspaceHost; } + set { _useRunspaceHost = value; } } @@ -442,10 +447,12 @@ private static void CheckHostChain(PSHost host, ref bool isHostNull, ref bool is // Verify that the UI is not null. if (host.UI == null) { return; } + isHostUINull = false; // Verify that the raw UI is not null. if (host.UI.RawUI == null) { return; } + isHostRawUINull = false; } } From e91c119f5f019bc46f2572e4b56ac8936e2f7f23 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:15 -0800 Subject: [PATCH 74/81] Update Binding --- .../engine/runtime/Binding/Binders.cs | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 5321f520987..48425371dde 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -276,6 +276,7 @@ internal static Expression CastOrConvertMethodArgument(this DynamicMetaObject ta { return conversionResult; } + rank = ConversionRank.None; } @@ -416,6 +417,7 @@ private static Expression ProcessOnePSObject(DynamicMetaObject arg, ref BindingR expr = arg.Expression; restrictions = restrictions.Merge(arg.PSGetTypeRestriction()); } + return expr; } @@ -937,6 +939,7 @@ internal static PSArrayAssignmentRHSBinder Get(int i) { s_binders.Add(null); } + return s_binders[i] ?? (s_binders[i] = new PSArrayAssignmentRHSBinder(i)); } } @@ -996,6 +999,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje newArrayElements[i] = Expression.Call(temp, CachedReflectionInfo.IList_get_Item, ExpressionCache.Constant(i)); } + for (; i < _elements; ++i) { newArrayElements[i] = ExpressionCache.NullConstant; @@ -1136,6 +1140,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje { ilistExpr = Expression.Convert(ilistExpr, typeof(IList)); } + var countExpr = Expression.Property( Expression.Convert(ilistExpr, typeof(ICollection)), CachedReflectionInfo.ICollection_Count); @@ -1203,6 +1208,7 @@ internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitio s_binderCache.Add(key, result); } } + return result; } @@ -1380,6 +1386,7 @@ internal static object GetIDictionaryMember(IDictionary hash, object key) throw new PropertyNotFoundException("PropertyNotFoundStrict", null, ParserStrings.PropertyNotFoundStrict, LanguagePrimitives.ConvertTo(key)); } + return null; } } @@ -1611,6 +1618,7 @@ internal static PSAttributeGenerator Get(CallInfo callInfo) binder = new PSAttributeGenerator(callInfo); s_binderCache.Add(callInfo, binder); } + return binder; } } @@ -1731,6 +1739,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe return target.ThrowRuntimeError(args, BindingRestrictions.Empty, "PropertyIsReadOnly", ParserStrings.PropertyIsReadOnly, Expression.Constant(name)); } + propertyType = propertyInfo.PropertyType; lhs = Expression.Property(tmp.Cast(propertyInfo.DeclaringType), propertyInfo); } @@ -1974,30 +1983,35 @@ private static Expression GetExprForValueType(Type type, { restrictions = restrictions.Merge(GetVersionCheck(s_mutableValueWithInstanceMemberVersion)); } + return expr; } private static object EnumRule(CallSite site, object obj) { if (obj is Enum) { return obj; } + return ((CallSite>)site).Update(site, obj); } private static object BoolRule(CallSite site, object obj) { if (obj is bool) { return obj; } + return ((CallSite>)site).Update(site, obj); } private static object IntRule(CallSite site, object obj) { if (obj is int) { return obj; } + return ((CallSite>)site).Update(site, obj); } private static object ObjectRule(CallSite site, object obj) { if (!(obj is ValueType) && !(obj is PSObject)) { return obj; } + return ((CallSite>)site).Update(site, obj); } @@ -2112,6 +2126,7 @@ internal static PSBinaryOperationBinder Get(ExpressionType operation, bool ignor s_binderCache.Add(key, result); } } + return result; } @@ -2146,6 +2161,7 @@ private Func GetScalarCompareDelegate() lvalExpr, rvalExpr).Compile(); Interlocked.CompareExchange(ref _compareDelegate, compareDelegate, null); } + return _compareDelegate; } @@ -2252,6 +2268,7 @@ private string GetOperatorText() case ExpressionType.LeftShift: return TokenKind.Shl.Text(); case ExpressionType.RightShift: return TokenKind.Shr.Text(); } + Diagnostics.Assert(false, "Unexpected operator"); return string.Empty; } @@ -2439,6 +2456,7 @@ private DynamicMetaObject BinaryNumericOp(string methodName, DynamicMetaObject t target.CombineRestrictions(arg)); } } + opImplType = typeof(DecimalOps); argType = typeof(decimal); } @@ -2568,6 +2586,7 @@ internal static Expression ConvertStringToNumber(Expression expr, Type toType) // would string. Fall back to int if Parser.ScanNumber fails. toType = typeof(int); } + return Expression.Call(CachedReflectionInfo.Parser_ScanNumber, expr.Cast(typeof(string)), Expression.Constant(toType, typeof(Type))); } @@ -2612,6 +2631,7 @@ private static Type GetBitwiseOpType(TypeCode opTypeCode) else if ((int)opTypeCode <= (int)TypeCode.Int64) { opType = typeof(long); } // Because we use unsigned for -bnot, to be consistent, we promote to unsigned here too (-band,-bor,-xor) else { opType = typeof(ulong); } + return opType; } @@ -2850,6 +2870,7 @@ private DynamicMetaObject Shift(DynamicMetaObject target, DynamicMetaObject arg, { return PSConvertBinder.ThrowNoConversion(arg, typeof(int), this, _version); } + var numericArg = PSConvertBinder.InvokeConverter(conversion, arg.Expression, resultType, debase, ExpressionCache.InvariantCulture); if (typeCode == TypeCode.Decimal || typeCode == TypeCode.Double || typeCode == TypeCode.Single) @@ -2939,6 +2960,7 @@ private DynamicMetaObject BinaryBitwiseOp(DynamicMetaObject target, numericTarget = target; numericArg = arg; } + if (opTypeCode == TypeCode.Decimal) { opImplType = typeof(DecimalOps); @@ -3357,6 +3379,7 @@ private DynamicMetaObject BinaryComparisonCommon(DynamicMetaObject targetAsEnume case ExpressionType.LessThan: numericMethod = "CompareLt"; break; case ExpressionType.LessThanOrEqual: numericMethod = "CompareLe"; break; } + return BinaryNumericOp(numericMethod, target, numericArg); } @@ -3413,6 +3436,7 @@ internal static PSUnaryOperationBinder Get(ExpressionType operation) Interlocked.CompareExchange(ref s_decrementBinder, new PSUnaryOperationBinder(operation), null); return s_decrementBinder; } + throw new NotImplementedException("Unimplemented unary operation"); } @@ -3447,6 +3471,7 @@ public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject targe case ExpressionType.Decrement: return IncrDecr(target, -1, errorSuggestion).WriteToDebugLog(this); } + throw new NotImplementedException(); } @@ -3556,6 +3581,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro { targetConvertType = Enum.GetUnderlyingType(targetConvertType); } + targetExpr = target.Expression.Cast(targetConvertType); } else @@ -3576,6 +3602,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro { result = result.Cast(target.LimitType); } + return new DynamicMetaObject(result.Cast(typeof(object)), target.PSGetTypeRestriction()); } @@ -3602,6 +3629,7 @@ private DynamicMetaObject UnaryPlus(DynamicMetaObject target, DynamicMetaObject // promote to int, unary plus doesn't support byte directly. expr = expr.Cast(typeof(int)); } + return new DynamicMetaObject( Expression.UnaryPlus(expr).Cast(typeof(object)), target.PSGetTypeRestriction()); @@ -3634,6 +3662,7 @@ private DynamicMetaObject UnaryMinus(DynamicMetaObject target, DynamicMetaObject // promote to int, unary plus doesn't support byte directly. expr = expr.Cast(typeof(int)); } + return new DynamicMetaObject( Expression.Negate(expr).Cast(typeof(object)), target.PSGetTypeRestriction()); @@ -3702,6 +3731,7 @@ public static PSConvertBinder Get(Type type) s_binderCache.Add(type, result); } } + return result; } @@ -3847,6 +3877,7 @@ internal static Expression InvokeConverter(LanguagePrimitives.IConversionData co valueToConvert = value.Cast(typeof(object)); valueAsPSObject = ExpressionCache.NullPSObject; } + conv = Expression.Call( Expression.Constant(conversion.Converter), conversion.Converter.GetType().GetMethod("Invoke"), @@ -3863,10 +3894,12 @@ internal static Expression InvokeConverter(LanguagePrimitives.IConversionData co { return conv; } + if (resultType.IsValueType && Nullable.GetUnderlyingType(resultType) == null) { return Expression.Unbox(conv, resultType); } + return Expression.Convert(conv, resultType); } @@ -3900,6 +3933,7 @@ public static PSGetIndexBinder Get(int argCount, PSMethodInvocationConstraints c binder = new PSGetIndexBinder(tuple); s_binderCache.Add(tuple, binder); } + return binder; } } @@ -4068,6 +4102,7 @@ private DynamicMetaObject GetIndexDictionary(DynamicMetaObject target, // slicing, or possibly just invoke the indexer. return null; } + if (indexes[0].LimitType.IsArray && !keyType.IsArray) { // There was a conversion, but it's far more likely (and backwards compatible) that we want to do slicing @@ -4156,6 +4191,7 @@ private DynamicMetaObject IndexWithNegativeChecks( // if (StrictMode(3)) { throw } // $null // } + var targetTmp = Expression.Parameter(target.LimitType, "target"); var lenTmp = Expression.Parameter(typeof(int), "len"); var indexTmp = Expression.Parameter(typeof(int), "index"); @@ -4487,6 +4523,7 @@ public static PSSetIndexBinder Get(int argCount, PSMethodInvocationConstraints c binder = new PSSetIndexBinder(tuple); s_binderCache.Add(tuple, binder); } + return binder; } } @@ -4892,6 +4929,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy targetExpr = target.Expression.Convert(typeof(PSObject)); break; } + Diagnostics.Assert(mi != null, "ReservedMemberBinder doesn't support member Name"); return new DynamicMetaObject(WrapGetMemberInTry(Expression.Call(mi, targetExpr)), target.PSGetTypeRestriction()); @@ -4928,6 +4966,7 @@ static PSGetMemberBinder() private bool _hasInstanceMember; internal bool HasInstanceMember { get { return _hasInstanceMember; } } + internal static void SetHasInstanceMember(string memberName) { // We must invalidate dynamic sites (if any) when the first instance member (for this binder) @@ -5061,6 +5100,7 @@ private static PSGetMemberBinder Get(string memberName, Type classScope, bool @s result._hasInstanceMember = binderList[0]._hasInstanceMember; result._hasTypeTableMember = binderList[0]._hasTypeTableMember; } + binderList.Add(result); Diagnostics.Assert(binderList.All(b => b._hasInstanceMember == result._hasInstanceMember), @@ -5070,9 +5110,11 @@ private static PSGetMemberBinder Get(string memberName, Type classScope, bool @s } } } + s_binderCache.Add(tuple, result); } } + return result; } @@ -5325,6 +5367,7 @@ internal static bool IsGenericDictionary(object value, ref Type genericTypeArg) } } } + return isGeneric; } @@ -5371,6 +5414,7 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy : Expression.Unbox(expr, type)) : expr.Cast(type); } + return expr; } @@ -5514,6 +5558,7 @@ private PSMemberInfo ResolveAlias(PSAliasProperty alias, DynamicMetaObject targe { throw new ExtendedTypeSystemException("CycleInAliasLookup", null, ExtendedTypeSystem.CycleInAlias, alias.Name); } + aliases.Add(alias.Name); } @@ -5692,6 +5737,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, { candidateMethods = new List(); } + candidateMethods.Add(methodInfo); } } @@ -5809,6 +5855,7 @@ internal static object GetAdaptedValue(object obj, string member) throw new PropertyNotFoundException("PropertyNotFoundStrict", null, ParserStrings.PropertyNotFoundStrict, LanguagePrimitives.ConvertTo(member)); } + return null; } @@ -5859,6 +5906,7 @@ internal static bool TryGetGenericDictionaryValue(IDictionary hash value = result; return true; } + value = null; return false; } @@ -5892,6 +5940,7 @@ public int GetHashCode(PSSetMemberBinderKeyType obj) obj.Item3.GetHashCode()); } } + private static readonly Dictionary s_binderCache = new Dictionary(new KeyComparer()); @@ -5904,6 +5953,7 @@ public static PSSetMemberBinder Get(string memberName, TypeDefinitionAst classSc var classScope = classScopeAst != null ? classScopeAst.Type : null; return Get(memberName, classScope, @static); } + public static PSSetMemberBinder Get(string memberName, Type classScope, bool @static) { PSSetMemberBinder result; @@ -5917,6 +5967,7 @@ public static PSSetMemberBinder Get(string memberName, Type classScope, bool @st s_binderCache.Add(tuple, result); } } + return result; } @@ -5939,11 +5990,13 @@ private Expression GetTransformedExpression(IEnumerable 1) @@ -7411,6 +7475,7 @@ internal static bool TryGetInstanceMethod(object value, string memberName, out P throw InterpreterError.NewInterpreterException(memberName, typeof(RuntimeException), null, "MethodNotFound", ParserStrings.MethodNotFound, ParserOps.GetTypeFullName(value), memberName); } + return true; } @@ -7470,8 +7535,10 @@ public static PSCreateInstanceBinder Get(CallInfo callInfo, PSMethodInvocationCo s_binderCache.Add(key, result); } } + return result; } + internal static void InvalidateCache() { // Invalidate binders @@ -7645,6 +7712,7 @@ public static PSInvokeBaseCtorBinder Get(CallInfo callInfo, PSMethodInvocationCo s_binderCache.Add(key, result); } } + return result; } From 936ddc69c90d69761b6941474eee0196677fed57 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:16 -0800 Subject: [PATCH 75/81] Update Operations --- .../engine/runtime/Operations/ArrayOps.cs | 3 + .../engine/runtime/Operations/ClassOps.cs | 3 + .../engine/runtime/Operations/MiscOps.cs | 31 ++++++++++ .../engine/runtime/Operations/NumericOps.cs | 60 +++++++++++++++++++ .../engine/runtime/Operations/VariableOps.cs | 6 ++ 5 files changed, 103 insertions(+) diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index 88207bd9422..4ee9df04863 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -31,6 +31,7 @@ internal static object[] SlicingIndex(object target, object[] indexes, Func ub) { // In strict mode, don't return, fall through and let Array.GetValue raise an exception. @@ -205,6 +207,7 @@ internal static object GetMDArrayValueOrSlice(Array array, object indexes) Array.Copy(result, shortResult, j); return shortResult; } + return result; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 631323afe34..b2e220bcac8 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -90,6 +90,7 @@ public object GetSessionState() { _stateMap.TryGetValue(defaultRunspace, out ss); } + return ss; } } @@ -217,6 +218,7 @@ private void PrepareScriptBlockToInvoke(object instance, object sessionStateInte } } } + _boundScriptBlock.Value.SessionStateInternal = sessionStateToUse; } @@ -363,6 +365,7 @@ private static DynamicMethod CreateDynamicMethod(MethodInfo mi) { il.Emit(OpCodes.Ldarg, i); } + il.Emit(OpCodes.Tailcall); il.EmitCall(OpCodes.Call, mi, null); il.Emit(OpCodes.Ret); diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 0045fd44278..36efda050c3 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -60,6 +60,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeCallOperatorAcrossLanguageBoundaries", ParserStrings.CantInvokeCallOperatorAcrossLanguageBoundaries); } + commandSessionState = mi.SessionState.Internal; commandIndex += 1; } @@ -145,6 +146,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, { InvocationName = invocationName }; rte.ErrorRecord.SetInvocationInfo(invocationInfo); } + throw; } } @@ -249,21 +251,25 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, commandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput; } } + if (!redirectedWarning && (context.ExpressionWarningOutputPipe != null)) { commandProcessor.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe; redirectedWarning = true; } + if (!redirectedVerbose && (context.ExpressionVerboseOutputPipe != null)) { commandProcessor.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe; redirectedVerbose = true; } + if (!redirectedDebug && (context.ExpressionDebugOutputPipe != null)) { commandProcessor.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe; redirectedDebug = true; } + if (!redirectedInformation && (context.ExpressionInformationOutputPipe != null)) { commandProcessor.CommandRuntime.InformationOutputPipe = context.ExpressionInformationOutputPipe; @@ -323,6 +329,7 @@ internal static IEnumerable Splat(object splattedValue string parameterText = GetParameterText(parameterName); if (markUntrustedData) { ExecutionContext.MarkObjectAsUntrusted(parameterValue); } + yield return CommandParameterInternal.CreateParameterWithArgument( splatAst, parameterName, parameterText, splatAst, parameterValue, false); @@ -336,6 +343,7 @@ internal static IEnumerable Splat(object splattedValue foreach (object obj in enumerableValue) { if (markUntrustedData) { ExecutionContext.MarkObjectAsUntrusted(obj); } + yield return SplatEnumerableElement(obj, splatAst); } } @@ -386,6 +394,7 @@ private static string GetParameterText(string parameterName) string whitespaces = parameterName.Substring(endPosition); parameterText = "-" + parameterName.Substring(0, endPosition) + ":" + whitespaces; } + return parameterText; } @@ -532,6 +541,7 @@ internal static void InvokePipelineInBackground( position = v.Extent.EndOffset - pipelineOffset; } } + updatedScriptblock.Append(scriptblockBodyString.Substring(position)); var sb = ScriptBlock.Create(updatedScriptblock.ToString()); var commandInfo = new CmdletInfo("Start-Job", typeof(StartJobCommand)); @@ -578,6 +588,7 @@ internal static object CheckAutomationNullInCommandArgument(object obj) { return null; } + var objAsArray = obj as object[]; return objAsArray != null ? CheckAutomationNullInCommandArgumentArray(objAsArray) : obj; } @@ -759,6 +770,7 @@ internal static object PipelineResult(List resultList) { return AutomationNull.Value; } + var result = resultCount == 1 ? resultList[0] : resultList.ToArray(); // Clear the array list so that we don't write the results of the pipe when flushing the pipe. resultList.Clear(); @@ -823,6 +835,7 @@ protected CommandRedirection(RedirectionStream from) } internal RedirectionStream FromStream { get; private set; } + internal abstract void Bind(PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context); internal void UnbindForExpression(FunctionContext funcContext, Pipe[] pipes) @@ -1003,7 +1016,9 @@ public override string ToString() } internal string File { get; private set; } + internal bool Appending { get; private set; } + private PipelineProcessor PipelineProcessor { get; set; } // Handle binding file redirection for commands, like: @@ -1114,6 +1129,7 @@ internal Pipe[] BindForExpression(FunctionContext funcContext) context.ExpressionInformationOutputPipe = pipe; break; } + return oldPipes; } @@ -1172,6 +1188,7 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par // I think this is only necessary for calling Dispose on the commands in the redirection pipe. parentPipelineProcessor.AddRedirectionPipe(PipelineProcessor); } + return new Pipe(context, PipelineProcessor); } @@ -1497,6 +1514,7 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte var errorRecord = new ErrorRecord(current.ErrorRecordToPass, current.ExceptionToPass); tuple.SetAutomaticVariable(AutomaticVariable.Underbar, errorRecord, context); } + return current.Handler; } @@ -1685,6 +1703,7 @@ private static ActionPreference ProcessTraps(FunctionContext funcContext, { locals.SetValue(i, funcContext._localsTuple.GetValue(i)); } + var newScope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = newScope; newScope.LocalsTuple = locals; @@ -2503,10 +2522,12 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W } } } + if (numberToReturn == 1) { return new Object[] { current }; } + return rest.ToArray(); } @@ -2538,6 +2559,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W var e = Current(enumerator); rest.Add(e); } + return new System.Object[] { first, rest.ToArray() }; } @@ -2550,6 +2572,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W { notMatched = new Collection(); } + var resultCollection = new List(); Pipe outputPipe = new Pipe(resultCollection); bool returnTheRest = false; @@ -2657,6 +2680,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W var ie = Current(enumerator); notMatched.Add(ie == null ? null : PSObject.AsPSObject(ie)); } + return new System.Object[] { matches, notMatched }; } @@ -2703,6 +2727,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object object current = Current(enumerator); list.Add(current); } + return LanguagePrimitives.ConvertTo(list, targetType, CultureInfo.InvariantCulture); } @@ -2715,6 +2740,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException), null, "ForEachBadGenericConversionTypeSpecified", ParserStrings.ForEachBadGenericConversionTypeSpecified, ParserOps.ConvertTo(targetType, null)); } + resultCollection = PSObject.AsPSObject(Activator.CreateInstance(targetType)); while (MoveNext(context, enumerator)) { @@ -2832,6 +2858,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object ExtendedTypeSystem.MethodInvocationException, name, arguments.Length, nullRefException.Message); } + continue; } @@ -2934,6 +2961,7 @@ internal static object SlicingIndex(object target, IEnumerator indexes, Func rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(int lhs, int rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } internal static object[] Range(int lower, int upper) @@ -129,6 +137,7 @@ internal static object Add(uint lhs, uint rhs) { return (uint)result; } + return (double)result; } @@ -139,6 +148,7 @@ internal static object Sub(uint lhs, uint rhs) { return (uint)result; } + return (double)result; } @@ -149,6 +159,7 @@ internal static object Multiply(uint lhs, uint rhs) { return (uint)result; } + return (double)result; } @@ -187,10 +198,15 @@ internal static object Remainder(uint lhs, uint rhs) } internal static object CompareEq(uint lhs, uint rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } + internal static object CompareNe(uint lhs, uint rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLt(uint lhs, uint rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLe(uint lhs, uint rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGt(uint lhs, uint rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(uint lhs, uint rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } @@ -203,6 +219,7 @@ internal static object Add(long lhs, long rhs) { return (long)result; } + return (double)result; } @@ -213,6 +230,7 @@ internal static object Sub(long lhs, long rhs) { return (long)result; } + return (double)result; } @@ -226,6 +244,7 @@ internal static object Multiply(long lhs, long rhs) { return (long)biResult; } + return (double)biResult; } @@ -278,10 +297,15 @@ internal static object Remainder(long lhs, long rhs) } internal static object CompareEq(long lhs, long rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } + internal static object CompareNe(long lhs, long rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLt(long lhs, long rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLe(long lhs, long rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGt(long lhs, long rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(long lhs, long rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } @@ -294,6 +318,7 @@ internal static object Add(ulong lhs, ulong rhs) { return (ulong)result; } + return (double)result; } @@ -304,6 +329,7 @@ internal static object Sub(ulong lhs, ulong rhs) { return (ulong)result; } + return (double)result; } @@ -317,6 +343,7 @@ internal static object Multiply(ulong lhs, ulong rhs) { return (ulong)biResult; } + return (double)biResult; } @@ -355,10 +382,15 @@ internal static object Remainder(ulong lhs, ulong rhs) } internal static object CompareEq(ulong lhs, ulong rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } + internal static object CompareNe(ulong lhs, ulong rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLt(ulong lhs, ulong rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLe(ulong lhs, ulong rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGt(ulong lhs, ulong rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(ulong lhs, ulong rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } @@ -472,6 +504,7 @@ internal static object BOr(decimal lhs, decimal rhs) return (long)(l | r); } } + return l | r; } @@ -488,6 +521,7 @@ internal static object BXor(decimal lhs, decimal rhs) return (long)(l ^ r); } } + return l ^ r; } @@ -504,6 +538,7 @@ internal static object BAnd(decimal lhs, decimal rhs) return (long)(l & r); } } + return l & r; } @@ -517,6 +552,7 @@ private static ulong ConvertToUlong(decimal val) long lValue = LanguagePrimitives.ConvertTo(val); return unchecked((ulong)lValue); } + return LanguagePrimitives.ConvertTo(val); } @@ -575,10 +611,15 @@ internal static object RightShift(decimal val, int count) } internal static object CompareEq(decimal lhs, decimal rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } + internal static object CompareNe(decimal lhs, decimal rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLt(decimal lhs, decimal rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLe(decimal lhs, decimal rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGt(decimal lhs, decimal rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(decimal lhs, decimal rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } private static object CompareWithDouble(decimal left, double right, @@ -616,17 +657,27 @@ private static object CompareWithDouble(double left, decimal right, } internal static object CompareEq1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); } + internal static object CompareNe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); } + internal static object CompareLt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); } + internal static object CompareLe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); } + internal static object CompareGt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); } + internal static object CompareGe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); } internal static object CompareEq2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); } + internal static object CompareNe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); } + internal static object CompareLt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); } + internal static object CompareLe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); } + internal static object CompareGt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); } + internal static object CompareGe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); } } @@ -706,6 +757,7 @@ internal static object BOr(double lhs, double rhs) return (long)(l | r); } } + return l | r; } @@ -722,6 +774,7 @@ internal static object BXor(double lhs, double rhs) return (long)(l ^ r); } } + return l ^ r; } @@ -738,6 +791,7 @@ internal static object BAnd(double lhs, double rhs) return (long)(l & r); } } + return l & r; } @@ -751,6 +805,7 @@ private static ulong ConvertToUlong(double val) long lValue = LanguagePrimitives.ConvertTo(val); return unchecked((ulong)lValue); } + return LanguagePrimitives.ConvertTo(val); } @@ -815,10 +870,15 @@ internal static object RightShift(double val, int count) } internal static object CompareEq(double lhs, double rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } + internal static object CompareNe(double lhs, double rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLt(double lhs, double rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } + internal static object CompareLe(double lhs, double rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGt(double lhs, double rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } + internal static object CompareGe(double lhs, double rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index ca420c2a905..f26fce16a00 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -85,6 +85,7 @@ internal static object SetVariableValue(VariablePath variablePath, object value, throw e; } + var.SetValueRaw(value, true); // Don't update the PSVariable's attributes until we successfully set the value var.Attributes.Clear(); @@ -135,8 +136,10 @@ private static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionC { return false; } + parent = parent.Parent; } + return true; } @@ -164,6 +167,7 @@ internal static object GetAutomaticVariableValue(int tupleIndex, ExecutionContex result = null; } + return result; } @@ -228,6 +232,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio staticType = value.GetType(); } } + if (staticType == null) { var declaredType = var.Attributes.OfType().FirstOrDefault(); @@ -244,6 +249,7 @@ private static Collection GetAttributeCollection(AttributeBaseAst[] a { result.Add(attributeAst.GetAttribute()); } + return result; } From e57479e6d78c9f4e98af3dc2a3017de6b158d2b6 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:16 -0800 Subject: [PATCH 76/81] Update interface --- .../engine/lang/interface/PSParser.cs | 1 + .../engine/lang/interface/PSToken.cs | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/src/System.Management.Automation/engine/lang/interface/PSParser.cs b/src/System.Management.Automation/engine/lang/interface/PSParser.cs index 806eb4eb076..2e44c622794 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParser.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParser.cs @@ -184,6 +184,7 @@ public static Collection Tokenize(object[] script, out Collection Date: Sun, 23 Dec 2018 09:46:20 -0800 Subject: [PATCH 77/81] Update cmdletization --- .../cimSupport/cmdletization/SessionBasedWrapper.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 8c10a2dfbb0..61cab210aaf 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -60,6 +60,7 @@ protected virtual void Dispose(bool disposing) _parentJob = null; } } + _disposed = true; } } @@ -75,6 +76,7 @@ protected virtual void Dispose(bool disposing) protected TSession[] Session { get { return _session ?? (_session = new TSession[] { this.DefaultSession }); } + set { if (value == null) @@ -86,6 +88,7 @@ protected TSession[] Session _sessionWasSpecified = true; } } + private TSession[] _session; private bool _sessionWasSpecified; @@ -96,8 +99,10 @@ protected TSession[] Session public SwitchParameter AsJob { get { return _asJob; } + set { _asJob = value; } } + private bool _asJob; /// @@ -319,6 +324,7 @@ private enum JobOutputs NonPipelineResults = Output | Error | Warning | Verbose | Debug | Progress, PipelineResults = Results, } + private static void DiscardJobOutputs(Job job, JobOutputs jobOutputsToDiscard) { if (JobOutputs.Output == (jobOutputsToDiscard & JobOutputs.Output)) @@ -523,6 +529,7 @@ private IEnumerable GetSessionsToActAgainst(MethodInvocationInfo metho associatedSessions.Add(associatedSession); } } + if (associatedSessions.Count == 1) { return associatedSessions; @@ -636,6 +643,7 @@ public override void BeginProcessing() { conflictingParameter = "Confirm"; } + if (conflictingParameter != null) { string errorMessage = string.Format( From 41fcf7ea59c29c0a851ba794b967906cbfc043e4 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:21 -0800 Subject: [PATCH 78/81] Update cim --- .../cmdletization/cim/CimJobException.cs | 2 ++ .../cim/EnumerateAssociatedInstancesJob.cs | 1 + .../cim/ExtrinsicMethodInvocationJob.cs | 2 ++ .../cim/MethodInvocationJobBase.cs | 1 + .../cmdletization/cim/ModifyInstanceJob.cs | 1 + .../cmdletization/cim/QueryJobBase.cs | 3 +++ .../cim/TerminatingErrorTracker.cs | 3 +++ .../cmdletization/cim/cimChildJobBase.cs | 20 +++++++++++++++++++ .../cim/cimCmdletDefinitionContext.cs | 8 ++++++++ .../cim/cimCmdletInvocationContext.cs | 6 ++++++ .../cmdletization/cim/cimConverter.cs | 14 +++++++++++++ .../cmdletization/cim/cimJobContext.cs | 3 +++ .../cim/cimOperationOptionsHelper.cs | 1 + .../cimSupport/cmdletization/cim/cimQuery.cs | 3 +++ .../cmdletization/cim/cimWrapper.cs | 10 ++++++++++ .../cmdletization/cim/clientSideQuery.cs | 11 ++++++++++ 16 files changed, 89 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 4493c263a06..6525de9fa52 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -125,6 +125,7 @@ internal static CimJobException CreateFromAnyException( errorId: "CimJob_" + inner.GetType().Name, errorCategory: ErrorCategory.NotSpecified); } + return cimJobException; } @@ -352,6 +353,7 @@ public ErrorRecord ErrorRecord { get { return _errorRecord; } } + private ErrorRecord _errorRecord; internal bool IsTerminatingError diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs index c28363eae55..fe3dba1ae7a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -89,6 +89,7 @@ internal override void WriteObject(object outputObject) PSObject pso = PSObject.AsPSObject(outputObject); AddShowComputerNameMarker(pso); } + base.WriteObject(outputObject); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 1b7fbf99da9..d21e5564a3b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -130,6 +130,7 @@ private void OnNext(CimMethodResult methodResult) var tmp = new PSNoteProperty(element.Key, element.Value.Value); propertyBag.Properties.Add(tmp); } + this.WriteObject(propertyBag); } } @@ -179,6 +180,7 @@ private void WriteObject(object cmdletOutput, MethodParameter methodParameter) pso.TypeNames.Insert(0, methodParameter.ParameterTypeName); } } + this.WriteObject(cmdletOutput); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs index f93c54cd7c4..8512492cabd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -58,6 +58,7 @@ private IEnumerable GetMethodInputParametersCore(Func _privateData; private const string QueryLanguageKey = "QueryDialect"; @@ -47,8 +51,10 @@ public bool UseEnumerateInstancesInsteadOfWql { newValue = true; } + _useEnumerateInstancesInsteadOfWql = newValue; } + return _useEnumerateInstancesInsteadOfWql.Value; } } @@ -122,6 +128,7 @@ public Uri ResourceUri _resourceUriHasBeenCalculated = true; } + return _resourceUri; } } @@ -164,6 +171,7 @@ public CimOperationFlags SchemaConformanceLevel _schemaConformanceLevel = newSchemaConformanceLevel; } + return _schemaConformanceLevel.Value; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs index 96fd9c1e376..9bb778ffb72 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -82,11 +82,17 @@ private static void WarnAboutUnsupportedActionPreferences( public CimCmdletDefinitionContext CmdletDefinitionContext { get; private set; } public InvocationInfo CmdletInvocationInfo { get; private set; } + public MshCommandRuntime.ShouldProcessPossibleOptimization ShouldProcessOptimization { get; private set; } + public ActionPreference ErrorActionPreference { get; private set; } + public ActionPreference WarningActionPreference { get; private set; } + public ActionPreference VerboseActionPreference { get; private set; } + public ActionPreference DebugActionPreference { get; private set; } + public string NamespaceOverride { get; private set; } public bool IsRunningInBackground diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 6c6e7b95542..cc435687849 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -52,6 +52,7 @@ private unsafe void Copy(char* source, int offset, int charsToCopy) { throw new ArgumentOutOfRangeException("offset"); } + if (offset + charsToCopy > _string.Length) { throw new ArgumentOutOfRangeException("charsToCopy"); @@ -148,6 +149,7 @@ private void Dispose(bool disposing) { d.Dispose(); } + _trackedDisposables.Clear(); } } @@ -173,6 +175,7 @@ internal object ConvertFromDotNetToCim(object dotNetObject) var sensitiveString = new SensitiveString(escapedUsername.Length + PSCredentialDelimiter.Length + credential.Password.Length); lock (_trackedDisposables) { _trackedDisposables.Add(sensitiveString); } + sensitiveString.Copy(escapedUsername, 0); sensitiveString.Copy(PSCredentialDelimiter, escapedUsername.Length); sensitiveString.Copy(credential.Password, escapedUsername.Length + PSCredentialDelimiter.Length); @@ -184,6 +187,7 @@ internal object ConvertFromDotNetToCim(object dotNetObject) SecureString secureString = (SecureString)psObject.BaseObject; var sensitiveString = new SensitiveString(secureString.Length); lock (_trackedDisposables) { _trackedDisposables.Add(sensitiveString); } + sensitiveString.Copy(secureString, 0); return sensitiveString.Value; } @@ -201,6 +205,7 @@ internal object ConvertFromDotNetToCim(object dotNetObject) object cimElement = ConvertFromDotNetToCim(dotNetArray.GetValue(i)); cimArray.SetValue(cimElement, i); } + return cimArray; } } @@ -244,10 +249,12 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) { return psObject.BaseObject; } + if (typeof(CimInstance).IsAssignableFrom(dotNetType)) { return psObject.BaseObject; } + if (typeof(PSReference).IsAssignableFrom(dotNetType)) { PSReference psReference = (PSReference)psObject.BaseObject; @@ -275,6 +282,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) object cimElement = ConvertFromDotNetToCim(dotNetArray.GetValue(i)); cimArray.SetValue(cimElement, i); } + return cimArray; } } @@ -358,6 +366,7 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot { return LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture); } + if (expectedDotNetType == typeof(CimInstance)) { return LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture); @@ -375,6 +384,7 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot object dotNetElement = ConvertFromCimToDotNet(cimArray.GetValue(i), dotNetElementType); dotNetArray.SetValue(dotNetElement, i); } + return dotNetArray; } } @@ -484,6 +494,7 @@ internal static CimType GetCimTypeEnum(Type dotNetType) { return CimType.Reference; } + if (typeof(PSReference[]).IsAssignableFrom(dotNetType)) { return CimType.ReferenceArray; @@ -510,10 +521,12 @@ internal static Type GetCimType(Type dotNetType) { return dotNetType; } + if (dotNetType == typeof(CimInstance)) { return dotNetType; } + if (dotNetType == typeof(PSReference)) { return dotNetType; @@ -615,6 +628,7 @@ internal static Type GetElementType(Type arrayType) { return null; } + Type elementType = arrayType.GetElementType(); if (elementType.IsArray) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs index 89f0cad9064..ee68da063a6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -24,6 +24,7 @@ internal CimJobContext( public CimCmdletInvocationContext CmdletInvocationContext { get; private set; } public CimSession Session { get; private set; } + public object TargetObject { get; private set; } public string ClassName @@ -42,6 +43,7 @@ public string ClassNameOrNullIfResourceUriIsUsed { return null; } + return this.ClassName; } } @@ -54,6 +56,7 @@ public string Namespace { return this.CmdletInvocationContext.NamespaceOverride; } + return GetCimNamespace(this.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassName); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs index bbd6bad2fc8..11a1c8519a6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -104,6 +104,7 @@ internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictiona result = MergeOptions(result, instanceRelatedToThisOperation); } } + return result; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index fcdde574011..989cbcabe1a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -97,6 +97,7 @@ private static string ObjectToWqlLiteral(object o) { return "TRUE"; // based on http://msdn.microsoft.com/library/aa394054(VS.85).aspx } + return "FALSE"; // based on http://msdn.microsoft.com/library/aa394054(VS.85).aspx } @@ -317,6 +318,7 @@ public override void AddQueryOption(string optionName, object optionValue) { throw new ArgumentNullException("optionName"); } + if (optionValue == null) { throw new ArgumentNullException("optionValue"); @@ -360,6 +362,7 @@ CimSession ISessionBoundQueryBuilder.GetTargetSession() { return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(_associatedObject); } + return null; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index 81fc991dd4e..46bd4f016e7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -43,6 +43,7 @@ public CimSession[] CimSession { return base.Session; } + set { base.Session = value; @@ -64,12 +65,14 @@ public override int ThrottleLimit return this.CmdletDefinitionContext.DefaultThrottleLimit; } + set { base.ThrottleLimit = value; _throttleLimitIsSetExplicitly = true; } } + private bool _throttleLimitIsSetExplicitly; #endregion @@ -96,6 +99,7 @@ internal CimCmdletInvocationContext CmdletInvocationContext this.GetDynamicNamespace())); } } + private CimCmdletInvocationContext _cmdletInvocationContext; internal CimCmdletDefinitionContext CmdletDefinitionContext @@ -111,9 +115,11 @@ internal CimCmdletDefinitionContext CmdletDefinitionContext this.Cmdlet.CommandInfo.CommandMetadata.SupportsShouldProcess, this.PrivateData); } + return _cmdletDefinitionContext; } } + private CimCmdletDefinitionContext _cmdletDefinitionContext; internal InvocationInfo CmdletInvocationInfo @@ -175,6 +181,7 @@ internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder b { return null; } + if (!IsSupportedSession(session, tracker)) { return null; @@ -201,6 +208,7 @@ internal override StartableJob CreateInstanceMethodInvocationJob(CimSession sess { return null; } + if (!IsSupportedSession(session, tracker)) { return null; @@ -301,6 +309,7 @@ internal override StartableJob CreateStaticMethodInvocationJob(CimSession sessio { return null; } + if (!IsSupportedSession(session, tracker)) { return null; @@ -344,6 +353,7 @@ internal static CimSession GetSessionOfOriginFromCimInstance(CimInstance instanc { s_cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); } + return result; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index f07114a5379..084d61ecab0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -54,7 +54,9 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn } public string PropertyName { get; private set; } + public object PropertyValue { get; private set; } + public Func ErrorMessageGenerator { get; private set; } private static string GetErrorMessageForNotFound(string queryDescription, string className) @@ -151,6 +153,7 @@ private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase { private readonly List _propertyValueFilters = new List(); protected IEnumerable PropertyValueFilters { get { return _propertyValueFilters; } } + protected void AddPropertyValueFilter(PropertyValueFilter propertyValueFilter) { _propertyValueFilters.Add(propertyValueFilter); @@ -170,6 +173,7 @@ protected override bool IsMatchCore(CimInstance cimInstance) } } } + return isMatch; } } @@ -345,9 +349,11 @@ public BehaviorOnNoMatch BehaviorOnNoMatch { _behaviorOnNoMatch = this.GetDefaultBehaviorWhenNoMatchesFound(this.CimTypedExpectedPropertyValue); } + return _behaviorOnNoMatch; } } + protected abstract BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue); private BehaviorOnNoMatch _behaviorOnNoMatch; @@ -371,6 +377,7 @@ public bool IsMatch(CimInstance o) { return false; } + object actualPropertyValue = propertyInfo.Value; if (CimTypedExpectedPropertyValue == null) @@ -422,6 +429,7 @@ private static bool IsSameType(object actualPropertyValue, object expectedProper { return true; } + if (expectedPropertyValue == null) { return true; @@ -491,6 +499,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV expectedPropertyValue = expectedPropertyValue.ToString(); actualPropertyValue = actualPropertyValue.ToString(); } + var expectedPropertyValueAsString = expectedPropertyValue as string; if (expectedPropertyValueAsString != null) { @@ -510,10 +519,12 @@ private static bool WildcardEqual(string propertyName, object actualPropertyValu { return false; } + if (!LanguagePrimitives.TryConvertTo(expectedPropertyValue, out expectedPropertyValueAsString)) { return false; } + return WildcardPattern.Get(expectedPropertyValueAsString, WildcardOptions.IgnoreCase).IsMatch(actualPropertyValueAsString); } } From 243eef1ede873f6904ced85f1cedbb4c4b939f10 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:22 -0800 Subject: [PATCH 79/81] Update management --- .../management/ClearPropertyCommand.cs | 1 + .../management/ClearRecycleBinCommand.cs | 6 ++ .../commands/management/Computer.cs | 37 +++++++++ .../commands/management/ContentCommandBase.cs | 6 ++ .../management/ControlPanelItemCommand.cs | 14 ++++ .../management/CopyPropertyCommand.cs | 3 + .../commands/management/Eventlog.cs | 53 ++++++++++++ .../commands/management/GetChildrenCommand.cs | 8 ++ .../management/GetClipboardCommand.cs | 9 +++ .../management/GetComputerInfoCommand.cs | 13 +++ .../commands/management/GetContentCommand.cs | 4 + .../commands/management/GetPropertyCommand.cs | 3 + .../management/GetWMIObjectCommand.cs | 11 +++ .../commands/management/Hotfix.cs | 6 ++ .../management/InvokeWMIMethodCommand.cs | 19 +++++ .../management/MovePropertyCommand.cs | 5 ++ .../commands/management/Navigation.cs | 22 +++++ .../commands/management/NewPropertyCommand.cs | 2 + .../commands/management/ParsePathCommand.cs | 1 + .../PassThroughPropertyCommandBase.cs | 1 + .../commands/management/PingPathCommand.cs | 5 ++ .../commands/management/Process.cs | 69 ++++++++++++++++ .../management/RegisterWMIEventCommand.cs | 3 + .../management/RemovePropertyCommand.cs | 3 + .../management/RemoveWMIObjectCommand.cs | 11 +++ .../management/RenamePropertyCommand.cs | 1 + .../commands/management/ResolvePathCommand.cs | 3 + .../commands/management/Service.cs | 81 +++++++++++++++++++ .../management/SetClipboardCommand.cs | 4 + .../commands/management/SetPropertyCommand.cs | 4 + .../management/SetWMIInstanceCommand.cs | 9 +++ .../management/StartTransactionCommand.cs | 6 ++ .../management/UseTransactionCommand.cs | 2 + .../commands/management/WMIHelper.cs | 60 ++++++++++++++ .../commands/management/WebServiceProxy.cs | 19 +++++ .../management/WriteContentCommandBase.cs | 1 + 36 files changed, 505 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs index e69bc7ea455..d524d11b12f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -97,6 +97,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) propertyCollection, context); } + return InvokeProvider.Property.ClearPropertyDynamicParameters( ".", propertyCollection, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 9e2ec6eb743..1916d600176 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -33,6 +33,7 @@ public class ClearRecycleBinCommand : PSCmdlet public string[] DriveLetter { get { return _drivesList; } + set { _drivesList = value; } } @@ -46,6 +47,7 @@ public SwitchParameter Force { return _force; } + set { _force = value; @@ -134,6 +136,7 @@ private bool ValidDrivePath(string drivePath) // The drive path exists, and the drive is 'fixed'. return true; } + WriteError(new ErrorRecord( new ArgumentException( String.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveType, drivePath, "Get-Volume")), @@ -141,6 +144,7 @@ private bool ValidDrivePath(string drivePath) ErrorCategory.InvalidArgument, drivePath)); } + return false; } @@ -175,6 +179,7 @@ private string GetDrivePath(string driveName) { drivePath = driveName + ":\\"; } + return drivePath; } @@ -251,6 +256,7 @@ internal enum RecycleFlags : uint SHERB_NOPROGRESSUI = 0x00000002, SHERB_NOSOUND = 0x00000004 } + [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 2530f714d9c..80cdb8fa14a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -239,12 +239,14 @@ public class RestartComputerCommand : PSCmdlet, IDisposable public int Timeout { get { return _timeout; } + set { _timeout = value; _timeoutSpecified = true; } } + private int _timeout = -1; private bool _timeoutSpecified = false; @@ -256,12 +258,14 @@ public int Timeout public WaitForServiceTypes For { get { return _waitFor; } + set { _waitFor = value; _waitForSpecified = true; } } + private WaitForServiceTypes _waitFor = WaitForServiceTypes.PowerShell; private bool _waitForSpecified = false; @@ -274,12 +278,14 @@ public WaitForServiceTypes For public Int16 Delay { get { return (Int16)_delay; } + set { _delay = value; _delaySpecified = true; } } + private int _delay = 5; private bool _delaySpecified = false; @@ -295,13 +301,16 @@ public Int16 Delay $arguments = @{ ComputerName = $computerName ScriptBlock = { $true } + SessionOption = NewPSSessionOption -NoMachineProfile ErrorAction = 'SilentlyContinue' } + if ( $null -ne $array[0] ) { $arguments['Credential'] = $array[0] } + $result[$computerName] = (Invoke-Command @arguments) -as [bool] } $result @@ -418,6 +427,7 @@ private void ValidateComputerNames() { WriteError(error); } + continue; } @@ -527,6 +537,7 @@ private List TestRestartStageUsingWsman(IEnumerable computerName try { if (token.IsCancellationRequested) { break; } + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, token, this)) { bool itemRetrieved = false; @@ -668,6 +679,7 @@ internal static List TestWmiConnectionUsingWsman(List computerNa try { if (token.IsCancellationRequested) { break; } + using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credential, wsmanAuthentication, token, cmdlet)) { bool itemRetrieved = false; @@ -924,6 +936,7 @@ protected override void ProcessRecord() // We check if the target machine has already rebooted by querying the LastBootUpTime from the Win32_OperatingSystem object. // So after this step, we are sure that both the Network and the WMI or WinRM service have already come up. if (_exit) { break; } + if (restartStageTestList.Count > 0) { if (_waitOnComputers.Count == 1) @@ -932,12 +945,14 @@ protected override void ProcessRecord() _percent = CalculateProgressPercentage(StageVerification); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } + List nextTestList = (isForWmi || isForPowershell) ? wmiTestList : winrmTestList; restartStageTestList = TestRestartStageUsingWsman(restartStageTestList, nextTestList, _cancel.Token); } // Test WMI service if (_exit) { break; } + if (wmiTestList.Count > 0) { // This statement block executes for both CLRs. @@ -949,13 +964,16 @@ protected override void ProcessRecord() _percent = CalculateProgressPercentage(WmiConnectionTest); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } + wmiTestList = TestWmiConnectionUsingWsman(wmiTestList, winrmTestList, _cancel.Token, Credential, WsmanAuthentication, this); } } + if (isForWmi) { break; } // Test WinRM service if (_exit) { break; } + if (winrmTestList.Count > 0) { // This statement block executes for both CLRs. @@ -984,10 +1002,12 @@ protected override void ProcessRecord() } } } + if (isForWinRm) { break; } // Test PowerShell if (_exit) { break; } + if (psTestList.Count > 0) { if (_waitOnComputers.Count == 1) @@ -996,6 +1016,7 @@ protected override void ProcessRecord() _percent = CalculateProgressPercentage(PowerShellConnectionTest); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } + psTestList = TestPowerShell(psTestList, allDoneList, _powershell, this.Credential); } } while (false); @@ -1029,6 +1050,7 @@ protected override void ProcessRecord() WriteProgress(_indicator[indicatorIndex % 4] + _activity, _status, 100, ProgressRecordType.Completed); _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); } + break; } @@ -1045,12 +1067,14 @@ protected override void ProcessRecord() do { if (restartStageTestList.Count > 0) { WriteOutTimeoutError(restartStageTestList); } + if (wmiTestList.Count > 0) { WriteOutTimeoutError(wmiTestList); } // Wait for WMI. All computers that finished restarting are put in "winrmTestList" if (isForWmi) { break; } // Wait for WinRM. All computers that finished restarting are put in "psTestList" if (winrmTestList.Count > 0) { WriteOutTimeoutError(winrmTestList); } + if (isForWinRm) { break; } if (psTestList.Count > 0) { WriteOutTimeoutError(psTestList); } @@ -1312,8 +1336,10 @@ public class RenameComputerCommand : PSCmdlet public SwitchParameter Force { get { return _force; } + set { _force = value; } } + private bool _force; /// @@ -1323,8 +1349,10 @@ public SwitchParameter Force public SwitchParameter Restart { get { return _restart; } + set { _restart = value; } } + private bool _restart; /// @@ -1359,6 +1387,7 @@ private string ValidateComputerName() { WriteError(targetError); } + return null; } @@ -1833,6 +1862,7 @@ internal static string GetScopeString(string computer, string namespaceParameter { returnValue.Append(computer); } + returnValue.Append(namespaceParameter); return returnValue.ToString(); } @@ -1853,6 +1883,7 @@ internal static bool IsValidDrive(string drive) return true; } } + return false; } @@ -1876,6 +1907,7 @@ internal static bool ContainsSystemDrive(string[] drives, string sysdrive) if (driveApp.Equals(sysdrive, StringComparison.OrdinalIgnoreCase)) return true; } + return false; } @@ -1937,6 +1969,7 @@ internal static ComputerChangeInfo GetComputerStatusObject(int errorcode, string { computerchangeinfo.HasSucceeded = true; } + return computerchangeinfo; } @@ -1953,6 +1986,7 @@ internal static RenameComputerChangeInfo GetRenameComputerStatusObject(int error { renamecomputerchangeinfo.HasSucceeded = true; } + return renamecomputerchangeinfo; } @@ -1964,6 +1998,7 @@ internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, st { additionalmessage = StringUtil.Format(ComputerResources.NetworkPathNotFound, computername); } + string message = StringUtil.Format(ComputerResources.OperationFailed, ex.Message, computername, additionalmessage); ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername); cmdlet.WriteError(er); @@ -2022,6 +2057,7 @@ internal static bool SkipSystemRestoreOperationForARMPlatform(PSCmdlet cmdlet) cmdlet.WriteError(er); retValue = true; } + return retValue; } @@ -2211,6 +2247,7 @@ internal static string ValidateComputerName( return null; } + validatedComputerName = nameToCheck; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index e97babef287..a2c3c3bf2cc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -34,6 +34,7 @@ public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable public string[] LiteralPath { get { return Path; } + set { base.SuppressWildcardExpansion = true; @@ -48,6 +49,7 @@ public string[] LiteralPath public override string Filter { get { return base.Filter; } + set { base.Filter = value; } } @@ -58,6 +60,7 @@ public override string Filter public override string[] Include { get { return base.Include; } + set { base.Include = value; } } @@ -68,6 +71,7 @@ public override string[] Include public override string[] Exclude { get { return base.Exclude; } + set { base.Exclude = value; } } @@ -87,6 +91,7 @@ public override string[] Exclude public override SwitchParameter Force { get { return base.Force; } + set { base.Force = value; } } @@ -181,6 +186,7 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn { parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context); } + note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs index f345fa72882..c3e3f87a614 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -140,6 +140,7 @@ internal List AllControlPanelItems break; } } + if (match) continue; } @@ -148,9 +149,11 @@ internal List AllControlPanelItems _allControlPanelItems.Add(item); } } + return _allControlPanelItems; } } + private List _allControlPanelItems; #region Cmdlet Overrides @@ -199,6 +202,7 @@ private bool ContainVerbOpen(ShellFolderItem item) break; } } + return result; } @@ -433,6 +437,7 @@ internal List GetControlPanelItemByCanonicalName(List @@ -576,12 +583,14 @@ public string[] Name public string[] CanonicalName { get { return CanonicalNames; } + set { CanonicalNames = value; _canonicalNameSpecified = true; } } + private bool _canonicalNameSpecified = false; /// @@ -593,12 +602,14 @@ public string[] CanonicalName public string[] Category { get { return CategoryNames; } + set { CategoryNames = value; _categorySpecified = true; } } + private bool _categorySpecified = false; #endregion "Parameters" @@ -690,6 +701,7 @@ public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand public string[] Name { get { return RegularNames; } + set { RegularNames = value; } } @@ -702,6 +714,7 @@ public string[] Name public string[] CanonicalName { get { return CanonicalNames; } + set { CanonicalNames = value; } } @@ -714,6 +727,7 @@ public string[] CanonicalName public ControlPanelItem[] InputObject { get { return ControlPanelItems; } + set { ControlPanelItems = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs index 43c3a3d5e44..2b7438d302f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs @@ -23,6 +23,7 @@ public class CopyItemPropertyCommand : PassThroughItemPropertyCommandBase public string[] Path { get { return paths; } + set { paths = value; } } @@ -35,6 +36,7 @@ public string[] Path public string[] LiteralPath { get { return paths; } + set { base.SuppressWildcardExpansion = true; @@ -78,6 +80,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) Name, context); } + return InvokeProvider.Property.CopyPropertyDynamicParameters( ".", Name, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index c760e02754b..693645072b5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -69,6 +69,7 @@ public sealed class GetEventLogCommand : PSCmdlet public DateTime After { get { return _after; } + set { _after = value; @@ -76,6 +77,7 @@ public DateTime After _isFilterSpecified = true; } } + private DateTime _after; /// @@ -86,6 +88,7 @@ public DateTime After public DateTime Before { get { return _before; } + set { _before = value; @@ -93,6 +96,7 @@ public DateTime Before _isFilterSpecified = true; } } + private DateTime _before; /// @@ -104,12 +108,14 @@ public DateTime Before public String[] UserName { get { return _username; } + set { _username = value; _isFilterSpecified = true; } } + private String[] _username; /// @@ -123,12 +129,14 @@ public String[] UserName public long[] InstanceId { get { return _instanceIds; } + set { _instanceIds = value; _isFilterSpecified = true; } } + private long[] _instanceIds = null; /// @@ -142,12 +150,14 @@ public long[] InstanceId public int[] Index { get { return _indexes; } + set { _indexes = value; _isFilterSpecified = true; } } + private int[] _indexes = null; /// @@ -162,12 +172,14 @@ public int[] Index public string[] EntryType { get { return _entryTypes; } + set { _entryTypes = value; _isFilterSpecified = true; } } + private string[] _entryTypes = null; /// @@ -181,12 +193,14 @@ public string[] Source { get { return _sources; } + set { _sources = value; _isFilterSpecified = true; } } + private string[] _sources; /// @@ -201,12 +215,14 @@ public string Message { return _message; } + set { _message = value; _isFilterSpecified = true; } } + private string _message; /// @@ -231,11 +247,13 @@ public SwitchParameter AsString { return _asString; } + set { _asString = value; } } + private bool _asString /* = false */; #endregion Parameters @@ -403,6 +421,7 @@ private void Process(EventLog log) + ": " + e.Message); throw; } + if ((entry != null) && ((lastindex == Int32.MinValue || lastindex - entry.Index == 1))) @@ -413,6 +432,7 @@ private void Process(EventLog log) if (!FiltersMatch(entry)) continue; } + if (!AsBaseObject) { //wrapping in PSobject to insert into PStypesnames @@ -428,9 +448,11 @@ private void Process(EventLog log) WriteObject(entry); matchesfound = true; } + processed++; } } + if (!matchesfound && _isThrowError) { Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, string.Empty)); @@ -447,6 +469,7 @@ private bool FiltersMatch(EventLogEntry entry) return false; } } + if (_instanceIds != null) { if (!((IList)_instanceIds).Contains(entry.InstanceId)) @@ -454,6 +477,7 @@ private bool FiltersMatch(EventLogEntry entry) return false; } } + if (_entryTypes != null) { bool entrymatch = false; @@ -465,8 +489,10 @@ private bool FiltersMatch(EventLogEntry entry) break; } } + if (!entrymatch) return entrymatch; } + if (_sources != null) { bool sourcematch = false; @@ -476,6 +502,7 @@ private bool FiltersMatch(EventLogEntry entry) { _isThrowError = false; } + WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase); if (wildcardpattern.IsMatch(entry.Source)) { @@ -483,20 +510,24 @@ private bool FiltersMatch(EventLogEntry entry) break; } } + if (!sourcematch) return sourcematch; } + if (_message != null) { if (WildcardPattern.ContainsWildcardCharacters(_message)) { _isThrowError = false; } + WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase); if (!wildcardpattern.IsMatch(entry.Message)) { return false; } } + if (_username != null) { bool usernamematch = false; @@ -513,8 +544,10 @@ private bool FiltersMatch(EventLogEntry entry) } } } + if (!usernamematch) return usernamematch; } + if (_isDateSpecified) { _isThrowError = false; @@ -548,10 +581,13 @@ private bool FiltersMatch(EventLogEntry entry) } } } + if (!datematch) return datematch; } + return true; } + private List GetMatchingLogs(string pattern) { WildcardPattern wildcardPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); @@ -637,6 +673,7 @@ protected override void BeginProcessing() { computer = compName; } + foreach (string eventString in LogName) { try @@ -647,10 +684,12 @@ protected override void BeginProcessing() WriteError(er); continue; } + if (!ShouldProcess(StringUtil.Format(EventlogResources.ClearEventLogWarning, eventString, computer))) { continue; } + EventLog Log = new EventLog(eventString, compName); Log.Clear(); } @@ -785,6 +824,7 @@ protected override void BeginProcessing() { _computerName = ComputerName; } + try { if (!(EventLog.SourceExists(Source, ComputerName))) @@ -866,12 +906,14 @@ public sealed class LimitEventLogCommand : PSCmdlet public Int32 RetentionDays { get { return _retention; } + set { _retention = value; _retentionSpecified = true; } } + private Int32 _retention; private bool _retentionSpecified = false; /// @@ -885,12 +927,14 @@ public Int32 RetentionDays public System.Diagnostics.OverflowAction OverflowAction { get { return _overflowaction; } + set { _overflowaction = value; _overflowSpecified = true; } } + private System.Diagnostics.OverflowAction _overflowaction; private bool _overflowSpecified = false; /// @@ -901,12 +945,14 @@ public System.Diagnostics.OverflowAction OverflowAction public Int64 MaximumSize { get { return _maximumKilobytes; } + set { _maximumKilobytes = value; _maxkbSpecified = true; } } + private Int64 _maximumKilobytes; private bool _maxkbSpecified = false; #endregion Parameters @@ -941,6 +987,7 @@ protected override { computer = compname; } + foreach (string logname in LogName) { try @@ -992,6 +1039,7 @@ protected override { newLog.ModifyOverflowPolicy(_overflowaction, _minRetention); } + if (_maxkbSpecified) { int kiloByte = 1024; @@ -1021,6 +1069,7 @@ protected override { WriteNonTerminatingError(ex, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null); } + continue; } } @@ -1210,6 +1259,7 @@ protected override void BeginProcessing() { computer = compname; } + try { foreach (string _sourceName in Source) @@ -1326,6 +1376,7 @@ protected override void BeginProcessing() { computer = compName; } + if (ParameterSetName.Equals("Default")) { foreach (string log in LogName) @@ -1338,6 +1389,7 @@ protected override void BeginProcessing() { continue; } + EventLog.Delete(log, compName); } else @@ -1367,6 +1419,7 @@ protected override void BeginProcessing() { continue; } + EventLog.DeleteEventSource(src, compName); } else diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index cd2dfaf6ff1..fdffe822708 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -40,6 +40,7 @@ public string[] Path { return _paths; } + set { _paths = value; @@ -76,6 +77,7 @@ public override string Filter { return base.Filter; } + set { base.Filter = value; @@ -127,6 +129,7 @@ public SwitchParameter Recurse { return _recurse; } + set { _recurse = value; @@ -146,6 +149,7 @@ public uint Depth { return _depth; } + set { _depth = value; @@ -172,6 +176,7 @@ public override SwitchParameter Force { return base.Force; } + set { base.Force = value; @@ -188,6 +193,7 @@ public SwitchParameter Name { return _childNames; } + set { _childNames = value; @@ -232,12 +238,14 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { result = InvokeProvider.ChildItem.GetChildItemsDynamicParameters(path, Recurse, context); } + break; default: result = InvokeProvider.ChildItem.GetChildItemsDynamicParameters(path, Recurse, context); break; } + return result; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs index f88f79aefb5..c6375a8de75 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -58,12 +58,14 @@ public class GetClipboardCommand : PSCmdlet public TextDataFormat TextFormatType { get { return _textFormat; } + set { _isTextFormatTypeSet = true; _textFormat = value; } } + private TextDataFormat _textFormat = TextDataFormat.UnicodeText; private bool _isTextFormatTypeSet = false; @@ -74,12 +76,14 @@ public TextDataFormat TextFormatType public SwitchParameter Raw { get { return _raw; } + set { _isRawSet = true; _raw = value; } } + private bool _raw; private bool _isRawSet = false; @@ -140,6 +144,7 @@ private List GetClipboardContentAsText(TextDataFormat textFormat) { return null; } + List result = new List(); // TextFormat default value is Text, by default it is same as Clipboard.GetText() @@ -153,6 +158,7 @@ private List GetClipboardContentAsText(TextDataFormat textFormat) string[] splitSymbol = { Environment.NewLine }; result.AddRange(textContent.Split(splitSymbol, StringSplitOptions.None)); } + return result; } @@ -166,12 +172,14 @@ private List GetClipboardContentAsFileList() { return null; } + List result = new List(); foreach (string filePath in Clipboard.GetFileDropList()) { FileInfo file = new FileInfo(filePath); result.Add(WrapOutputInPSObject(file, filePath)); } + return result; } @@ -199,6 +207,7 @@ private PSObject WrapOutputInPSObject( string childName = item.Name; result.AddOrSetProperty("PSChildName", childName); } + return result; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 642e45c5908..a611f53fa90 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -411,6 +411,7 @@ private static bool CheckDeviceGuardLicense() // consider there to be no license. } } + return false; } @@ -442,6 +443,7 @@ private static DeviceGuardInfo GetDeviceGuard(CimSession session) { status = (DeviceGuardSmartStatus)smartStatus; } + guard = wmiGuard.AsOutputType; } } @@ -1538,6 +1540,7 @@ public DeviceGuard AsOutputType if (temp != null) listHardware.Add(temp.Value); } + guard.RequiredSecurityProperties = listHardware.ToArray(); listHardware.Clear(); @@ -1548,6 +1551,7 @@ public DeviceGuard AsOutputType if (temp != null) listHardware.Add(temp.Value); } + guard.AvailableSecurityProperties = listHardware.ToArray(); var listSoftware = new List(); @@ -1558,6 +1562,7 @@ public DeviceGuard AsOutputType if (temp != null) listSoftware.Add(temp.Value); } + guard.SecurityServicesConfigured = listSoftware.ToArray(); listSoftware.Clear(); @@ -1568,6 +1573,7 @@ public DeviceGuard AsOutputType if (temp != null) listSoftware.Add(temp.Value); } + guard.SecurityServicesRunning = listSoftware.ToArray(); } @@ -2481,6 +2487,7 @@ public class ComputerInfo /// System hardware security settings for administrator password status /// //public AdminPasswordStatus? CsAdminPasswordStatus { get; internal set; } + public HardwareSecurity? CsAdminPasswordStatus { get; internal set; } /// @@ -2534,6 +2541,7 @@ public class ComputerInfo /// Boot up state of the chassis /// //public ChassisBootupState? CsChassisBootupState { get; internal set; } + public SystemElementState? CsChassisBootupState { get; internal set; } /// @@ -2590,6 +2598,7 @@ public class ComputerInfo /// Hardware security setting for the reset button on a computer /// //public FrontPanelResetStatus? CsFrontPanelResetStatus { get; internal set; } + public HardwareSecurity? CsFrontPanelResetStatus { get; internal set; } /// @@ -2616,6 +2625,7 @@ public class ComputerInfo /// System hardware security setting for Keyboard Password Status /// //public KeyboardPasswordStatus? CsKeyboardPasswordStatus { get; internal set; } + public HardwareSecurity? CsKeyboardPasswordStatus { get; internal set; } /// @@ -2727,6 +2737,7 @@ public class ComputerInfo /// System hardware security setting for Power-On Password Status /// //public PowerOnPasswordStatus? CsPowerOnPasswordStatus { get; internal set; } + public HardwareSecurity? CsPowerOnPasswordStatus { get; internal set; } /// @@ -2738,6 +2749,7 @@ public class ComputerInfo /// State of the power supply or supplies when last booted /// //public PowerSupplyState? CsPowerSupplyState { get; internal set; } + public SystemElementState? CsPowerSupplyState { get; internal set; } /// @@ -2808,6 +2820,7 @@ public class ComputerInfo /// Thermal state of the system when last booted /// //public ThermalState? CsThermalState { get; internal set; } + public SystemElementState? CsThermalState { get; internal set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index 42f630a509c..e5854f4bfce 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -48,6 +48,7 @@ public long TotalCount _totalCountSpecified = true; } } + private bool _totalCountSpecified = false; /// @@ -62,8 +63,10 @@ public int Tail _backCount = value; _tailSpecified = true; } + get { return _backCount; } } + private int _backCount = -1; private bool _tailSpecified = false; @@ -85,6 +88,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Content.GetContentReaderDynamicParameters(Path[0], context); } + return InvokeProvider.Content.GetContentReaderDynamicParameters(".", context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs index 342af4d8151..67b394375da 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -92,6 +92,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) Path[0], SessionStateUtilities.ConvertArrayToCollection(_property), context); } + return InvokeProvider.Property.GetPropertyDynamicParameters( ".", SessionStateUtilities.ConvertArrayToCollection(_property), context); @@ -248,6 +249,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) Path[0], SessionStateUtilities.ConvertArrayToCollection(_property), context); } + return InvokeProvider.Property.GetPropertyDynamicParameters( ".", SessionStateUtilities.ConvertArrayToCollection(_property), context); @@ -275,6 +277,7 @@ protected override void ProcessRecord() { paths = new string[] { "." }; } + foreach (string path in Path) { try diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs index 58eabbb3de2..a3eb7f09da1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -43,6 +43,7 @@ public class GetWmiObjectCommand : WmiBaseCmdlet public string[] Property { get { return (string[])_property.Clone(); } + set { _property = value; } } @@ -101,6 +102,7 @@ internal string GetQueryString() returnValue.Append(" where "); returnValue.Append(Filter); } + return returnValue.ToString(); } /// @@ -124,6 +126,7 @@ internal string GetFilterClassName() filterClass = filterClass.Replace('?', '_'); return filterClass; } + internal bool IsLocalizedNamespace(string sNamespace) { bool toReturn = false; @@ -131,8 +134,10 @@ internal bool IsLocalizedNamespace(string sNamespace) { toReturn = true; } + return toReturn; } + internal bool ValidateClassFormat() { string filterClass = this.Class; @@ -156,8 +161,10 @@ internal bool ValidateClassFormat() newClassName.Append(']'); continue; } + return false; } + this.Class = newClassName.ToString(); return true; } @@ -181,6 +188,7 @@ internal ManagementObjectSearcher GetObjectList(ManagementScope scope) queryStringBuilder.Append(filterClass); queryStringBuilder.Append("'"); } + ObjectQuery classQuery = new ObjectQuery(queryStringBuilder.ToString()); EnumerationOptions enumOptions = new EnumerationOptions(); @@ -219,6 +227,7 @@ protected override void BeginProcessing() WriteError(errorRecord); return; } + foreach (string name in ComputerName) { if (this.Recurse.IsPresent) @@ -325,6 +334,7 @@ protected override void BeginProcessing() WriteError(errorRecord); continue; } + ManagementObjectSearcher searcher = this.GetObjectList(scope); if (searcher == null) continue; @@ -334,6 +344,7 @@ protected override void BeginProcessing() } } } + return; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index e96fa603d01..633d4926b44 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -103,6 +103,7 @@ protected override void BeginProcessing() if (i < Id.Length - 1) QueryString.Append(" Or "); } + QueryString.Append(")"); } else @@ -110,6 +111,7 @@ protected override void BeginProcessing() QueryString.Append("Select * from Win32_QuickFixEngineering"); foundRecord = true; } + _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString())); foreach (ManagementObject obj in _searchProcess.Get()) { @@ -153,11 +155,13 @@ protected override void BeginProcessing() WriteObject(obj); foundRecord = true; } + if (!foundRecord && !_inputContainsWildcard) { Exception Ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer)); WriteError(new ErrorRecord(Ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); } + if (_searchProcess != null) { this.Dispose(); @@ -190,6 +194,7 @@ private bool FilterMatch(ManagementObject obj) { return true; } + if (WildcardPattern.ContainsWildcardCharacters(desc)) { _inputContainsWildcard = true; @@ -200,6 +205,7 @@ private bool FilterMatch(ManagementObject obj) { return false; } + return false; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs index 71bd7b86098..fe0c21a714a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -30,6 +30,7 @@ public sealed class InvokeWmiMethod : WmiBaseCmdlet public ManagementObject InputObject { get { return _inputObject; } + set { _inputObject = value; } } /// @@ -39,6 +40,7 @@ public ManagementObject InputObject public string Path { get { return _path; } + set { _path = value; } } /// @@ -48,6 +50,7 @@ public string Path public string Class { get { return _className; } + set { _className = value; } } /// @@ -57,6 +60,7 @@ public string Class public string Name { get { return _methodName; } + set { _methodName = value; } } @@ -70,6 +74,7 @@ public string Name public object[] ArgumentList { get { return _argumentList; } + set { _argumentList = value; } } @@ -94,6 +99,7 @@ protected override void ProcessRecord() RunAsJob("Invoke-WMIMethod"); return; } + if (_inputObject != null) { object result = null; @@ -112,6 +118,7 @@ protected override void ProcessRecord() inParamCount--; } } + if (!ShouldProcess( StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, _inputObject["__CLASS"].ToString(), @@ -120,6 +127,7 @@ protected override void ProcessRecord() { return; } + result = _inputObject.InvokeMethod(_methodName, inputParameters, null); } catch (ManagementException e) @@ -132,10 +140,12 @@ protected override void ProcessRecord() ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } + if (result != null) { WriteObject(result); } + return; } else @@ -177,6 +187,7 @@ protected override void ProcessRecord() ComputerName = serverName; } } + foreach (string name in ComputerName) { result = null; @@ -195,6 +206,7 @@ protected override void ProcessRecord() ManagementObject mInstance = new ManagementObject(mPath); mObject = mInstance; } + ManagementScope mScope = new ManagementScope(mPath, options); mObject.Scope = mScope; } @@ -205,6 +217,7 @@ protected override void ProcessRecord() mObject = mClass; mObject.Scope = scope; } + ManagementBaseObject inputParameters = mObject.GetMethodParameters(_methodName); if (_argumentList != null) { @@ -222,9 +235,11 @@ protected override void ProcessRecord() { property.Value = argument; } + inParamCount--; } } + if (!ShouldProcess( StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, mObject["__CLASS"].ToString(), @@ -233,6 +248,7 @@ protected override void ProcessRecord() { return; } + result = mObject.InvokeMethod(_methodName, inputParameters, null); } catch (ManagementException e) @@ -245,6 +261,7 @@ protected override void ProcessRecord() ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } + if (result != null) { WriteObject(result); @@ -278,6 +295,7 @@ private static object MakeBaseObjectArray(object argument) break; } } + if (needCopy) { var copiedArgument = new object[listArgument.Count]; @@ -286,6 +304,7 @@ private static object MakeBaseObjectArray(object argument) { copiedArgument[index++] = argElement != null ? PSObject.Base(argElement) : null; } + return copiedArgument; } else diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index d753f331811..3fcd3e57c53 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -24,6 +24,7 @@ public class MoveItemPropertyCommand : PassThroughItemPropertyCommandBase public string[] Path { get { return paths; } + set { paths = value; } } @@ -36,6 +37,7 @@ public string[] Path public string[] LiteralPath { get { return paths; } + set { base.SuppressWildcardExpansion = true; @@ -51,12 +53,14 @@ public string[] LiteralPath public string[] Name { get { return _property; } + set { if (value == null) { value = Utils.EmptyArray(); } + _property = value; } } @@ -91,6 +95,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Property.MovePropertyDynamicParameters(Path[0], propertyName, Destination, propertyName, context); } + return InvokeProvider.Property.MovePropertyDynamicParameters( ".", propertyName, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 33c774f48c1..7b17c88dc6c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -62,6 +62,7 @@ internal virtual SwitchParameter SuppressWildcardExpansion get => _suppressWildcardExpansion; set => _suppressWildcardExpansion = value; } + private bool _suppressWildcardExpansion; /// @@ -130,6 +131,7 @@ protected bool DoesProviderSupportShouldProcess(string[] paths) } } } + return result; } @@ -373,6 +375,7 @@ public SwitchParameter Stack get => _stackSwitch; set => _stackSwitch = value; } + private bool _stackSwitch; /// @@ -573,6 +576,7 @@ protected override void ProcessRecord() // Get the current working directory using the core command API. WriteObject(SessionState.Path.CurrentLocation); } + break; case StackParameterSet: @@ -609,6 +613,7 @@ protected override void ProcessRecord() argException)); } } + break; default: @@ -759,6 +764,7 @@ protected override void ProcessRecord() argException.ErrorRecord, argException)); } + break; case StackParameterSet: @@ -1135,6 +1141,7 @@ public SwitchParameter Persist get => _persist; set => _persist = value; } + private bool _persist = false; #endif /// @@ -1457,6 +1464,7 @@ internal List GetMatchingDrives( } } } + results.Sort(); return results; } @@ -1610,6 +1618,7 @@ protected override void ProcessRecord() invalidOperation)); continue; } + SessionState.Drive.Remove(drive.Name, Force, Scope, CmdletProviderContext); } } @@ -1930,6 +1939,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.GetItemDynamicParameters(Path[0], context); } + return InvokeProvider.Item.GetItemDynamicParameters(".", context); } @@ -2074,6 +2084,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) else return InvokeProvider.Item.NewItemDynamicParameters(Path[0], ItemType, Value, context); } + return InvokeProvider.Item.NewItemDynamicParameters(".", ItemType, Value, context); } @@ -2266,6 +2277,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.SetItemDynamicParameters(Path[0], Value, context); } + return InvokeProvider.Item.SetItemDynamicParameters(".", Value, context); } @@ -2460,6 +2472,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.RemoveItemDynamicParameters(Path[0], Recurse, context); } + return InvokeProvider.Item.RemoveItemDynamicParameters(".", Recurse, context); } @@ -2517,6 +2530,7 @@ protected override void ProcessRecord() new Collection(), null); } + try { resolvedPSPaths = SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext); @@ -2710,6 +2724,7 @@ protected override void ProcessRecord() { continue; } + shouldRecurse = true; } @@ -2893,6 +2908,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.MoveItemDynamicParameters(Path[0], Destination, context); } + return InvokeProvider.Item.MoveItemDynamicParameters(".", Destination, context); } @@ -3295,6 +3311,7 @@ private Collection GetResolvedPaths(string path) pathNotFound.ErrorRecord, pathNotFound)); } + return results; } @@ -3308,11 +3325,13 @@ protected override void ProcessRecord() RenameItem(Path, literalPath: true); return; } + Collection resolvedPaths = GetResolvedPaths(Path); if (resolvedPaths == null) { return; } + if (resolvedPaths.Count == 1) { RenameItem(resolvedPaths[0].Path, literalPath: true); @@ -3641,6 +3660,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.CopyItemDynamicParameters(Path[0], Destination, Recurse, context); } + return InvokeProvider.Item.CopyItemDynamicParameters(".", Destination, Recurse, context); } @@ -3846,6 +3866,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.ClearItemDynamicParameters(Path[0], context); } + return InvokeProvider.Item.ClearItemDynamicParameters(".", context); } @@ -4015,6 +4036,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Item.InvokeItemDynamicParameters(Path[0], context); } + return InvokeProvider.Item.InvokeItemDynamicParameters(".", context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs index 0d4ce0db09a..d5a4479e99b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -91,6 +91,7 @@ public override SwitchParameter Force { return base.Force; } + set { base.Force = value; @@ -115,6 +116,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Property.NewPropertyDynamicParameters(Path[0], Name, PropertyType, Value, context); } + return InvokeProvider.Property.NewPropertyDynamicParameters(".", Name, PropertyType, Value, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index b04d41aed5f..c55144602a9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -336,6 +336,7 @@ protected override void ProcessRecord() separatorIndex + 1); } } + break; case parentSet: diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs index fa7a8d7d2e0..d486f1bfc54 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs @@ -50,6 +50,7 @@ public override SwitchParameter Force { return base.Force; } + set { base.Force = value; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index 21d8ab146b9..50e5ba7c1cb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -48,6 +48,7 @@ public class TestPathCommand : CoreCommandWithCredentialsBase public string[] Path { get { return _paths; } + set { _paths = value; } } @@ -63,6 +64,7 @@ public string[] Path public string[] LiteralPath { get { return _paths; } + set { base.SuppressWildcardExpansion = true; @@ -77,6 +79,7 @@ public string[] LiteralPath public override string Filter { get { return base.Filter; } + set { base.Filter = value; } } @@ -87,6 +90,7 @@ public override string Filter public override string[] Include { get { return base.Include; } + set { base.Include = value; } } @@ -97,6 +101,7 @@ public override string[] Include public override string[] Exclude { get { return base.Exclude; } + set { base.Exclude = value; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 32947c9318d..8fdd8146afe 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -91,12 +91,14 @@ public virtual Process[] InputObject { return _input; } + set { myMode = MatchMode.ByInput; _input = value; } } + private Process[] _input = null; #endregion Parameters @@ -170,6 +172,7 @@ private void RetrieveMatchingProcessesByProcessName() _matchingProcesses = new List(AllProcesses); return; } + foreach (string pattern in processNames) { WildcardPattern wildcard = @@ -182,6 +185,7 @@ private void RetrieveMatchingProcessesByProcessName() found = true; AddIdempotent(process); } + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) { @@ -211,6 +215,7 @@ private void RetrieveMatchingProcessesById() Diagnostics.Assert(false, "null processIds"); throw PSTraceSource.NewInvalidOperationException(); } + foreach (int processId in processIds) { Process process; @@ -246,6 +251,7 @@ private void RetrieveProcessesByInput() Diagnostics.Assert(false, "null InputObject"); throw PSTraceSource.NewInvalidOperationException(); } + foreach (Process process in InputObject) { SafeRefresh(process); @@ -272,9 +278,11 @@ internal Process[] AllProcesses processes.AddRange(Process.GetProcesses()); _allProcesses = processes.ToArray(); } + return _allProcesses; } } + private Process[] _allProcesses = null; /// @@ -463,6 +471,7 @@ public sealed class GetProcessCommand : ProcessBaseCommand public string[] Name { get { return processNames; } + set { myMode = MatchMode.ByName; @@ -482,6 +491,7 @@ public int[] Id { return processIds; } + set { myMode = MatchMode.ById; @@ -500,6 +510,7 @@ public override Process[] InputObject { return base.InputObject; } + set { base.InputObject = value; @@ -515,8 +526,10 @@ public override Process[] InputObject public SwitchParameter IncludeUserName { get { return _includeUserName; } + set { _includeUserName = value; } } + private bool _includeUserName = false; /// @@ -845,6 +858,7 @@ public int[] Id { return processIds; } + set { myMode = MatchMode.ById; @@ -865,6 +879,7 @@ public int[] Id public string[] Name { get { return processNames; } + set { myMode = MatchMode.ByName; @@ -885,12 +900,14 @@ public int Timeout { return _timeout; } + set { _timeout = value; _timeOutSpecified = true; } } + private int _timeout = 0; private bool _timeOutSpecified; @@ -911,6 +928,7 @@ public void Dispose() _waitHandle.Dispose(); _waitHandle = null; } + _disposed = true; } } @@ -961,6 +979,7 @@ protected override void ProcessRecord() WriteNonTerminatingError(process, null, ProcessResources.WaitOnItself, "WaitOnItself", ErrorCategory.ObjectNotFound); continue; } + _processList.Add(process); } } @@ -1002,6 +1021,7 @@ protected override void EndProcessing() _waitHandle.WaitOne(); } } + foreach (Process process in _processList) { try @@ -1064,6 +1084,7 @@ public string[] Name { return processNames; } + set { processNames = value; @@ -1085,6 +1106,7 @@ public int[] Id { return processIds; } + set { myMode = MatchMode.ById; @@ -1107,6 +1129,7 @@ public int[] Id { return base.InputObject; } + set { base.InputObject = value; @@ -1121,6 +1144,7 @@ public int[] Id public SwitchParameter PassThru { get { return _passThru; } + set { _passThru = value; } } @@ -1428,6 +1452,7 @@ public int[] Id { return processIds; } + set { myMode = MatchMode.ById; @@ -1448,6 +1473,7 @@ public int[] Id public string[] Name { get { return processNames; } + set { myMode = MatchMode.ByName; @@ -1564,6 +1590,7 @@ private string MapReturnCodeToErrorMessage(int returnCode) case 21: errorMessage = ProcessResources.AttachDebuggerReturnCode21; break; default: Diagnostics.Assert(false, "Unreachable code."); break; } + return errorMessage; } } @@ -1609,12 +1636,14 @@ public sealed class StartProcessCommand : PSCmdlet, IDisposable public PSCredential Credential { get { return _credential; } + set { _credential = value; _isDefaultSetParameterSpecified = true; } } + private PSCredential _credential; /// @@ -1632,12 +1661,14 @@ public PSCredential Credential public SwitchParameter LoadUserProfile { get { return _loaduserprofile; } + set { _loaduserprofile = value; _isDefaultSetParameterSpecified = true; } } + private SwitchParameter _loaduserprofile = SwitchParameter.Present; /// @@ -1648,12 +1679,14 @@ public SwitchParameter LoadUserProfile public SwitchParameter NoNewWindow { get { return _nonewwindow; } + set { _nonewwindow = value; _isDefaultSetParameterSpecified = true; } } + private SwitchParameter _nonewwindow; /// @@ -1671,12 +1704,14 @@ public SwitchParameter NoNewWindow public string RedirectStandardError { get { return _redirectstandarderror; } + set { _redirectstandarderror = value; _isDefaultSetParameterSpecified = true; } } + private string _redirectstandarderror; /// @@ -1688,12 +1723,14 @@ public string RedirectStandardError public string RedirectStandardInput { get { return _redirectstandardinput; } + set { _redirectstandardinput = value; _isDefaultSetParameterSpecified = true; } } + private string _redirectstandardinput; /// @@ -1705,12 +1742,14 @@ public string RedirectStandardInput public string RedirectStandardOutput { get { return _redirectstandardoutput; } + set { _redirectstandardoutput = value; _isDefaultSetParameterSpecified = true; } } + private string _redirectstandardoutput; /// @@ -1731,12 +1770,14 @@ public string RedirectStandardOutput public ProcessWindowStyle WindowStyle { get { return _windowstyle; } + set { _windowstyle = value; _windowstyleSpecified = true; } } + private ProcessWindowStyle _windowstyle = ProcessWindowStyle.Normal; private bool _windowstyleSpecified = false; @@ -1753,12 +1794,14 @@ public ProcessWindowStyle WindowStyle public SwitchParameter UseNewEnvironment { get { return _UseNewEnvironment; } + set { _UseNewEnvironment = value; _isDefaultSetParameterSpecified = true; } } + private SwitchParameter _UseNewEnvironment; #endregion @@ -1827,6 +1870,7 @@ protected override void BeginProcessing() startInfo.UseShellExecute = (ArgumentList == null); #endif } + if (ArgumentList != null) { StringBuilder sb = new StringBuilder(); @@ -1835,6 +1879,7 @@ protected override void BeginProcessing() sb.Append(str); sb.Append(' '); } + startInfo.Arguments = sb.ToString(); ; } @@ -1849,6 +1894,7 @@ protected override void BeginProcessing() WriteError(er); return; } + startInfo.WorkingDirectory = WorkingDirectory; } else @@ -1892,6 +1938,7 @@ protected override void BeginProcessing() { startInfo.Domain = nwcredential.Domain; } + startInfo.Password = _credential.Password; } @@ -1953,6 +2000,7 @@ protected override void BeginProcessing() else if (ParameterSetName.Equals("UseShellExecute")) { if (Verb != null) { startInfo.Verb = Verb; } + startInfo.WindowStyle = _windowstyle; } @@ -2074,6 +2122,7 @@ private void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDictionary Env { processEnvironment.Remove(entry.Key.ToString()); } + if (entry.Key.ToString().Equals("PATH")) { processEnvironment.Add(entry.Key.ToString(), Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + ";" + Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); @@ -2102,10 +2151,12 @@ private Process Start(ProcessStartInfo startInfo) { process.BeginOutputReadLine(); } + if (process.StartInfo.RedirectStandardError) { process.BeginErrorReadLine(); } + if (process.StartInfo.RedirectStandardInput) { WriteToStandardInput(process); @@ -2114,6 +2165,7 @@ private Process Start(ProcessStartInfo startInfo) process = StartWithCreateProcess(startInfo); #endif } + return process; } @@ -2156,6 +2208,7 @@ private void StreamClosing() { _outputWriter.Dispose(); } + if (_errorWriter != null) { _errorWriter.Dispose(); @@ -2216,6 +2269,7 @@ private void WriteToStandardInput(Process p) string line = reader.ReadToEnd(); writer.WriteLine(line); } + writer.Dispose(); } #else @@ -2239,6 +2293,7 @@ private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, u ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } + SafeFileHandle sf = new SafeFileHandle(hFileHandle, true); return sf; } @@ -2252,16 +2307,19 @@ private static StringBuilder BuildCommandLine(string executableFileName, string { builder.Append("\""); } + builder.Append(str); if (!flag) { builder.Append("\""); } + if (!string.IsNullOrEmpty(arguments)) { builder.Append(" "); builder.Append(arguments); } + return builder; } @@ -2281,6 +2339,7 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) builder.Append(strArray2[i]); builder.Append('\0'); } + builder.Append('\0'); // Use Unicode encoding @@ -2289,6 +2348,7 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) { throw new InvalidOperationException("EnvironmentBlockTooLong"); } + return bytes; } @@ -2395,6 +2455,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) AddressOfEnvironmentBlock = pinnedEnvironmentBlock.AddrOfPinnedObject(); } } + bool flag; if (_credential != null) @@ -2435,6 +2496,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) er = er ?? new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } + goto Label_03AE; } finally @@ -2496,6 +2558,7 @@ private Process StartWithShellExecute(ProcessStartInfo startInfo) ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } + return result; } #endregion @@ -2687,12 +2750,14 @@ internal SafeLocalMemHandle() : base(true) { } + [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) { base.SetHandle(existingHandle); } + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(PinvokeDllNames.LocalFreeDllName)] private static extern IntPtr LocalFree(IntPtr hMem); protected override bool ReleaseHandle() @@ -2743,11 +2808,13 @@ public void Dispose(bool disposing) this.hStdInput.Dispose(); this.hStdInput = null; } + if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) { this.hStdOutput.Dispose(); this.hStdOutput = null; } + if ((this.hStdError != null) && !this.hStdError.IsInvalid) { this.hStdError.Dispose(); @@ -2911,8 +2978,10 @@ public override void GetObjectData( public string ProcessName { get { return _processName; } + set { _processName = value; } } + private string _processName = String.Empty; #endregion Properties } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index 0e288454b0d..2ac07ac5498 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -67,6 +67,7 @@ public Int64 Timeout { return _timeOut; } + set { _timeOut = value; @@ -85,6 +86,7 @@ private string BuildEventQuery(string objectName) returnValue.Append(objectName); return returnValue.ToString(); } + private string GetScopeString(string computer, string namespaceParameter) { StringBuilder returnValue = new StringBuilder("\\\\"); @@ -140,6 +142,7 @@ protected override Object GetSourceObject() { conOptions.Username = cred.Domain + "\\" + cred.UserName; } + conOptions.Password = cred.Password; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs index 6ee903f7aa0..f16d8c92ec3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs @@ -61,6 +61,7 @@ public string[] LiteralPath public string[] Name { get { return _property; } + set { _property = value ?? Utils.EmptyArray(); } } @@ -80,6 +81,7 @@ public string[] Name public override SwitchParameter Force { get { return base.Force; } + set { base.Force = value; } } @@ -107,6 +109,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Property.RemovePropertyDynamicParameters(Path[0], propertyName, context); } + return InvokeProvider.Property.RemovePropertyDynamicParameters(".", propertyName, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs index 6fae6f1d1de..4ac4fe56b11 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -22,6 +22,7 @@ public class RemoveWmiObject : WmiBaseCmdlet public ManagementObject InputObject { get { return _inputObject; } + set { _inputObject = value; } } /// @@ -31,6 +32,7 @@ public ManagementObject InputObject public string Path { get { return _path; } + set { _path = value; } } /// @@ -40,6 +42,7 @@ public string Path public string Class { get { return _className; } + set { _className = value; } } @@ -62,6 +65,7 @@ protected override void ProcessRecord() RunAsJob("Remove-WMIObject"); return; } + if (_inputObject != null) { try @@ -70,6 +74,7 @@ protected override void ProcessRecord() { return; } + _inputObject.Delete(); } catch (ManagementException e) @@ -82,6 +87,7 @@ protected override void ProcessRecord() ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } + return; } else @@ -115,12 +121,14 @@ protected override void ProcessRecord() ErrorCategory.InvalidOperation, this.ComputerName)); } + if (!(mPath.Server == "." && serverNameSpecified)) { string[] serverName = new string[] { mPath.Server }; ComputerName = serverName; } } + foreach (string name in ComputerName) { try @@ -138,6 +146,7 @@ protected override void ProcessRecord() ManagementObject mInstance = new ManagementObject(mPath); mObject = mInstance; } + ManagementScope mScope = new ManagementScope(mPath, options); mObject.Scope = mScope; } @@ -148,10 +157,12 @@ protected override void ProcessRecord() mObject = mClass; mObject.Scope = scope; } + if (!ShouldProcess(mObject["__PATH"].ToString())) { continue; } + mObject.Delete(); } catch (ManagementException e) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs index e483852b437..82de59ccd31 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs @@ -84,6 +84,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Property.RenamePropertyDynamicParameters(Path, Name, NewName, context); } + return InvokeProvider.Property.RenamePropertyDynamicParameters(".", Name, NewName, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index aa12f541f20..a52476e5d5c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -73,6 +73,7 @@ public SwitchParameter Relative _relative = value; } } + private SwitchParameter _relative; #endregion Parameters @@ -115,6 +116,7 @@ protected override void ProcessRecord() WriteObject(currentPath.Path, enumerateCollection: false); continue; } + string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, SessionState.Path.CurrentLocation.ProviderPath); // Do not insert './' if result path is not relative @@ -124,6 +126,7 @@ protected override void ProcessRecord() { adjustedPath = SessionState.Path.Combine(".", adjustedPath); } + WriteObject(adjustedPath, enumerateCollection: false); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 27bde24aa1a..871c9564fa3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -168,12 +168,14 @@ public string[] DisplayName { return displayNames; } + set { displayNames = value; selectionMode = SelectionMode.DisplayName; } } + internal string[] displayNames = null; /// @@ -190,11 +192,13 @@ public string[] Include { return include; } + set { include = value; } } + internal string[] include = null; /// @@ -211,11 +215,13 @@ public string[] Exclude { return exclude; } + set { exclude = value; } } + internal string[] exclude = null; // 1054295-2004/12/01-JonN This also works around 1054295. @@ -237,12 +243,14 @@ public ServiceController[] InputObject { return _inputObject; } + set { _inputObject = value; selectionMode = SelectionMode.InputObject; } } + private ServiceController[] _inputObject = null; #endregion Parameters @@ -265,9 +273,11 @@ internal ServiceController[] AllServices { _allServices = ServiceController.GetServices(); } + return _allServices; } } + private ServiceController[] _allServices = null; internal ServiceController GetOneService(string nameOfService) @@ -345,6 +355,7 @@ private List MatchingServicesByServiceName() { IncludeExcludeAdd(matchingServices, service, false); } + return matchingServices; } @@ -385,6 +396,7 @@ private List MatchingServicesByServiceName() ErrorCategory.ObjectNotFound); } } + return matchingServices; } @@ -404,6 +416,7 @@ private List MatchingServicesByDisplayName() Diagnostics.Assert(false, "null DisplayName"); throw PSTraceSource.NewInvalidOperationException(); } + foreach (string pattern in DisplayName) { WildcardPattern wildcard = @@ -416,6 +429,7 @@ private List MatchingServicesByDisplayName() found = true; IncludeExcludeAdd(matchingServices, service, true); } + if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) { WriteNonTerminatingError( @@ -428,6 +442,7 @@ private List MatchingServicesByDisplayName() ErrorCategory.ObjectNotFound); } } + return matchingServices; } @@ -444,11 +459,13 @@ private List MatchingServicesByInput() Diagnostics.Assert(false, "null InputObject"); throw PSTraceSource.NewInvalidOperationException(); } + foreach (ServiceController service in InputObject) { service.Refresh(); IncludeExcludeAdd(matchingServices, service, false); } + return matchingServices; } @@ -481,6 +498,7 @@ private void IncludeExcludeAdd( } } } + list.Add(service); } @@ -504,6 +522,7 @@ private bool Matches(ServiceController service, string[] matchList) if (wildcard.IsMatch(serviceID)) return true; } + return false; } #endregion Internal @@ -537,6 +556,7 @@ public string[] Name { return serviceNames; } + set { serviceNames = value; @@ -581,6 +601,7 @@ protected override void ProcessRecord() WriteObject(dependantserv); } } + if (RequiredServices.IsPresent) { foreach (ServiceController servicedependedon in service.ServicesDependedOn) @@ -623,6 +644,7 @@ private PSObject AddProperties(ServiceController service) ServiceResources.FailToOpenServiceControlManager, ErrorCategory.PermissionDenied); } + hService = NativeMethods.OpenServiceW( hScManager, service.ServiceName, @@ -700,6 +722,7 @@ private PSObject AddProperties(ServiceController service) } } } + return serviceAsPSObj; } } @@ -728,6 +751,7 @@ public string[] Name { return serviceNames; } + set { serviceNames = value; @@ -747,6 +771,7 @@ public string[] Name { return base.InputObject; } + set { base.InputObject = value; @@ -824,6 +849,7 @@ internal bool DoWaitForStatus( ErrorCategory.OpenError); return false; } + string message = StringUtil.Format(resourceIdPending, serviceController.ServiceName, serviceController.DisplayName @@ -860,6 +886,7 @@ internal bool DoStartService(ServiceController serviceController) exception = e; } } + if (exception != null) { // This service refused to accept the start command, @@ -884,6 +911,7 @@ internal bool DoStartService(ServiceController serviceController) { return false; } + return true; } @@ -976,6 +1004,7 @@ internal List DoStopService(ServiceController serviceControll exception = e; } } + if (exception != null) { // This service refused to accept the stop command, @@ -1032,6 +1061,7 @@ private bool HaveAllDependentServicesStopped(ICollection depe return false; } } + return true; } @@ -1070,6 +1100,7 @@ internal bool DoPauseService(ServiceController serviceController) { serviceNotRunning = true; } + exception = e; } catch (InvalidOperationException e) @@ -1080,8 +1111,10 @@ internal bool DoPauseService(ServiceController serviceController) { serviceNotRunning = true; } + exception = e; } + if (exception != null) { // This service refused to accept the pause command, @@ -1148,6 +1181,7 @@ internal bool DoResumeService(ServiceController serviceController) { serviceNotRunning = true; } + exception = e; } catch (InvalidOperationException e) @@ -1158,8 +1192,10 @@ internal bool DoResumeService(ServiceController serviceController) { serviceNotRunning = true; } + exception = e; } + if (exception != null) { // This service refused to accept the continue command, @@ -1353,6 +1389,7 @@ protected override void ProcessRecord() { continue; } + if (DoResumeService(serviceController)) { if (PassThru) @@ -1438,11 +1475,13 @@ public class SetServiceCommand : ServiceOperationBaseCommand public new String Name { get { return serviceName; } + set { serviceName = value; } } + internal String serviceName = null; /// @@ -1464,11 +1503,13 @@ public class SetServiceCommand : ServiceOperationBaseCommand public new string DisplayName { get { return displayName; } + set { displayName = value; } } + internal string displayName = null; /// @@ -1491,11 +1532,13 @@ public class SetServiceCommand : ServiceOperationBaseCommand public string Description { get { return description; } + set { description = value; } } + internal string description = null; /// @@ -1511,6 +1554,7 @@ public string Description public ServiceStartupType StartupType { get { return startupType; } + set { startupType = value; @@ -1533,11 +1577,13 @@ public ServiceStartupType StartupType public string Status { get { return serviceStatus; } + set { serviceStatus = value; } } + internal string serviceStatus = null; /// @@ -1560,11 +1606,13 @@ public string Status { return include; } + set { include = null; } } + internal new string[] include = null; /// @@ -1578,11 +1626,13 @@ public string Status { return exclude; } + set { exclude = null; } } + internal new string[] exclude = null; #endregion Parameters @@ -1609,6 +1659,7 @@ protected override void ProcessRecord() service = new ServiceController(serviceName); objServiceShouldBeDisposed = true; } + Diagnostics.Assert(!String.IsNullOrEmpty(Name), "null ServiceName"); // "new ServiceController" will succeed even if @@ -1663,6 +1714,7 @@ protected override void ProcessRecord() ErrorCategory.PermissionDenied); return; } + hService = NativeMethods.OpenServiceW( hScManager, Name, @@ -1700,6 +1752,7 @@ protected override void ProcessRecord() username = Credential.UserName; password = Marshal.SecureStringToCoTaskMemUnicode(Credential.Password); } + bool succeeded = NativeMethods.ChangeServiceConfigW( hService, NativeMethods.SERVICE_NO_CHANGE, @@ -1816,6 +1869,7 @@ protected override void ProcessRecord() } } } + if (PassThru.IsPresent) { // To display the service, refreshing the service would not show the display name after updating @@ -1829,6 +1883,7 @@ protected override void ProcessRecord() { Marshal.FreeCoTaskMem(delayedAutoStartInfoBuffer); } + if (IntPtr.Zero != hService) { bool succeeded = NativeMethods.CloseServiceHandle(hService); @@ -1868,6 +1923,7 @@ protected override void ProcessRecord() { Marshal.ZeroFreeCoTaskMemUnicode(password); } + if (objServiceShouldBeDisposed) { service.Dispose(); @@ -1897,8 +1953,10 @@ public class NewServiceCommand : ServiceBaseCommand public string Name { get { return serviceName; } + set { serviceName = value; } } + internal string serviceName = null; /// @@ -1910,8 +1968,10 @@ public string Name public string BinaryPathName { get { return binaryPathName; } + set { binaryPathName = value; } } + internal string binaryPathName = null; /// @@ -1923,8 +1983,10 @@ public string BinaryPathName public string DisplayName { get { return displayName; } + set { displayName = value; } } + internal string displayName = null; /// @@ -1936,8 +1998,10 @@ public string DisplayName public string Description { get { return description; } + set { description = value; } } + internal string description = null; /// @@ -1948,8 +2012,10 @@ public string Description public ServiceStartupType StartupType { get { return startupType; } + set { startupType = value; } } + internal ServiceStartupType startupType = ServiceStartupType.Automatic; /// @@ -1961,8 +2027,10 @@ public ServiceStartupType StartupType public PSCredential Credential { get { return credential; } + set { credential = value; } } + internal PSCredential credential = null; /// @@ -1973,8 +2041,10 @@ public PSCredential Credential public string[] DependsOn { get { return dependsOn; } + set { dependsOn = value; } } + internal string[] dependsOn = null; #endregion Parameters @@ -2023,6 +2093,7 @@ protected override void BeginProcessing() ErrorCategory.PermissionDenied); return; } + if (!NativeMethods.TryGetNativeStartupType(StartupType, out DWORD dwStartType)) { WriteNonTerminatingError(StartupType.ToString(), "New-Service", Name, @@ -2040,6 +2111,7 @@ protected override void BeginProcessing() { numchars += dependedOn.Length + 1; } + char[] doubleNullArray = new char[numchars]; int pos = 0; foreach (string dependedOn in DependsOn) @@ -2052,6 +2124,7 @@ protected override void BeginProcessing() pos += dependedOn.Length; doubleNullArray[pos++] = (char)0; // null terminator } + doubleNullArray[pos++] = (char)0; // double-null terminator Diagnostics.Assert(pos == numchars, "lpDependencies build error"); lpDependencies = Marshal.AllocHGlobal( @@ -2262,6 +2335,7 @@ protected override void ProcessRecord() service = new ServiceController(Name); objServiceShouldBeDisposed = true; } + Diagnostics.Assert(!String.IsNullOrEmpty(Name), "null ServiceName"); // "new ServiceController" will succeed even if there is no such service. @@ -2314,6 +2388,7 @@ protected override void ProcessRecord() ErrorCategory.PermissionDenied); return; } + hService = NativeMethods.OpenServiceW( hScManager, Name, @@ -2463,8 +2538,10 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont public string ServiceName { get { return _serviceName; } + set { _serviceName = value; } } + private string _serviceName = String.Empty; #endregion Properties } @@ -2706,6 +2783,7 @@ internal static bool QueryServiceConfig(NakedWin32Handle hService, out NativeMet { Marshal.FreeCoTaskMem(lpBuffer); } + return status; } @@ -2744,6 +2822,7 @@ internal static bool QueryServiceConfig2(NakedWin32Handle hService, DWORD inf { Marshal.FreeCoTaskMem(lpBuffer); } + return status; } @@ -2782,6 +2861,7 @@ internal static bool TryGetNativeStartupType(ServiceStartupType StartupType, out success = false; break; } + return success; } @@ -2800,6 +2880,7 @@ internal static ServiceStartupType GetServiceStartupType(ServiceStartMode startM result = ServiceStartupType.Disabled; break; } + return result; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 525c4a975c8..a158ac69bbb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -70,12 +70,14 @@ public class SetClipboardCommand : PSCmdlet public SwitchParameter AsHtml { get { return _asHtml; } + set { _isHtmlSet = true; _asHtml = value; } } + private bool _asHtml; private bool _isHtmlSet = false; @@ -150,6 +152,7 @@ private void SetClipboardContent(List contentList, bool append, bool asH { Clipboard.Clear(); } + return; } @@ -417,6 +420,7 @@ private static int GetByteCount(StringBuilder sb, int start = 0, int end = -1) _byteCount[0] = sb[i]; count += Encoding.UTF8.GetByteCount(_byteCount); } + return count; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs index c3d6b67db22..221e6bde4fd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs @@ -31,6 +31,7 @@ public class SetItemPropertyCommand : PassThroughItemPropertyCommandBase public string[] Path { get { return paths; } + set { paths = value; } } @@ -45,6 +46,7 @@ public string[] Path public string[] LiteralPath { get { return paths; } + set { base.SuppressWildcardExpansion = true; @@ -123,6 +125,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty(Name, Value)); } + break; default: @@ -134,6 +137,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Property.SetPropertyDynamicParameters(Path[0], mshObject, context); } + return InvokeProvider.Property.SetPropertyDynamicParameters(".", mshObject, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs index 846937d2484..db44142adaa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -58,6 +58,7 @@ public sealed class SetWmiInstance : WmiBaseCmdlet public PutType PutType { get { return _putType; } + set { _putType = value; flagSpecified = true; } } @@ -79,6 +80,7 @@ protected override void ProcessRecord() RunAsJob("Set-WMIInstance"); return; } + if (InputObject != null) { object result = null; @@ -94,6 +96,7 @@ protected override void ProcessRecord() { return; } + mObj.Put(pOptions); } else @@ -101,6 +104,7 @@ protected override void ProcessRecord() InvalidOperationException exp = new InvalidOperationException(); throw exp; } + result = mObj; } catch (ManagementException e) @@ -113,6 +117,7 @@ protected override void ProcessRecord() ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } + WriteObject(result); } else @@ -129,6 +134,7 @@ protected override void ProcessRecord() ComputerName = serverName; } } + ConnectionOptions options = GetConnectionOption(); object result = null; ManagementObject mObject = null; @@ -146,6 +152,7 @@ protected override void ProcessRecord() { continue; } + mObject.Put(pOptions); } else @@ -153,6 +160,7 @@ protected override void ProcessRecord() InvalidOperationException exp = new InvalidOperationException(); throw exp; } + result = mObject; } catch (ManagementException e) @@ -165,6 +173,7 @@ protected override void ProcessRecord() ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } + if (result != null) { WriteObject(result); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs index d39f5036caa..b0d7bd775f9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs @@ -25,6 +25,7 @@ public int Timeout { return (int)_timeout.TotalMinutes; } + set { // The transactions constructor treats a timeout of @@ -37,6 +38,7 @@ public int Timeout _timeoutSpecified = true; } } + private bool _timeoutSpecified = false; private TimeSpan _timeout = TimeSpan.MinValue; @@ -48,8 +50,10 @@ public int Timeout public SwitchParameter Independent { get { return _independent; } + set { _independent = value; } } + private SwitchParameter _independent; /// @@ -59,8 +63,10 @@ public SwitchParameter Independent public RollbackSeverity RollbackPreference { get { return _rollbackPreference; } + set { _rollbackPreference = value; } } + private RollbackSeverity _rollbackPreference = RollbackSeverity.Error; /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs index 329b577dcf7..53b1a48c0bd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -25,11 +25,13 @@ public ScriptBlock TransactedScript { return _transactedScript; } + set { _transactedScript = value; } } + private ScriptBlock _transactedScript; /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index eacdadb25d2..93085d0e40a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -40,6 +40,7 @@ internal Exception InternalException return internalException; } } + protected Exception internalException = null; } @@ -93,6 +94,7 @@ internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string c internal WmiState State { get { return _state; } + set { _state = value; } } @@ -122,6 +124,7 @@ private string GetWmiQueryString() returnValue.Append(" where "); returnValue.Append(getObject.Filter); } + return returnValue.ToString(); } @@ -155,6 +158,7 @@ internal override void StartOperation() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + thread.IsBackground = true; //thread.SetApartmentState( ApartmentState.STA); thread.Start(); @@ -212,6 +216,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + mObj = ((ManagementClass)setObject.InputObject).CreateInstance(); setObject.PutType = PutType.CreateOnly; } @@ -236,6 +241,7 @@ private void ConnectSetWmi() mObj = (ManagementObject)setObject.InputObject.Clone(); } + if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); @@ -244,6 +250,7 @@ private void ConnectSetWmi() mObj[en.Key as string] = en.Value; } } + pOptions.Type = setObject.PutType; if (mObj != null) { @@ -290,6 +297,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + setObject.PutType = PutType.CreateOnly; } else @@ -316,6 +324,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + if (mPath.IsClass) { if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) @@ -326,6 +335,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + setObject.PutType = PutType.CreateOnly; } else @@ -355,6 +365,7 @@ private void ConnectSetWmi() _computerName = mPath.Server; } } + ConnectionOptions options = setObject.GetConnectionOption(); ManagementObject mObject = null; try @@ -387,6 +398,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + int namespaceIndex = setObject.Path.IndexOf(':'); if (namespaceIndex == -1) { @@ -395,6 +407,7 @@ private void ConnectSetWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); if (classIndex == -1) { @@ -410,6 +423,7 @@ private void ConnectSetWmi() mClass.Scope = mScope; mInstance = mClass.CreateInstance(); } + mObject = mInstance; } } @@ -420,6 +434,7 @@ private void ConnectSetWmi() mClass.Scope = scope; mObject = mClass.CreateInstance(); } + if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); @@ -428,6 +443,7 @@ private void ConnectSetWmi() mObject[en.Key as string] = en.Value; } } + PutOptions pOptions = new PutOptions(); pOptions.Type = setObject.PutType; if (mObject != null) @@ -489,6 +505,7 @@ private void ConnectInvokeWmi() inParamCount--; } } + invokeObject.InputObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); } catch (ManagementException e) @@ -509,6 +526,7 @@ private void ConnectInvokeWmi() _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } + return; } else @@ -581,6 +599,7 @@ private void ConnectInvokeWmi() ManagementObject mInstance = new ManagementObject(mPath); mObject = mInstance; } + ManagementScope mScope = new ManagementScope(mPath, options); mObject.Scope = mScope; } @@ -719,6 +738,7 @@ private void ConnectRemoveWmi() _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } + return; } else @@ -750,11 +770,13 @@ private void ConnectRemoveWmi() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + if (!(mPath.Server == "." && removeObject.serverNameSpecified)) { _computerName = mPath.Server; } } + try { if (removeObject.Path != null) @@ -770,6 +792,7 @@ private void ConnectRemoveWmi() ManagementObject mInstance = new ManagementObject(mPath); mObject = mInstance; } + ManagementScope mScope = new ManagementScope(mPath, options); mObject.Scope = mScope; } @@ -780,6 +803,7 @@ private void ConnectRemoveWmi() mObject = mClass; mObject.Scope = scope; } + mObject.Delete(_results); } catch (ManagementException e) @@ -826,6 +850,7 @@ private void ConnectGetWMI() RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } + try { if (getObject.Recurse.IsPresent) @@ -849,6 +874,7 @@ private void ConnectGetWMI() namespaceArray.Add(connectNamespace + "\\" + obj["Name"]); } } + if (topNamespace) { topNamespace = false; @@ -858,6 +884,7 @@ private void ConnectGetWMI() { sinkArray.Add(_job.GetNewSink()); } + connectArray.Add(scope); currentNamespaceCount++; } @@ -880,6 +907,7 @@ private void ConnectGetWMI() currentNamespaceCount++; continue; } + if (topNamespace) { topNamespace = false; @@ -889,6 +917,7 @@ private void ConnectGetWMI() { searcher.Get((ManagementOperationObserver)sinkArray[currentNamespaceCount]); } + currentNamespaceCount++; } } @@ -920,8 +949,10 @@ private void ConnectGetWMI() _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } + return; } + string queryString = string.IsNullOrEmpty(getObject.Query) ? GetWmiQueryString() : getObject.Query; ObjectQuery query = new ObjectQuery(queryString.ToString()); try @@ -1110,6 +1141,7 @@ public class WmiBaseCmdlet : Cmdlet public string[] ComputerName { get { return _computerName; } + set { _computerName = value; serverNameSpecified = true; } } /// @@ -1124,6 +1156,7 @@ public string[] ComputerName public string Namespace { get { return _nameSpace; } + set { _nameSpace = value; namespaceSpecified = true; } } #endregion Parameters @@ -1171,6 +1204,7 @@ internal ConnectionOptions GetConnectionOption() options.SecurePassword = this.Credential.Password; } } + return options; } /// @@ -1208,11 +1242,13 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s { throw; } + int namespaceIndex = setObject.Path.IndexOf(':'); if (namespaceIndex == -1) { throw; } + int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); if (classIndex == -1) { @@ -1225,6 +1261,7 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s mClass.Scope = mScope; mInstance = mClass.CreateInstance(); } + mObject = mInstance; } } @@ -1235,6 +1272,7 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s mClass.Scope = scope; mObject = mClass.CreateInstance(); } + if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); @@ -1244,6 +1282,7 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s } } } + return mObject; } /// @@ -1267,6 +1306,7 @@ internal ManagementPath SetWmiInstanceBuildManagementPath() ErrorCategory.InvalidOperation, wmiInstance.PutType)); } + wmiInstance.PutType = PutType.CreateOnly; } else @@ -1295,6 +1335,7 @@ internal ManagementPath SetWmiInstanceBuildManagementPath() ErrorCategory.InvalidOperation, wmiInstance.ComputerName)); } + if (mPath.IsClass) { if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) @@ -1306,6 +1347,7 @@ internal ManagementPath SetWmiInstanceBuildManagementPath() ErrorCategory.InvalidOperation, wmiInstance.PutType)); } + wmiInstance.PutType = PutType.CreateOnly; } else @@ -1329,6 +1371,7 @@ internal ManagementPath SetWmiInstanceBuildManagementPath() } } } + return mPath; } @@ -1357,6 +1400,7 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() ErrorCategory.InvalidOperation, wmiInstance.PutType)); } + mObj = ((ManagementClass)wmiInstance.InputObject).CreateInstance(); wmiInstance.PutType = PutType.CreateOnly; } @@ -1382,6 +1426,7 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() mObj = (ManagementObject)wmiInstance.InputObject.Clone(); } + if (wmiInstance.Arguments != null) { IDictionaryEnumerator en = wmiInstance.Arguments.GetEnumerator(); @@ -1392,6 +1437,7 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() } } } + return mObj; } @@ -1405,6 +1451,7 @@ internal void RunAsJob(string cmdletName) { ((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob); } + WriteObject(wmiJob); } // Get the PowerShell execution context if it's available at cmdlet creation time... @@ -1435,6 +1482,7 @@ internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimt, string c job.JobUnblocked += new EventHandler(HandleJobUnblocked); ChildJobs.Add(job); } + CommonInit(throttleLimt); } @@ -1496,6 +1544,7 @@ private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) { return; } + if (e.JobStateInfo.State == JobState.Failed) { //If any of the child job failed, we set status to failed @@ -1513,6 +1562,7 @@ private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) allChildJobsFinished = true; } } + if (allChildJobsFinished) { //if any child job failed, set status to failed @@ -1599,6 +1649,7 @@ public override string Location return ConstructLocation(); } } + private String ConstructLocation() { StringBuilder location = new StringBuilder(); @@ -1608,6 +1659,7 @@ private String ConstructLocation() location.Append(job.Location); location.Append(","); } + location.Remove(location.Length - 1, 1); return location.ToString(); @@ -1647,6 +1699,7 @@ protected override void Dispose(bool disposing) { StopJob(); } + _throttleManager.Dispose(); foreach (Job job in ChildJobs) { @@ -1796,6 +1849,7 @@ internal void UnblockJob() SetJobState(JobState.Running, null); JobUnblocked.SafeInvoke(this, EventArgs.Empty); } + internal ManagementOperationObserver GetNewSink() { ManagementOperationObserver wmiSink = new ManagementOperationObserver(); @@ -1804,6 +1858,7 @@ internal ManagementOperationObserver GetNewSink() { _sinkCompleted++; } + wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); wmiSink.Completed += new CompletedEventHandler(this.JobDone); return wmiSink; @@ -1818,6 +1873,7 @@ private void NewObject(object sender, ObjectReadyEventArgs obj) { _bAtLeastOneObject = true; } + this.WriteObject(obj.NewObject); } @@ -1830,10 +1886,12 @@ private void JobDone(object sender, CompletedEventArgs obj) { _sinkCompleted--; } + if (obj.Status != ManagementStatus.NoError) { _bJobFailed = true; } + if (_sinkCompleted == 0) { //Notify throttle manager and change the state to complete @@ -1865,6 +1923,7 @@ private void JobDoneForWin32Shutdown(object sender, EventArgs arg) { _sinkCompleted--; } + if (_sinkCompleted == 0) { _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); @@ -1929,6 +1988,7 @@ protected override void Dispose(bool disposing) } } } + private bool _isDisposed; /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 84d966e9094..e82d60c7625 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -47,11 +47,13 @@ public sealed class NewWebServiceProxy : PSCmdlet public System.Uri Uri { get { return _uri; } + set { _uri = value; } } + private System.Uri _uri; /// @@ -63,11 +65,13 @@ public System.Uri Uri public string Class { get { return _class; } + set { _class = value; } } + private string _class; /// @@ -79,11 +83,13 @@ public string Class public string Namespace { get { return _namespace; } + set { _namespace = value; } } + private string _namespace; /// @@ -96,11 +102,13 @@ public string Namespace public PSCredential Credential { get { return _credential; } + set { _credential = value; } } + private PSCredential _credential; /// @@ -112,11 +120,13 @@ public PSCredential Credential public SwitchParameter UseDefaultCredential { get { return _usedefaultcredential; } + set { _usedefaultcredential = value; } } + private SwitchParameter _usedefaultcredential; #endregion @@ -184,9 +194,11 @@ protected override void BeginProcessing() _class = data[1]; } } + sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture); } } + if (string.IsNullOrEmpty(_namespace)) { _namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName(); @@ -214,6 +226,7 @@ protected override void BeginProcessing() pr.SetValue(instance, flag as object, null); } } + if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase)) { if (Credential != null) @@ -230,6 +243,7 @@ protected override void BeginProcessing() { s_uriCache.Remove(_uri); } + if (sourceCache > 0) { lock (_cachelock) @@ -237,11 +251,13 @@ protected override void BeginProcessing() s_srccodeCache.Remove(sourceCache); } } + string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) }); lock (s_uriCache) { s_uriCache.Add(_uri, key); } + lock (_cachelock) { s_srccodeCache.Add(_sourceHash, instance); @@ -288,6 +304,7 @@ private string GenerateRandomName() { return (sequenceString + rndname.Substring(rndname.Length - 30)); } + return (sequenceString + rndname); } @@ -385,6 +402,7 @@ private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassN WriteObject(obj, true); return null; } + CompilerParameters options = new CompilerParameters(); CompilerResults results = null; @@ -454,6 +472,7 @@ private object InstantiateWebServiceProxy(Assembly assembly) proxyType = type; break; } + if (proxyType != null) break; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 2087f6e5e91..41e3dd70345 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -239,6 +239,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) { return InvokeProvider.Content.GetContentWriterDynamicParameters(Path[0], context); } + return InvokeProvider.Content.GetContentWriterDynamicParameters(".", context); } From ee8d71e6ef1441aa4750d09818ae172be16c42ff Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:23 -0800 Subject: [PATCH 80/81] Update WindowsTaskbarJumpList --- .../WindowsTaskbarJumpList/ComInterfaces.cs | 2 +- .../WindowsTaskbarJumpList/HResult.cs | 2 +- .../WindowsTaskbarJumpList/PropVariant.cs | 2 +- .../WindowsTaskbarJumpList/PropertyKey.cs | 2 +- .../WindowsTaskbarJumpList/TaskbarJumpList.cs | 6 +++++- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs index f4596b5b6a4..1cf2749928d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs index c7d24c65581..8398be9cf26 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.PowerShell diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 614d4e92ab0..c1dd5782724 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index 94dea27ee60..c02603f104a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 69e4e264fa9..7d03d0b8368 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; @@ -31,6 +31,7 @@ internal static void CreateElevatedEntry(string title) Debug.Fail($"Creating ICustomDestinationList failed with HResult '{hResult}'."); return; } + var pCustDestList = (ICustomDestinationList)pCustDestListobj; hResult = pCustDestList.BeginList(out uint uMaxSlots, new Guid(@"92CA9DCD-5622-4BBA-A805-5E9F541BD8C9"), out object pRemovedItems); if (hResult < 0) @@ -59,6 +60,7 @@ internal static void CreateElevatedEntry(string title) Debug.Fail($"SetValue on IPropertyStore with title '{title}' failed with HResult '{hResult}'."); return; } + hResult = nativePropertyStore.Commit(); if (hResult < 0) { @@ -79,6 +81,7 @@ internal static void CreateElevatedEntry(string title) Debug.Fail($"Creating IObjectCollection failed with HResult '{hResult}'."); return; } + var pShortCutCollection = (IObjectCollection)instance; pShortCutCollection.AddObject((IShellLinkW)nativePropertyStore); @@ -90,6 +93,7 @@ internal static void CreateElevatedEntry(string title) Debug.Fail($"AddUserTasks on ICustomDestinationList failed with HResult '{hResult}'."); return; } + pCustDestList.CommitList(); } } From c8d7f980b336baa0b68050ca6bcb85ce0eff31f7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Sun, 23 Dec 2018 09:46:24 -0800 Subject: [PATCH 81/81] Update msh --- .../host/msh/CommandLineParameterParser.cs | 12 ++++++ .../host/msh/ConsoleControl.cs | 29 +++++++++++++ .../host/msh/ConsoleHost.cs | 43 +++++++++++++++++++ .../host/msh/ConsoleHostRawUserInterface.cs | 21 +++++++++ .../host/msh/ConsoleHostTranscript.cs | 2 + .../host/msh/ConsoleHostUserInterface.cs | 19 ++++++++ .../msh/ConsoleHostUserInterfaceProgress.cs | 1 + .../msh/ConsoleHostUserInterfacePrompt.cs | 14 ++++++ ...ConsoleHostUserInterfacePromptForChoice.cs | 1 + .../msh/ConsoleHostUserInterfaceSecurity.cs | 1 + .../host/msh/Executor.cs | 4 ++ .../host/msh/ManagedEntrance.cs | 3 ++ .../host/msh/PendingProgress.cs | 3 ++ .../host/msh/ProgressNode.cs | 2 + .../host/msh/ProgressPane.cs | 1 + .../host/msh/Serialization.cs | 5 +++ .../host/msh/StartTranscriptCmdlet.cs | 10 +++++ .../host/msh/Telemetry.cs | 1 + 18 files changed, 172 insertions(+) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 38d657905a9..af55d568bcb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -195,6 +195,7 @@ internal class CommandLineParameterParser internal CommandLineParameterParser(PSHostUserInterface hostUI, string bannerText, string helpText) { if (hostUI == null) { throw new PSArgumentNullException("hostUI"); } + _hostUI = hostUI; _bannerText = bannerText; @@ -478,6 +479,7 @@ private static bool TryParseSettingFileHelper(string[] args, int settingFileArgI return false; } + PowerShellConfig.Instance.SetSystemConfigFilePath(configFile); return true; } @@ -629,6 +631,7 @@ private void ShowHelp() { _hostUI.Write(ManagedEntranceStrings.ExtendedHelp); } + _hostUI.WriteLine(string.Empty); } @@ -865,8 +868,10 @@ private void ParseHelper(string[] args) ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg }); moduleCount++; } + ++i; } + if (moduleCount < 1) { _hostUI.WriteErrorLine("No modules specified for -module option"); @@ -1067,6 +1072,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) boolValue = false; return true; } + boolValue = false; return false; } @@ -1136,6 +1142,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) possibleParameters.Append(validParameter); } } + if (possibleParameters.Length > 0) { WriteCommandLineError( @@ -1145,6 +1152,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) return false; } } + WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]), showHelp: true); @@ -1199,9 +1207,11 @@ bool TryGetBoolValue(string arg, out bool boolValue) { _collectedArgs.Add(new CommandParameter(null, arg)); } + ++i; } } + return true; } @@ -1283,11 +1293,13 @@ private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEnco cmdLineCmdSB.Append(args[i] + " "); ++i; } + if (cmdLineCmdSB.Length > 0) { // remove the last blank cmdLineCmdSB.Remove(cmdLineCmdSB.Length - 1, 1); } + _commandLineCommand = cmdLineCmdSB.ToString(); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 9c90b6e7964..8787639edb5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -770,6 +770,7 @@ internal static string ReadConsole(ConsoleHandle consoleHandle, string initialCo ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleExceptionTemplate); throw e; } + if (charsReadUnused > (uint)buffer.Length) charsReadUnused = (uint)buffer.Length; return buffer.ToString(0, (int)charsReadUnused); @@ -812,6 +813,7 @@ internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECO ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleInputExceptionTemplate); throw e; } + return (int)recordsRead; } @@ -1011,6 +1013,7 @@ internal static bool IsConsoleColor(ConsoleColor c) case ConsoleColor.Yellow: return true; } + return false; } @@ -1063,6 +1066,7 @@ internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates { throw PSTraceSource.NewArgumentNullException("contents"); } + uint codePage; if (IsCJKOutputCodePage(out codePage)) { @@ -1148,10 +1152,12 @@ private static void BuildEdgeTypeInfo( { firstLeftTrailingRow = r; } + if (firstRightLeadingRow == -1 && ((range.Type & BufferCellArrayRowType.RightLeading) != 0)) { firstRightLeadingRow = r; } + for (;;) { r++; @@ -1161,6 +1167,7 @@ private static void BuildEdgeTypeInfo( sameEdgeAreas.Add(range); return; } + edgeType = GetEdgeType(contents[r, contentsRegion.Left], contents[r, contentsRegion.Right]); if (edgeType != range.Type) { @@ -1179,10 +1186,12 @@ private static BufferCellArrayRowType GetEdgeType(BufferCell left, BufferCell ri { edgeType |= BufferCellArrayRowType.LeftTrailing; } + if (right.BufferCellType == BufferCellType.Leading) { edgeType |= BufferCellArrayRowType.RightLeading; } + return edgeType; } @@ -1305,6 +1314,7 @@ private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rect { break; } + if (contents[r, c].Character != 0 || contents[r, c].BufferCellType != BufferCellType.Trailing) { // for a 2 cell character, either there is no trailing BufferCell or @@ -1385,6 +1395,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat bufferSize.X--; writeRegion.Right--; } + CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X]; // copy characterBuffer to contents; @@ -1444,6 +1455,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat // We don't output anything for this cell if Raster font is in use, or if the last cell is not a leading byte characterBufferIndex--; } + lastCharIsLeading = false; } } @@ -1481,6 +1493,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat bufferCoord, ref writeRegion); } + if (result == false) { // When WriteConsoleOutput fails, half bufferLimit @@ -1491,6 +1504,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate); throw e; } + bufferLimit /= 2; if (cols == colsRemaining) { @@ -1531,6 +1545,7 @@ private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordin tracer.WriteLine("contents passed in has 0 rows and columns"); return; } + int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes COORD bufferCoord; @@ -1617,6 +1632,7 @@ private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordin ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate); throw e; } + bufferLimit /= 2; if (cols == colsRemaining) { @@ -1713,6 +1729,7 @@ internal static void ReadConsoleOutput { cellArray = new BufferCell[cellArrayRegion.Bottom + 1, 2]; } + checkOrigin = new Coordinates(origin.X + (contentsRegion.Right - contentsRegion.Left), origin.Y); ReadConsoleOutputCJK(consoleHandle, codePage, checkOrigin, @@ -1750,6 +1767,7 @@ private static bool ShouldCheck(int edge, BufferCell[,] contents, Rectangle cont return true; } } + return false; } @@ -1787,6 +1805,7 @@ private static bool ReadConsoleOutputCJKSmall { return false; } + int characterBufferIndex = 0; for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; r++) @@ -1840,6 +1859,7 @@ private static bool ReadConsoleOutputCJKSmall } } } + return true; } @@ -1964,6 +1984,7 @@ internal static void ReadConsoleOutputCJK } } } + colsRemaining -= bufferSize.X; readRegion.Left += bufferSize.X; if (colsRemaining > 0 && (bufferSize.Y == 1) && @@ -1972,6 +1993,7 @@ internal static void ReadConsoleOutputCJK colsRemaining++; readRegion.Left--; } + bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); } // column iteration @@ -2015,10 +2037,12 @@ out background { break; } + contents[rowIndex, colIndex] = new BufferCell( ' ', foreground, background, BufferCellType.Complete); colIndex++; } + rowIndex++; } } @@ -2149,6 +2173,7 @@ private static void ReadConsoleOutputPlain contents[r, c].BackgroundColor = bgColor; } } + colsRemaining -= bufferSize.X; readRegion.Left += bufferSize.X; bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); @@ -2194,11 +2219,13 @@ out background { break; } + contents[rowIndex, colIndex].Character = ' '; contents[rowIndex, colIndex].ForegroundColor = foreground; contents[rowIndex, colIndex].BackgroundColor = background; colIndex++; } + rowIndex++; } } @@ -2742,6 +2769,7 @@ internal static CONSOLE_CURSOR_INFO GetConsoleCursorInfo(ConsoleHandle consoleHa ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleCursorInfoExceptionTemplate); throw e; } + return cursorInfo; } @@ -2762,6 +2790,7 @@ internal static CONSOLE_FONT_INFO_EX GetConsoleFontInfo(ConsoleHandle consoleHan ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleFontInfoExceptionTemplate); throw e; } + return fontInfo; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index a6671339901..72985cacd5d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -188,6 +188,7 @@ internal static int Start( { s_theConsoleHost.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); } + return ExitCodeBadCommandLineParameter; } @@ -266,6 +267,7 @@ internal static int Start( return (int)exitCode; } } + private static CommandLineParameterParser s_cpp; #if UNIX @@ -292,6 +294,7 @@ private static void MyBreakHandler(object sender, ConsoleCancelEventArgs args) // Break into script debugger. BreakIntoDebugger(); } + return; } } @@ -316,6 +319,7 @@ private static bool MyBreakHandler(ConsoleControl.ConsoleBreakSignal signal) // Break into script debugger. BreakIntoDebugger(); } + return true; // Run the break handler... @@ -355,6 +359,7 @@ private static bool BreakIntoDebugger() debugger = host._runspaceRef.Runspace.Debugger; } } + if (debugger != null) { debugger.SetDebuggerStepMode(true); @@ -562,6 +567,7 @@ public override PSHostUserInterface UI public void PushRunspace(Runspace newRunspace) { if (_runspaceRef == null) { return; } + RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); remoteRunspace.StateChanged += new EventHandler(HandleRemoteRunspaceStateChanged); @@ -623,6 +629,7 @@ private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventA { PopRunspace(); } + break; } } @@ -682,6 +689,7 @@ public bool IsRunspacePushed return _isRunspacePushed; } } + private bool _isRunspacePushed = false; /// @@ -692,6 +700,7 @@ public Runspace Runspace get { if (this.RunspaceRef == null) { return null; } + return this.RunspaceRef.Runspace; } } @@ -704,7 +713,9 @@ internal LocalRunspace LocalRunspace { return RunspaceRef.OldRunspace as LocalRunspace; } + if (RunspaceRef == null) { return null; } + return RunspaceRef.Runspace as LocalRunspace; } } @@ -724,6 +735,7 @@ public ConsoleColor ErrorForegroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.ErrorForegroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.ErrorForegroundColor = value; } @@ -734,6 +746,7 @@ public ConsoleColor ErrorBackgroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.ErrorBackgroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.ErrorBackgroundColor = value; } @@ -744,6 +757,7 @@ public ConsoleColor WarningForegroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.WarningForegroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.WarningForegroundColor = value; } @@ -754,6 +768,7 @@ public ConsoleColor WarningBackgroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.WarningBackgroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.WarningBackgroundColor = value; } @@ -764,6 +779,7 @@ public ConsoleColor DebugForegroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.DebugForegroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.DebugForegroundColor = value; } @@ -774,6 +790,7 @@ public ConsoleColor DebugBackgroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.DebugBackgroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.DebugBackgroundColor = value; } @@ -784,6 +801,7 @@ public ConsoleColor VerboseForegroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.VerboseForegroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.VerboseForegroundColor = value; } @@ -794,6 +812,7 @@ public ConsoleColor VerboseBackgroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.VerboseBackgroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.VerboseBackgroundColor = value; } @@ -804,6 +823,7 @@ public ConsoleColor ProgressForegroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.ProgressForegroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.ProgressForegroundColor = value; } @@ -814,6 +834,7 @@ public ConsoleColor ProgressBackgroundColor [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { return _ui.ProgressBackgroundColor; } + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] set { _ui.ProgressBackgroundColor = value; } @@ -832,6 +853,7 @@ public override PSObject PrivateData return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui))); } } + private PSObject _consoleColorProxy; /// @@ -917,6 +939,7 @@ public override void EnterNestedPrompt() { IsNested = oldCurrent != null || this.ui.IsCommandCompletionRunning; } + InputLoop.RunNewInputLoop(this, IsNested); } finally @@ -998,8 +1021,11 @@ bool IHostProvidesTelemetryData.HostIsInteractive ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit); } } + double IHostProvidesTelemetryData.ProfileLoadTimeInMS { get { return _profileLoadTimeInMS; } } + double IHostProvidesTelemetryData.ReadyForInputTimeInMS { get { return _readyForInputTimeInMS; } } + int IHostProvidesTelemetryData.InteractiveCommandCount { get { return _interactiveCommandCount; } } #endif @@ -1117,14 +1143,17 @@ private void Dispose(bool isDisposingNotFinalizing) { StopTranscribing(); } + if (_outputSerializer != null) { _outputSerializer.End(); } + if (_errorSerializer != null) { _errorSerializer.End(); } + if (_runspaceRef != null) { // NTRAID#Windows Out Of Band Releases-925297-2005/12/14 @@ -1136,6 +1165,7 @@ private void Dispose(bool isDisposingNotFinalizing) { } } + _runspaceRef = null; ui = null; } @@ -1166,6 +1196,7 @@ internal bool ShouldEndSession return result; } + set { lock (hostGlobalLock) @@ -1193,6 +1224,7 @@ internal RunspaceRef RunspaceRef } internal WrappedSerializer.DataFormat OutputFormat { get; private set; } + internal bool OutputFormatSpecified { get; private set; } internal WrappedSerializer.DataFormat InputFormat { get; private set; } @@ -1209,6 +1241,7 @@ internal WrappedDeserializer.DataFormat ErrorFormat { format = Serialization.DataFormat.XML; } + return format; } } @@ -1235,6 +1268,7 @@ internal WrappedSerializer OutputSerializer "Output", Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter); } + return _outputSerializer; } } @@ -1251,6 +1285,7 @@ internal WrappedSerializer ErrorSerializer "Error", Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter); } + return _errorSerializer; } } @@ -1443,6 +1478,7 @@ private Exception InitializeRunspaceHelper(string command, Executor exec, Execut { exec.ExecuteCommand(command, out e, options); } + if (e != null) { ReportException(e, exec); @@ -1543,6 +1579,7 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta DefaultInitialSessionState.ClearPSModules(); DefaultInitialSessionState.ImportPSModule(defaultImportModulesList); } + consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); OpenConsoleRunspace(consoleRunspace, staMode); } @@ -1728,6 +1765,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, { c = new Command(filePath, false, false); } + tempPipeline.Commands.Add(c); if (initialCommandArgs != null) @@ -1891,6 +1929,7 @@ internal static string EscapeSingleQuotes(string str) { sb.Append(c); } + sb.Append(c); } @@ -2335,13 +2374,16 @@ internal void Run(bool inputLoopIsNested) { prompt = EvaluateDebugPrompt(); } + if (prompt == null) { prompt = EvaluatePrompt(); } } + ui.Write(prompt); } + previousResponseWasEmpty = false; // There could be a profile. So there could be a user defined custom readline command line = ui.ReadLineWithTabCompletion(_exec); @@ -2360,6 +2402,7 @@ internal void Run(bool inputLoopIsNested) // the output... ui.WriteLine(); } + inBlockMode = false; if (Console.IsInputRedirected) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 5f789c1928d..21b373ea914 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -94,6 +94,7 @@ public override ConsoleControl.WORDToColor(bufferInfo.Attributes, out foreground, out unused); return foreground; } + set { if (ConsoleControl.IsConsoleColor(value)) @@ -144,6 +145,7 @@ public override ConsoleControl.WORDToColor(bufferInfo.Attributes, out unused, out background); return background; } + set { if (ConsoleControl.IsConsoleColor(value)) @@ -190,6 +192,7 @@ public override Coordinates c = new Coordinates(bufferInfo.CursorPosition.X, bufferInfo.CursorPosition.Y); return c; } + set { // cursor position can't be outside the buffer area @@ -231,6 +234,7 @@ public override return size; } + set { const int MinCursorSize = 0; @@ -288,6 +292,7 @@ public override return c; } + set { ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; @@ -351,6 +356,7 @@ public override GetBufferInfo(out bufferInfo); return new Size(bufferInfo.BufferSize.X, bufferInfo.BufferSize.Y); } + set { // looking in windows/core/ntcon/server/output.c, it looks like the minimum size is 1 row X however many @@ -409,6 +415,7 @@ public override return s; } + set { ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; @@ -626,6 +633,7 @@ public override cachedKeyEvent.RepeatCount = 0; } } + if (cachedKeyEvent.RepeatCount > 0) { KEY_EVENT_RECORDToKeyInfo(cachedKeyEvent, out keyInfo); @@ -779,6 +787,7 @@ public override // represent a keystroke. continue; } + return true; } } @@ -808,6 +817,7 @@ public override string WindowTitle { return ConsoleControl.GetConsoleWindowTitle(); } + set { const int MaxWindowTitleLength = 1023; @@ -1037,11 +1047,13 @@ public override } } } + if (lineLength % 2 == 1) { lineLength++; } } + for (int row = firstRow; row <= lastRow; ++row) { origin.Y = row; @@ -1222,6 +1234,7 @@ int LengthInBufferCells(string s, int offset) { throw PSTraceSource.NewArgumentNullException("str"); } + return ConsoleControl.LengthInBufferCells(s, offset, parent.SupportsVirtualTerminal); } @@ -1357,6 +1370,7 @@ internal ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base public override ConsoleColor BackgroundColor { get { return Console.BackgroundColor; } + set { Console.BackgroundColor = value; } } @@ -1376,6 +1390,7 @@ public override Size BufferSize ? s_wrapSize : new Size(Console.BufferWidth, Console.BufferHeight); } + set { Console.SetBufferSize(value.Width, value.Height); } } @@ -1385,6 +1400,7 @@ public override Size BufferSize public override Coordinates CursorPosition { get { return new Coordinates(Console.CursorLeft, Console.CursorTop); } + set { Console.SetCursorPosition(value.X < 0 ? 0 : value.X, @@ -1401,6 +1417,7 @@ public override int CursorSize // Future porting note: this API throws on Windows when output is // redirected, but never throws on Unix because it's fake. get { return Console.CursorSize; } + set { Console.CursorSize = value; } } @@ -1411,6 +1428,7 @@ public override int CursorSize public override ConsoleColor ForegroundColor { get { return Console.ForegroundColor; } + set { Console.ForegroundColor = value; } } @@ -1459,6 +1477,7 @@ public override Size MaxWindowSize public override Coordinates WindowPosition { get { return new Coordinates(Console.WindowLeft, Console.WindowTop); } + set { Console.SetWindowPosition(value.X, value.Y); } } @@ -1477,6 +1496,7 @@ public override Size WindowSize ? s_wrapSize : new Size(Console.WindowWidth, Console.WindowHeight); } + set { Console.SetWindowSize(value.Width, value.Height); } } @@ -1688,6 +1708,7 @@ int LengthInBufferCells(string s, int offset) { throw PSTraceSource.NewArgumentNullException("str"); } + return ConsoleControl.LengthInBufferCells(s, offset, _parent.SupportsVirtualTerminal); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs index 61f56ee1319..e6061e0595f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -26,11 +26,13 @@ class ConsoleHost return _isTranscribing; } + set { _isTranscribing = value; } } + private bool _isTranscribing; /* diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 62199895a78..4f6b2da8efc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -200,6 +200,7 @@ public override SecureString ReadLineAsSecureString() { result = ReadLineSafe(true, printToken); } + SecureString secureResult = result as SecureString; System.Management.Automation.Diagnostics.Assert(secureResult != null, "ReadLineSafe did not return a SecureString"); @@ -290,6 +291,7 @@ private object ReadLineSafe(bool isSecureString, char? printToken) { isModeChanged = false; } + _rawui.ClearKeyCache(); #endif @@ -378,6 +380,7 @@ private object ReadLineSafe(bool isSecureString, char? printToken) result.Append(key); #endif } + if (!string.IsNullOrEmpty(printTokenString)) { WritePrintToken(printTokenString, ref originalCursorPos); @@ -404,6 +407,7 @@ private object ReadLineSafe(bool isSecureString, char? printToken) } #endif } + WriteLineToConsole(); PostRead(result.ToString()); if (isSecureString) @@ -452,6 +456,7 @@ private void WritePrintToken( originalCursorPosition.Y--; } } + WriteToConsole(printToken, false); } @@ -529,6 +534,7 @@ private static bool shouldUnsetMode( m &= ~flagToUnset; return true; } + return false; } #endif @@ -774,6 +780,7 @@ internal List WrapText(string text, int maxWidthInBufferCells) Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long"); result.Add(l); } + break; } @@ -931,6 +938,7 @@ internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result); startIndex = wordEnd; } + inWs = true; } else @@ -942,6 +950,7 @@ internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result); startIndex = wordEnd; } + inWs = false; } @@ -952,6 +961,7 @@ internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) { AddWord(text, startIndex, text.Length, maxWidthInBufferCells, inWs, ref result); } + return result; } @@ -1375,6 +1385,7 @@ private string ReadLineFromFile(string initialContent) if (!NoPrompt) Console.Out.Write('\n'); consoleIn.Read(); } + break; } @@ -1483,6 +1494,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca throw new PipelineStoppedException(); } + break; } @@ -1572,6 +1584,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Console.Out.Write(s.PadRight(length)); Console.CursorLeft = cursorCurrent - 1; } + continue; } @@ -1587,6 +1600,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Console.Out.Write(s.PadRight(length)); Console.CursorLeft = cursorCurrent; } + continue; } @@ -1598,6 +1612,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Console.CursorLeft--; index--; } + continue; } @@ -1609,6 +1624,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Console.CursorLeft++; index++; } + continue; } @@ -1742,6 +1758,7 @@ private string RemoveNulls(string input) if (c != '\0') sb.Append(c); } + return sb.ToString(); } @@ -1819,6 +1836,7 @@ internal string ReadLineWithTabCompletion(Executor exec) input = input.Remove(input.Length - 1); restOfLine = input.Substring(tabIndex + 1); } + input = input.Remove(tabIndex); if (input != lastCompletion || commandCompletion == null) @@ -2049,6 +2067,7 @@ internal bool ThrowOnReadAndPrompt _throwOnReadAndPrompt = value; } } + private bool _throwOnReadAndPrompt; internal void HandleThrowOnReadAndPrompt() diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index cc12c942d8f..d6308575153 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -45,6 +45,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt _progPane.Hide(); _progPane = null; } + _pendingProgress = null; } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index aef5d4bd025..4687a72793e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -121,6 +121,7 @@ public override WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); WriteLineToConsole(); } + if (!String.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); @@ -142,6 +143,7 @@ public override ConsoleHostUserInterfaceStrings.NullErrorTemplate, string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex)); } + PSObject inputPSObject = null; string fieldPrompt = null; fieldPrompt = desc.Name; @@ -251,6 +253,7 @@ public override inputPSObject = PSObject.AsPSObject(convertedObj); } } + if (cancelInput) { s_tracer.WriteLine("Prompt canceled"); @@ -258,8 +261,10 @@ public override results.Clear(); break; } + results.Add(desc.Name, PSObject.AsPSObject(inputPSObject)); } + return results; } } @@ -362,6 +367,7 @@ private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool f System.Management.Automation.Diagnostics.Assert(userInputString != null, "ReadLineSafe did not return a string"); rawInputString = userInputString; } + if (rawInputString == null) { // processedInputString is null as well. No need to assign null to it. @@ -379,10 +385,12 @@ private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool f { endListInput = true; } + processedInputString = rawInputString; break; } } + return processedInputString; } @@ -437,6 +445,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe WrapToCurrentWindowWidth( string.Format(CultureInfo.CurrentCulture, errMsgTemplate, fieldType, inputString))); } + return PromptCommonInputErrors.Format; } else @@ -447,6 +456,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe { } } + return PromptCommonInputErrors.None; } @@ -478,6 +488,7 @@ private string PromptCommandMode(string input, FieldDescription desc, out bool i { return command; } + if (command.Length == 1) { if (command[0] == '?') @@ -498,9 +509,11 @@ private string PromptCommandMode(string input, FieldDescription desc, out bool i { ReportUnrecognizedPromptCommand(input); } + inputDone = false; return null; } + if (command.Length == 2) { if (0 == string.Compare(command, "\"\"", StringComparison.OrdinalIgnoreCase)) @@ -508,6 +521,7 @@ private string PromptCommandMode(string input, FieldDescription desc, out bool i return string.Empty; } } + if (0 == string.Compare(command, "$null", StringComparison.OrdinalIgnoreCase)) { return null; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index b33854fb729..2b73f84d22a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -360,6 +360,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, "{0}{1}", prepend, defaultStr)); prepend = ","; } + string defaultChoices = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs index 4deb8b1f23b..aee9db4a145 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -112,6 +112,7 @@ public override PSCredential PromptForCredential( { return null; } + WriteLineToConsole(); cred = new PSCredential(userName, password); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index e89408fe512..e9959bdcb92 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -123,6 +123,7 @@ private void AsyncPipelineFailureHandler(Exception ex) { er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); } + _parent.ErrorSerializer.Serialize(er); } @@ -243,6 +244,7 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc }; des.End(); } + tempPipeline.Input.Close(); pipelineWaiter.Wait(); @@ -451,6 +453,7 @@ internal Collection ExecuteCommand(string command) { break; } + if (result == null) { break; @@ -693,6 +696,7 @@ internal static Executor CurrentExecutor return result; } + set { lock (s_staticStateLock) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 63964e3e311..5a10264e514 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -58,6 +58,7 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray while (!System.Diagnostics.Debugger.IsAttached) { Thread.Sleep(100); } + System.Diagnostics.Debugger.Break(); } #endif @@ -87,12 +88,14 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray return exitCode; } } + System.Environment.FailFast(e.Message, e); } catch (Exception e) { System.Environment.FailFast(e.Message, e); } + return exitCode; } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index a4c10600fa3..e0c2b011d4c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -72,6 +72,7 @@ class PendingProgress RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound); break; } + if (record.ParentActivityId == foundNode.ParentActivityId) { // record is an update to an existing activity. Copy the record data into the found node, and @@ -387,6 +388,7 @@ internal override this.IndexWhereFound = indexWhereFound; return false; } + return true; } @@ -741,6 +743,7 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt { return false; } + if (node.Children != null) { if (!AllNodesHaveGivenStyle(node.Children, style)) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index 22e62f73404..01fb9977c2a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -451,10 +451,12 @@ private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int max { ++lines; } + if (SecondsRemaining >= 0) { ++lines; } + if (!String.IsNullOrEmpty(CurrentOperation)) { if (isFullPlus) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index d98f04861b5..7323fb256a4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -225,6 +225,7 @@ class ProgressPane { Hide(); } + Show(); } else diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 6a7aa22a7f5..ff8284b2518 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -107,6 +107,7 @@ class WrappedSerializer : Serialization _firstCall = false; textWriter.WriteLine(Serialization.XmlCliTag); } + _xmlSerializer.Serialize(o, streamName); break; case DataFormat.Text: @@ -204,6 +205,7 @@ class WrappedDeserializer : Serialization { return null; } + if (_firstLine != null) { o = _firstLine; @@ -217,8 +219,10 @@ class WrappedDeserializer : Serialization _atEnd = true; } } + break; } + return o; } @@ -245,6 +249,7 @@ class WrappedDeserializer : Serialization result = _atEnd; break; } + return result; } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index 5c1de82aada..58794e92f12 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -32,6 +32,7 @@ public string Path { return _outFilename; } + set { _isFilenameSet = true; @@ -51,6 +52,7 @@ public string LiteralPath { return _outFilename; } + set { _isFilenameSet = true; @@ -58,6 +60,7 @@ public string LiteralPath _isLiteralPath = true; } } + private bool _isLiteralPath = false; /// @@ -82,6 +85,7 @@ public SwitchParameter Append { return _shouldAppend; } + set { _shouldAppend = value; @@ -103,11 +107,13 @@ public SwitchParameter Force { return _force; } + set { _force = value; } } + private bool _force; /// @@ -121,11 +127,13 @@ public SwitchParameter NoClobber { return _noclobber; } + set { _noclobber = value; } } + private bool _noclobber; /// @@ -298,6 +306,7 @@ private string ResolveFilePath(string filePath, bool isLiteralPath) { path = null; } + if (string.IsNullOrEmpty(path)) { CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(this); @@ -312,6 +321,7 @@ private string ResolveFilePath(string filePath, bool isLiteralPath) ReportWrongProviderType(provider.FullName); } } + return path; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs index fea8a667084..a1a879936aa 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs @@ -77,6 +77,7 @@ private static void SendTelemetry(string eventName, Dictionary pa { _telemetryClient = new TelemetryClient(); } + _telemetryClient.TrackEvent(eventName, payload, null); } catch (Exception)