Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
CommandDiscoveryExceptions.cs478 linesDownload Raw Back to utils
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System.Collections.ObjectModel;5using System.Management.Automation.Internal;6using System.Runtime.Serialization;7using System.Text;8 9namespace System.Management.Automation10{11    /// <summary>12    /// This exception is thrown when a command cannot be found.13    /// </summary>14    public class CommandNotFoundException : RuntimeException15    {16        /// <summary>17        /// Constructs a CommandNotFoundException. This is the recommended constructor.18        /// </summary>19        /// <param name="commandName">20        /// The name of the command that could not be found.21        /// </param>22        /// <param name="innerException">23        /// The inner exception.24        /// </param>25        /// <param name="resourceStr">26        /// This string is message template string27        /// </param>28        /// <param name="errorIdAndResourceId">29        /// This string is the ErrorId passed to the ErrorRecord, and is also30        /// the resourceId used to look up the message template string in31        /// DiscoveryExceptions.txt.32        /// </param>33        /// <param name="messageArgs">34        /// Additional arguments to format into the message.35        /// </param>36        internal CommandNotFoundException(37            string commandName,38            Exception innerException,39            string errorIdAndResourceId,40            string resourceStr,41            params object[] messageArgs)42            : base(BuildMessage(commandName, resourceStr, messageArgs), innerException)43        {44            _commandName = commandName;45            _errorId = errorIdAndResourceId;46        }47 48        /// <summary>49        /// Constructs a CommandNotFoundException.50        /// </summary>51        public CommandNotFoundException() : base() { }52 53        /// <summary>54        /// Constructs a CommandNotFoundException.55        /// </summary>56        /// <param name="message">57        /// The message used in the exception.58        /// </param>59        public CommandNotFoundException(string message) : base(message) { }60 61        /// <summary>62        /// Constructs a CommandNotFoundException.63        /// </summary>64        /// <param name="message">65        /// The message used in the exception.66        /// </param>67        /// <param name="innerException">68        /// An exception that led to this exception.69        /// </param>70        public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { }71 72        /// <summary>73        /// Serialization constructor for class CommandNotFoundException.74        /// </summary>75        /// <param name="info">76        /// serialization information77        /// </param>78        /// <param name="context">79        /// streaming context80        /// </param>81        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]82        protected CommandNotFoundException(SerializationInfo info,83                                        StreamingContext context)84        {85            throw new NotSupportedException();86        }87 88        #region Properties89        /// <summary>90        /// Gets the ErrorRecord information for this exception.91        /// </summary>92        public override ErrorRecord ErrorRecord93        {94            get95            {96                _errorRecord ??= new ErrorRecord(97                    new ParentContainsErrorRecordException(this),98                    _errorId,99                    _errorCategory,100                    _commandName);101 102                return _errorRecord;103            }104        }105 106        private ErrorRecord _errorRecord;107 108        /// <summary>109        /// Gets the name of the command that could not be found.110        /// </summary>111        public string CommandName112        {113            get { return _commandName; }114 115            set { _commandName = value; }116        }117 118        private string _commandName = string.Empty;119 120        #endregion Properties121 122        #region Private123        private readonly string _errorId = "CommandNotFoundException";124        private readonly ErrorCategory _errorCategory = ErrorCategory.ObjectNotFound;125 126        private static string BuildMessage(127            string commandName,128            string resourceStr,129            params object[] messageArgs130            )131        {132            object[] a;133            if (messageArgs != null && messageArgs.Length > 0)134            {135                a = new object[messageArgs.Length + 1];136                a[0] = commandName;137                messageArgs.CopyTo(a, 1);138            }139            else140            {141                a = new object[1];142                a[0] = commandName;143            }144 145            return StringUtil.Format(resourceStr, a);146        }147        #endregion Private148    }149    /// <summary>150    /// Defines the exception thrown when a script's requirements to run specified by the #requires151    /// statements are not met.152    /// </summary>153    public class ScriptRequiresException : RuntimeException154    {155        /// <summary>156        /// Constructs an ScriptRequiresException. Recommended constructor for the class for157        /// #requires -shellId MyShellId.158        /// </summary>159        /// <param name="commandName">160        /// The name of the script containing the #requires statement.161        /// </param>162        /// <param name="requiresShellId">163        /// The ID of the shell that is incompatible with the current shell.164        /// </param>165        /// <param name="requiresShellPath">166        /// The path to the shell specified in the #requires -shellId statement.167        /// </param>168        /// <param name="errorId">169        /// The error id for this exception.170        /// </param>171        internal ScriptRequiresException(172            string commandName,173            string requiresShellId,174            string requiresShellPath,175            string errorId)176            : base(BuildMessage(commandName, requiresShellId, requiresShellPath, true))177        {178            Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException");179            Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException");180            _commandName = commandName;181            _requiresShellId = requiresShellId;182            _requiresShellPath = requiresShellPath;183            this.SetErrorId(errorId);184            this.SetTargetObject(commandName);185            this.SetErrorCategory(ErrorCategory.ResourceUnavailable);186        }187        /// <summary>188        /// Constructs an ScriptRequiresException. Recommended constructor for the class for189        /// #requires -version N.190        /// </summary>191        /// <param name="commandName">192        /// The name of the script containing the #requires statement.193        /// </param>194        /// <param name="requiresPSVersion">195        /// The Msh version that the script requires.196        /// </param>197        /// <param name="currentPSVersion">198        /// The current Msh version199        /// </param>200        /// <param name="errorId">201        /// The error id for this exception.202        /// </param>203        internal ScriptRequiresException(204            string commandName,205            Version requiresPSVersion,206            string currentPSVersion,207            string errorId)208            : base(BuildMessage(commandName, requiresPSVersion.ToString(), currentPSVersion, false))209        {210            Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException");211            Diagnostics.Assert(requiresPSVersion != null, "requiresPSVersion is null or empty when constructing ScriptRequiresException");212            Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException");213            _commandName = commandName;214            _requiresPSVersion = requiresPSVersion;215            this.SetErrorId(errorId);216            this.SetTargetObject(commandName);217            this.SetErrorCategory(ErrorCategory.ResourceUnavailable);218        }219 220        /// <summary>221        /// Constructs an ScriptRequiresException. Recommended constructor for the class for the222        /// #requires -PSSnapin MyPSSnapIn statement.223        /// </summary>224        /// <param name="commandName">225        /// The name of the script containing the #requires statement.226        /// </param>227        /// <param name="missingItems">228        /// The missing snap-ins/modules that the script requires.229        /// </param>230        /// /// <param name="forSnapins">231        /// Indicates whether the error message needs to be constructed for missing snap-ins/ missing modules.232        /// </param>233        /// <param name="errorId">234        /// The error id for this exception.235        /// </param>236        internal ScriptRequiresException(237            string commandName,238            Collection<string> missingItems,239            string errorId,240            bool forSnapins)241            : this(commandName, missingItems, errorId, forSnapins, null)242        {243        }244 245        /// <summary>246        /// Constructs an ScriptRequiresException. Recommended constructor for the class for the247        /// #requires -PSSnapin MyPSSnapIn statement.248        /// </summary>249        /// <param name="commandName">250        /// The name of the script containing the #requires statement.251        /// </param>252        /// <param name="missingItems">253        /// The missing snap-ins/modules that the script requires.254        /// </param>255        /// /// <param name="forSnapins">256        /// Indicates whether the error message needs to be constructed for missing snap-ins/ missing modules.257        /// </param>258        /// <param name="errorId">259        /// The error id for this exception.260        /// </param>261        /// <param name="errorRecord">262        /// The error Record for this exception.263        /// </param>264        internal ScriptRequiresException(265            string commandName,266            Collection<string> missingItems,267            string errorId,268            bool forSnapins,269            ErrorRecord errorRecord)270            : base(BuildMessage(commandName, missingItems, forSnapins), null, errorRecord)271        {272            Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException");273            Diagnostics.Assert(missingItems != null && missingItems.Count > 0, "missingItems is null or empty when constructing ScriptRequiresException");274            Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException");275            _commandName = commandName;276            _missingPSSnapIns = new ReadOnlyCollection<string>(missingItems);277            this.SetErrorId(errorId);278            this.SetTargetObject(commandName);279            this.SetErrorCategory(ErrorCategory.ResourceUnavailable);280        }281 282        /// <summary>283        /// Constructs an ScriptRequiresException. Recommended constructor for the class for284        /// #requires -RunAsAdministrator statement.285        /// </summary>286        /// <param name="commandName">287        /// The name of the script containing the #requires statement.288        /// </param>289        /// <param name="errorId">290        /// The error id for this exception.291        /// </param>292        internal ScriptRequiresException(293            string commandName,294            string errorId)295            : base(BuildMessage(commandName))296        {297            Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException");298            Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException");299            _commandName = commandName;300            this.SetErrorId(errorId);301            this.SetTargetObject(commandName);302            this.SetErrorCategory(ErrorCategory.PermissionDenied);303        }304 305        /// <summary>306        /// Constructs an PSVersionNotCompatibleException.307        /// </summary>308        public ScriptRequiresException() : base() { }309 310        /// <summary>311        /// Constructs an PSVersionNotCompatibleException.312        /// </summary>313        /// <param name="message">314        /// The message used in the exception.315        /// </param>316        public ScriptRequiresException(string message) : base(message) { }317 318        /// <summary>319        /// Constructs an PSVersionNotCompatibleException.320        /// </summary>321        /// <param name="message">322        /// The message used in the exception.323        /// </param>324        /// <param name="innerException">325        /// The exception that led to this exception.326        /// </param>327        public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) { }328 329        #region Serialization330        /// <summary>331        /// Constructs an PSVersionNotCompatibleException using serialized data.332        /// </summary>333        /// <param name="info">334        /// serialization information335        /// </param>336        /// <param name="context">337        /// streaming context338        /// </param>339        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]340        protected ScriptRequiresException(SerializationInfo info,341                                        StreamingContext context)342        {343            throw new NotSupportedException();344        }345 346        #endregion Serialization347 348        #region Properties349 350        /// <summary>351        /// Gets the name of the script that contained the #requires statement.352        /// </summary>353        public string CommandName354        {355            get { return _commandName; }356        }357 358        private readonly string _commandName = string.Empty;359 360        /// <summary>361        /// Gets the PSVersion that the script requires.362        /// </summary>363        public Version RequiresPSVersion364        {365            get { return _requiresPSVersion; }366        }367 368        private readonly Version _requiresPSVersion;369 370        /// <summary>371        /// Gets the missing snap-ins that the script requires.372        /// </summary>373        public ReadOnlyCollection<string> MissingPSSnapIns374        {375            get { return _missingPSSnapIns; }376        }377 378        private readonly ReadOnlyCollection<string> _missingPSSnapIns = new ReadOnlyCollection<string>(Array.Empty<string>());379 380        /// <summary>381        /// Gets or sets the ID of the shell.382        /// </summary>383        public string RequiresShellId384        {385            get { return _requiresShellId; }386        }387 388        private readonly string _requiresShellId;389 390        /// <summary>391        /// Gets or sets the path to the incompatible shell.392        /// </summary>393        public string RequiresShellPath394        {395            get { return _requiresShellPath; }396        }397 398        private readonly string _requiresShellPath;399 400        #endregion Properties401 402        #region Private403 404        private static string BuildMessage(405            string commandName,406            Collection<string> missingItems,407            bool forSnapins)408        {409            StringBuilder sb = new StringBuilder();410            if (missingItems == null)411            {412                throw PSTraceSource.NewArgumentNullException(nameof(missingItems));413            }414 415            foreach (string missingItem in missingItems)416            {417                sb.Append(missingItem).Append(", ");418            }419 420            if (sb.Length > 1)421            {422                sb.Remove(sb.Length - 2, 2);423            }424 425            if (forSnapins)426            {427                return StringUtil.Format(428                    DiscoveryExceptions.RequiresMissingPSSnapIns,429                    commandName,430                    sb.ToString());431            }432            else433            {434                return StringUtil.Format(435                    DiscoveryExceptions.RequiresMissingModules,436                    commandName,437                    sb.ToString());438            }439        }440 441        private static string BuildMessage(442            string commandName,443            string first,444            string second,445            bool forShellId)446        {447            string resourceStr = null;448 449            if (forShellId)450            {451                if (string.IsNullOrEmpty(first))452                {453                    resourceStr = DiscoveryExceptions.RequiresShellIDInvalidForSingleShell;454                }455                else456                {457                    resourceStr = string.IsNullOrEmpty(second)458                            ? DiscoveryExceptions.RequiresInterpreterNotCompatibleNoPath459                            : DiscoveryExceptions.RequiresInterpreterNotCompatible;460                }461            }462            else463            {464                resourceStr = DiscoveryExceptions.RequiresPSVersionNotCompatible;465            }466 467            return StringUtil.Format(resourceStr, commandName, first, second);468        }469 470        private static string BuildMessage(string commandName)471        {472            return StringUtil.Format(DiscoveryExceptions.RequiresElevation, commandName);473        }474 475        #endregion Private476    }477}478