Exemple #1
0
        private PSAuthorizationManager.RunPromptDecision RemoteFilePrompt(
            string path,
            PSHost host)
        {
            if (host == null || host.UI == null)
            {
                return(PSAuthorizationManager.RunPromptDecision.DoNotRun);
            }
            Collection <ChoiceDescription> filePromptChoices = this.GetRemoteFilePromptChoices();
            string resourceString = ResourceManagerCache.GetResourceString("Authenticode", "RemoteFilePromptCaption");
            string message        = ResourceManagerCache.FormatResourceString("Authenticode", "RemoteFilePromptText", (object)path);

            switch (host.UI.PromptForChoice(resourceString, message, filePromptChoices, 0))
            {
            case 0:
                return(PSAuthorizationManager.RunPromptDecision.DoNotRun);

            case 1:
                return(PSAuthorizationManager.RunPromptDecision.RunOnce);

            case 2:
                return(PSAuthorizationManager.RunPromptDecision.Suspend);

            default:
                return(PSAuthorizationManager.RunPromptDecision.DoNotRun);
            }
        }
        private static string GetAndCheckFullFileName(
            string psSnapinName,
            Hashtable fullFileNameHash,
            RunspaceConfiguration runspaceConfiguration,
            string baseFolder,
            string baseFileName,
            Collection <string> independentErrors)
        {
            string path = !Path.IsPathRooted(baseFileName) ? Path.Combine(baseFolder, baseFileName) : baseFileName;

            if (!File.Exists(path))
            {
                string str = ResourceManagerCache.FormatResourceString("TypesXml", "FileNotFound", (object)psSnapinName, (object)path);
                independentErrors.Add(str);
                return((string)null);
            }
            string str1 = (string)fullFileNameHash[(object)path];

            if (str1 != null)
            {
                string str2 = ResourceManagerCache.FormatResourceString("TypesXml", "DuplicateFile", (object)psSnapinName, (object)path, (object)str1);
                independentErrors.Add(str2);
                return((string)null);
            }
            if (!path.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase))
            {
                string str2 = ResourceManagerCache.FormatResourceString("TypesXml", "EntryShouldBeMshXml", (object)psSnapinName, (object)path);
                independentErrors.Add(str2);
                return((string)null);
            }
            fullFileNameHash.Add((object)path, (object)psSnapinName);
            return(path);
        }
Exemple #3
0
 internal static void ThrowIfNotAdministrator()
 {
     if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
     {
         throw new InvalidOperationException(ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", "EDcsRequiresElevation"));
     }
 }
Exemple #4
0
        private bool SetPolicyFromAuthenticodePrompt(
            string path,
            PSHost host,
            ref Exception reason,
            System.Management.Automation.Signature signature)
        {
            bool flag = false;

            switch (this.AuthenticodePrompt(path, signature, host))
            {
            case PSAuthorizationManager.RunPromptDecision.NeverRun:
                this.UntrustPublisher(signature);
                string message1 = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_NeverRun", (object)path);
                reason = (Exception) new UnauthorizedAccessException(message1);
                flag   = false;
                break;

            case PSAuthorizationManager.RunPromptDecision.DoNotRun:
                flag = false;
                string message2 = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DoNotRun", (object)path);
                reason = (Exception) new UnauthorizedAccessException(message2);
                break;

            case PSAuthorizationManager.RunPromptDecision.RunOnce:
                flag = true;
                break;

            case PSAuthorizationManager.RunPromptDecision.AlwaysRun:
                this.TrustPublisher(signature);
                flag = true;
                break;
            }
            return(flag);
        }
 private Collection <PSSnapInInfo> Load(
     string path,
     out PSConsoleLoadException cle)
 {
     using (MshConsoleInfo.tracer.TraceMethod())
     {
         cle = (PSConsoleLoadException)null;
         MshConsoleInfo._mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", (object)path);
         if (string.IsNullOrEmpty(path))
         {
             throw MshConsoleInfo.tracer.NewArgumentNullException(nameof(path));
         }
         if (!Path.IsPathRooted(path))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", (object)path);
             throw MshConsoleInfo.tracer.NewArgumentException(nameof(path), "ConsoleInfoErrorStrings", "PathNotAbsolute", (object)path);
         }
         if (!path.EndsWith(".psc1", StringComparison.OrdinalIgnoreCase))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", (object)path, (object)".psc1");
             throw MshConsoleInfo.tracer.NewArgumentException(nameof(path), "ConsoleInfoErrorStrings", "BadConsoleExtension", (object)"");
         }
         PSConsoleFileElement fromFile = PSConsoleFileElement.CreateFromFile(path);
         if (!Utils.IsVersionSupported(fromFile.MonadVersion))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", (object)fromFile.MonadVersion);
             throw MshConsoleInfo.tracer.NewArgumentException("PSVersion", "ConsoleInfoErrorStrings", "BadMonadVersion", (object)fromFile.MonadVersion, (object)this.psVersion.ToString());
         }
         Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>();
         foreach (string psSnapIn in fromFile.PSSnapIns)
         {
             try
             {
                 this.AddPSSnapIn(psSnapIn);
             }
             catch (PSArgumentException ex)
             {
                 PSSnapInException psSnapInException = new PSSnapInException(psSnapIn, ex.Message, (Exception)ex);
                 MshConsoleInfo._mshsnapinTracer.TraceException((Exception)psSnapInException);
                 exceptions.Add(psSnapInException);
             }
             catch (SecurityException ex)
             {
                 string            message           = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInReadError");
                 PSSnapInException psSnapInException = new PSSnapInException(psSnapIn, message, (Exception)ex);
                 MshConsoleInfo._mshsnapinTracer.TraceException((Exception)psSnapInException);
                 exceptions.Add(psSnapInException);
             }
         }
         if (exceptions.Count > 0)
         {
             cle = new PSConsoleLoadException(this, exceptions);
         }
         this.isDirty = false;
         return(this.externalPSSnapIns);
     }
 }
 internal RunspaceOpenModuleLoadException(
     string moduleName,
     PSDataCollection <ErrorRecord> errors)
     : base(ResourceManagerCache.FormatResourceString("runspace", "ErrorLoadingModulesOnRunspaceOpen", (object)moduleName, errors == null || errors.Count <= 0 || errors[0] == null ? (object) string.Empty : (object)errors[0].ToString()), (Exception)null)
 {
     this._errors = errors;
     this.SetErrorId("ErrorLoadingModulesOnRunspaceOpen");
     this.SetErrorCategory(ErrorCategory.OpenError);
 }
Exemple #7
0
        internal void AddError(
            string typeName,
            int errorLineNumber,
            string resourceId,
            params object[] formatArguments)
        {
            string str = ResourceManagerCache.FormatResourceString("TypesXml", resourceId, formatArguments);

            this.errors.Add(ResourceManagerCache.FormatResourceString("TypesXml", "FileLineTypeError", (object)this.PSSnapinName, (object)this.fileName, (object)errorLineNumber, (object)typeName, (object)str));
        }
        private string PromptUserForFile()
        {
            if (!this.ShouldContinue(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PromptForExportConsole"), (string)null))
            {
                return(string.Empty);
            }
            Dictionary <string, PSObject> dictionary = this.PSHostInternal.UI.Prompt(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "FileNameCaptionForExportConsole", (object)"export-console"), ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "FileNamePromptMessage"), new Collection <FieldDescription>()
            {
                new FieldDescription("Name")
            });

            return(dictionary != null && dictionary["Name"] != null ? dictionary["Name"].BaseObject as string : string.Empty);
        }
Exemple #9
0
 private void ClearHistoryByID()
 {
     using (ClearHistoryCommand._trace.TraceMethod())
     {
         if (this._countParamterSpecified && this.Count < 0)
         {
             this.ThrowTerminatingError(new ErrorRecord((Exception) new ArgumentException(ResourceManagerCache.FormatResourceString("History", "InvalidCountValue")), "ClearHistoryInvalidCountValue", ErrorCategory.InvalidArgument, (object)this._count));
         }
         if (this._id != null)
         {
             if (!this._countParamterSpecified)
             {
                 foreach (long id in this._id)
                 {
                     HistoryInfo entry = this.history.GetEntry(id);
                     if (entry != null && entry.Id == id)
                     {
                         this.history.ClearEntry(entry.Id);
                     }
                     else
                     {
                         this.WriteError(new ErrorRecord((Exception) new ArgumentException(ResourceManagerCache.FormatResourceString("History", "NoHistoryForId", (object)id)), "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, (object)id));
                     }
                 }
             }
             else if (this._id.Length > 1)
             {
                 this.ThrowTerminatingError(new ErrorRecord((Exception) new ArgumentException(ResourceManagerCache.FormatResourceString("History", "NoCountWithMultipleIds")), "GetHistoryNoCountWithMultipleIds", ErrorCategory.InvalidArgument, (object)this._count));
             }
             else
             {
                 this.ClearHistoryEntries((long)this._id[0], this._count, (string)null, this._newest);
             }
         }
         else if (!this._countParamterSpecified)
         {
             if (!this.ShouldProcess(ResourceManagerCache.FormatResourceString("History", "ClearHistoryWarning", (object)"Warning")))
             {
                 return;
             }
             this.ClearHistoryEntries(0L, -1, (string)null, this._newest);
         }
         else
         {
             this.ClearHistoryEntries(0L, this._count, (string)null, this._newest);
         }
     }
 }
        public ModuleSpecification(Hashtable moduleSpecification)
        {
            if (moduleSpecification == null)
            {
                throw new ArgumentNullException(nameof(moduleSpecification));
            }
            StringBuilder stringBuilder = new StringBuilder();

            foreach (DictionaryEntry dictionaryEntry in moduleSpecification)
            {
                if (dictionaryEntry.Key.ToString().Equals("ModuleName", StringComparison.OrdinalIgnoreCase))
                {
                    this.name = (string)LanguagePrimitives.ConvertTo(dictionaryEntry.Value, typeof(string), (IFormatProvider)CultureInfo.InvariantCulture);
                }
                else if (dictionaryEntry.Key.ToString().Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase))
                {
                    this.version = (Version)LanguagePrimitives.ConvertTo(dictionaryEntry.Value, typeof(Version), (IFormatProvider)CultureInfo.InvariantCulture);
                }
                else if (dictionaryEntry.Key.ToString().Equals("GUID", StringComparison.OrdinalIgnoreCase))
                {
                    this.guid = (System.Guid?)LanguagePrimitives.ConvertTo(dictionaryEntry.Value, typeof(System.Guid?), (IFormatProvider)CultureInfo.InvariantCulture);
                }
                else
                {
                    if (stringBuilder.Length > 0)
                    {
                        stringBuilder.Append(", ");
                    }
                    stringBuilder.Append("'");
                    stringBuilder.Append(dictionaryEntry.Key.ToString());
                    stringBuilder.Append("'");
                }
            }
            if (stringBuilder.Length != 0)
            {
                throw new ArgumentException(ResourceManagerCache.FormatResourceString("Modules", "InvalidModuleSpecificationMember", (object)"ModuleName, ModuleVersion, GUID", (object)stringBuilder));
            }
            if (string.IsNullOrEmpty(this.name))
            {
                throw new MissingMemberException(ResourceManagerCache.FormatResourceString("Modules", "RequiredModuleMissingModuleName"));
            }
            if (this.version == (Version)null)
            {
                throw new MissingMemberException(ResourceManagerCache.FormatResourceString("Modules", "RequiredModuleMissingModuleVersion"));
            }
        }
Exemple #11
0
        private PSAuthorizationManager.RunPromptDecision AuthenticodePrompt(
            string path,
            System.Management.Automation.Signature signature,
            PSHost host)
        {
            if (host == null || host.UI == null)
            {
                return(PSAuthorizationManager.RunPromptDecision.DoNotRun);
            }
            PSAuthorizationManager.RunPromptDecision runPromptDecision1 = PSAuthorizationManager.RunPromptDecision.DoNotRun;
            if (signature == null)
            {
                return(runPromptDecision1);
            }
            PSAuthorizationManager.RunPromptDecision runPromptDecision2;
            switch (signature.Status)
            {
            case SignatureStatus.Valid:
                Collection <ChoiceDescription> authenticodePromptChoices = this.GetAuthenticodePromptChoices();
                string resourceString = ResourceManagerCache.GetResourceString("Authenticode", "AuthenticodePromptCaption");
                string message;
                if (signature.SignerCertificate == null)
                {
                    message = ResourceManagerCache.FormatResourceString("Authenticode", "AuthenticodePromptText_UnknownPublisher", (object)path);
                }
                else
                {
                    message = ResourceManagerCache.FormatResourceString("Authenticode", "AuthenticodePromptText", (object)path, (object)signature.SignerCertificate.SubjectName.Name);
                }
                runPromptDecision2 = (PSAuthorizationManager.RunPromptDecision)host.UI.PromptForChoice(resourceString, message, authenticodePromptChoices, 1);
                break;

            case SignatureStatus.UnknownError:
            case SignatureStatus.NotSigned:
            case SignatureStatus.HashMismatch:
            case SignatureStatus.NotSupportedFileFormat:
                runPromptDecision2 = PSAuthorizationManager.RunPromptDecision.DoNotRun;
                break;

            default:
                runPromptDecision2 = PSAuthorizationManager.RunPromptDecision.DoNotRun;
                break;
            }
            return(runPromptDecision2);
        }
        internal static void ThrowExceptionOnError(
            string errorId,
            Collection <string> independentErrors,
            Collection <PSSnapInTypeAndFormatErrors> PSSnapinFilesCollection,
            RunspaceConfigurationCategory category)
        {
            Collection <string> collection = new Collection <string>();

            foreach (string independentError in independentErrors)
            {
                collection.Add(independentError);
            }
            foreach (PSSnapInTypeAndFormatErrors psSnapinFiles in PSSnapinFilesCollection)
            {
                foreach (string error in psSnapinFiles.Errors)
                {
                    collection.Add(error);
                }
            }
            if (collection.Count != 0)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append('\n');
                foreach (string str in collection)
                {
                    stringBuilder.Append(str);
                    stringBuilder.Append('\n');
                }
                string message = "";
                switch (category)
                {
                case RunspaceConfigurationCategory.Types:
                    message = ResourceManagerCache.FormatResourceString("ExtendedTypeSystem", "TypesXmlError", (object)stringBuilder.ToString());
                    break;

                case RunspaceConfigurationCategory.Formats:
                    message = XmlLoadingResourceManager.FormatString("FormatLoadingErrors", (object)stringBuilder.ToString());
                    break;
                }
                RuntimeException runtimeException = new RuntimeException(message);
                runtimeException.SetErrorId(errorId);
                throw runtimeException;
            }
        }
Exemple #13
0
        protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(
            AuthorizationManager authorizationManager,
            PSHost host)
        {
            ExternalScriptInfo externalScriptInfo = new ExternalScriptInfo(this.FilePath, this.FilePath);
            string             scriptContents     = externalScriptInfo.ScriptContents;

            if (authorizationManager != null)
            {
                try
                {
                    authorizationManager.ShouldRunInternal((CommandInfo)externalScriptInfo, CommandOrigin.Internal, host);
                }
                catch (PSSecurityException ex)
                {
                    this.ReportError(ResourceManagerCache.FormatResourceString("TypesXml", "ValidationException", (object)string.Empty, (object)this.FilePath, (object)ex.Message));
                    return((XmlDocument)null);
                }
            }
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            try
            {
                using (StringReader stringReader = new StringReader(scriptContents))
                    xmlDocument.Load((TextReader)stringReader);
            }
            catch (XmlException ex)
            {
                this.ReportError(XmlLoadingResourceManager.FormatString("ErrorInFile", (object)this.FilePath, (object)ex.Message));
                this.ReportTrace("XmlDocument discarded");
                return((XmlDocument)null);
            }
            catch (Exception ex)
            {
                XmlLoaderBase.tracer.TraceException(ex);
                CommandProcessorBase.CheckForSevereException(ex);
                throw;
            }
            this.ReportTrace("XmlDocument loaded OK");
            return(xmlDocument);
        }
Exemple #14
0
        internal static void RestartWinRMService(
            PSCmdlet cmdlet,
            bool isErrorReported,
            bool force,
            bool noServiceRestart)
        {
            if (isErrorReported || noServiceRestart)
            {
                return;
            }
            string resourceString = ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "RestartWSManServiceAction");
            string target         = ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", "RestartWSManServiceTarget", (object)"WinRM");

            if (!force && !cmdlet.ShouldProcess(target, resourceString))
            {
                return;
            }
            cmdlet.WriteVerbose(ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", "RestartWSManServiceMessageV"));
            cmdlet.InvokeCommand.NewScriptBlock("restart-service winrm -force -confirm:$false").InvokeUsingCmdlet((Cmdlet)cmdlet, true, true, (object)AutomationNull.Value, (object)new object[0], (object)AutomationNull.Value);
        }
        private static string GetBaseFolder(
            RunspaceConfiguration runspaceConfiguration,
            Collection <string> independentErrors)
        {
            string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);
            string path;

            if (pathFromRegistry == null)
            {
                path = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
            }
            else
            {
                path = Path.GetDirectoryName(pathFromRegistry);
                if (!Directory.Exists(path))
                {
                    string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string str           = ResourceManagerCache.FormatResourceString("TypesXml", "CannotFindRegistryKeyPath", (object)path, (object)Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), (object)"\\Path", (object)directoryName);
                    independentErrors.Add(str);
                    path = directoryName;
                }
            }
            return(path);
        }
Exemple #16
0
 internal static string FormatString(string resourceId, params object[] args) => ResourceManagerCache.FormatResourceString("FormatAndOut.XmlLoading", resourceId, args);
Exemple #17
0
 private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest)
 {
     using (ClearHistoryCommand._trace.TraceMethod())
     {
         if (cmdline == null)
         {
             if (id > 0L)
             {
                 HistoryInfo entry = this.history.GetEntry(id);
                 if (entry == null || entry.Id != id)
                 {
                     this.WriteError(new ErrorRecord((Exception) new ArgumentException(ResourceManagerCache.FormatResourceString("History", "NoHistoryForId", (object)id)), "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, (object)id));
                 }
                 this.entries = this.history.GetEntries(id, (long)count, newest);
             }
             else
             {
                 this.entries = this.history.GetEntries(0L, (long)count, newest);
             }
         }
         else
         {
             WildcardPattern wildcardpattern = new WildcardPattern(cmdline, WildcardOptions.IgnoreCase);
             if (!this._countParamterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline))
             {
                 count = 0;
             }
             this.entries = this.history.GetEntries(wildcardpattern, (long)count, newest);
         }
         foreach (HistoryInfo entry in this.entries)
         {
             if (entry != null && !entry.Cleared)
             {
                 this.history.ClearEntry(entry.Id);
             }
         }
     }
 }
Exemple #18
0
 private void CoreInvoke(IEnumerable input, bool syncCall)
 {
     using (PipelineBase._trace.TraceMethod())
     {
         lock (this.SyncRoot)
         {
             if (this._disposed)
             {
                 throw PipelineBase._trace.NewObjectDisposedException("pipeline");
             }
             if (this.Commands == null || this.Commands.Count == 0)
             {
                 throw PipelineBase._trace.NewInvalidOperationException("Runspace", "NoCommandInPipeline");
             }
             if (this.PipelineState != PipelineState.NotStarted)
             {
                 InvalidPipelineStateException pipelineStateException = new InvalidPipelineStateException(ResourceManagerCache.FormatResourceString("Runspace", "PipelineReInvokeNotAllowed"), this.PipelineState, PipelineState.NotStarted);
                 PipelineBase._trace.TraceException((Exception)pipelineStateException);
                 throw pipelineStateException;
             }
             if (syncCall)
             {
                 if (input != null)
                 {
                     foreach (object obj in input)
                     {
                         this._inputStream.Write(obj);
                     }
                 }
                 this._inputStream.Close();
             }
             this._syncInvokeCall        = syncCall;
             this._pipelineFinishedEvent = new ManualResetEvent(false);
             this.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
             this.SetPipelineState(PipelineState.Running);
         }
         try
         {
             this.StartPipelineExecution();
         }
         catch (Exception ex)
         {
             CommandProcessorBase.CheckForSevereException(ex);
             PipelineBase._trace.TraceException(ex);
             this.RunspaceBase.RemoveFromRunningPipelineList(this);
             this.SetPipelineState(PipelineState.Failed, ex);
             throw;
         }
     }
 }
Exemple #19
0
        private Collection <int> EmulatePromptForMultipleChoice(
            string caption,
            string message,
            Collection <ChoiceDescription> choices,
            IEnumerable <int> defaultChoices)
        {
            if (choices == null)
            {
                throw InternalHostUserInterface.tracer.NewArgumentNullException(nameof(choices));
            }
            if (choices.Count == 0)
            {
                throw InternalHostUserInterface.tracer.NewArgumentException(nameof(choices), "InternalHostUserInterfaceStrings", "EmptyChoicesError", (object)nameof(choices));
            }
            Dictionary <int, bool> dictionary = new Dictionary <int, bool>();

            if (defaultChoices != null)
            {
                foreach (int defaultChoice in defaultChoices)
                {
                    if (defaultChoice < 0 || defaultChoice >= choices.Count)
                    {
                        throw InternalHostUserInterface.tracer.NewArgumentOutOfRangeException("defaultChoice", (object)defaultChoice, "InternalHostUserInterfaceStrings", "InvalidDefaultChoiceForMultipleSelection", (object)"defaultChoice", (object)nameof(choices), (object)defaultChoice);
                    }
                    if (!dictionary.ContainsKey(defaultChoice))
                    {
                        dictionary.Add(defaultChoice, true);
                    }
                }
            }
            StringBuilder stringBuilder1 = new StringBuilder();
            char          ch             = '\n';

            if (!string.IsNullOrEmpty(caption))
            {
                stringBuilder1.Append(caption);
                stringBuilder1.Append(ch);
            }
            if (!string.IsNullOrEmpty(message))
            {
                stringBuilder1.Append(message);
                stringBuilder1.Append(ch);
            }
            string[,] hotkeysAndPlainLabels = (string[, ])null;
            HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels);
            string format = "[{0}] {1}  ";

            for (int index = 0; index < hotkeysAndPlainLabels.GetLength(1); ++index)
            {
                string str = string.Format((IFormatProvider)CultureInfo.InvariantCulture, format, (object)hotkeysAndPlainLabels[0, index], (object)hotkeysAndPlainLabels[1, index]);
                stringBuilder1.Append(str);
                stringBuilder1.Append(ch);
            }
            string str1 = "";

            if (dictionary.Count > 0)
            {
                string        str2           = "";
                StringBuilder stringBuilder2 = new StringBuilder();
                foreach (int key in dictionary.Keys)
                {
                    string str3 = hotkeysAndPlainLabels[0, key];
                    if (string.IsNullOrEmpty(str3))
                    {
                        str3 = hotkeysAndPlainLabels[1, key];
                    }
                    stringBuilder2.Append(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0}{1}", (object)str2, (object)str3));
                    str2 = ",";
                }
                string str4 = stringBuilder2.ToString();
                if (dictionary.Count == 1)
                {
                    str1 = ResourceManagerCache.FormatResourceString("InternalHostUserInterfaceStrings", "DefaultChoice", (object)str4);
                }
                else
                {
                    str1 = ResourceManagerCache.FormatResourceString("InternalHostUserInterfaceStrings", "DefaultChoicesForMultipleChoices", (object)str4);
                }
            }
            string           str5       = stringBuilder1.ToString() + str1 + (object)ch;
            Collection <int> collection = new Collection <int>();
            int num = 0;

            while (true)
            {
                string str2 = ResourceManagerCache.FormatResourceString("InternalHostUserInterfaceStrings", "ChoiceMessage", (object)num);
                this.externalUI.WriteLine(str5 + str2);
                string str3 = this.externalUI.ReadLine();
                if (str3.Length != 0)
                {
                    int choicePicked = HostUIHelperMethods.DetermineChoicePicked(str3.Trim(), choices, hotkeysAndPlainLabels);
                    if (choicePicked >= 0)
                    {
                        collection.Add(choicePicked);
                        ++num;
                    }
                    str5 = "";
                }
                else
                {
                    break;
                }
            }
            if (collection.Count == 0 && dictionary.Keys.Count >= 0)
            {
                foreach (int key in dictionary.Keys)
                {
                    collection.Add(key);
                }
            }
            return(collection);
        }
Exemple #20
0
 public PromptingException()
     : base(ResourceManagerCache.FormatResourceString("HostInterfaceExceptionsStrings", "DefaultCtorMessageTemplate", (object) typeof(PromptingException).FullName))
     => this.SetDefaultErrorRecord();
Exemple #21
0
 internal static PSConsoleFileElement CreateFromFile(string path)
 {
     using (PSConsoleFileElement.tracer.TraceMethod())
     {
         PSConsoleFileElement._mshsnapinTracer.WriteLine("Loading console info from file {0}.", (object)path);
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.Load(path);
         if (xmlDocument["PSConsoleFile"] == null)
         {
             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", (object)path, (object)"PSConsoleFile");
             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MonadConsoleNotFound", (object)path));
         }
         if (xmlDocument["PSConsoleFile"]["PSVersion"] == null || string.IsNullOrEmpty(xmlDocument["PSConsoleFile"]["PSVersion"].InnerText))
         {
             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", (object)path, (object)"PSVersion");
             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MonadVersionNotFound", (object)path));
         }
         XmlElement xmlElement1 = xmlDocument["PSConsoleFile"];
         if (xmlElement1.HasAttribute("ConsoleSchemaVersion"))
         {
             if (!xmlElement1.GetAttribute("ConsoleSchemaVersion").Equals("1.0", StringComparison.OrdinalIgnoreCase))
             {
                 string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadConsoleVersion", (object)path), (object)"1.0");
                 PSConsoleFileElement._mshsnapinTracer.TraceError(str);
                 throw new XmlException(str);
             }
             PSConsoleFileElement consoleFileElement = new PSConsoleFileElement(xmlDocument["PSConsoleFile"]["PSVersion"].InnerText.Trim());
             bool flag1 = false;
             bool flag2 = false;
             for (XmlNode xmlNode1 = xmlDocument["PSConsoleFile"].FirstChild; xmlNode1 != null; xmlNode1 = xmlNode1.NextSibling)
             {
                 if (xmlNode1.NodeType != XmlNodeType.Comment)
                 {
                     if (!(xmlNode1 is XmlElement xmlElement))
                     {
                         throw new XmlException(ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "BadXMLFormat"));
                     }
                     if (xmlElement.Name == "PSVersion")
                     {
                         if (flag2)
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", (object)path);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MultipleMshSnapinsElementNotSupported", (object)"PSVersion"));
                         }
                         flag2 = true;
                     }
                     else
                     {
                         if (xmlElement.Name != "PSSnapIns")
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Tag {0} is not supported in console file", (object)xmlElement.Name);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadXMLElementFound", (object)xmlElement.Name, (object)"PSConsoleFile", (object)"PSVersion", (object)"PSSnapIns"));
                         }
                         if (flag1)
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", (object)path);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MultipleMshSnapinsElementNotSupported", (object)"PSSnapIns"));
                         }
                         flag1 = true;
                         for (XmlNode xmlNode2 = xmlElement.FirstChild; xmlNode2 != null; xmlNode2 = xmlNode2.NextSibling)
                         {
                             if (!(xmlNode2 is XmlElement xmlElement) || xmlElement.Name != "PSSnapIn")
                             {
                                 throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInNotFound", (object)xmlNode2.Name));
                             }
                             string attribute = xmlElement.GetAttribute("Name");
                             if (string.IsNullOrEmpty(attribute))
                             {
                                 throw new XmlException(ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "IDNotFound"));
                             }
                             consoleFileElement.mshsnapins.Add(attribute);
                             PSConsoleFileElement._mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", (object)attribute, (object)path);
                         }
                     }
                 }
             }
             return(consoleFileElement);
         }
         PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", (object)path);
         throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadConsoleVersion", (object)path));
     }
 }
Exemple #22
0
        private HistoryInfo GetHistoryInfoObject(PSObject mshObject)
        {
            using (AddHistoryCommand._trace.TraceMethod())
            {
                if (mshObject != null && AddHistoryCommand.GetPropertyValue(mshObject, "CommandLine") is string propertyValue)
                {
                    object propertyValue1 = AddHistoryCommand.GetPropertyValue(mshObject, "ExecutionStatus");
                    switch (propertyValue1)
                    {
                    case PipelineState status:
label_7:
                        object propertyValue2 = AddHistoryCommand.GetPropertyValue(mshObject, "StartExecutionTime");
                        switch (propertyValue2)
                        {
                        case DateTime startTime:
label_10:
                            object propertyValue3 = AddHistoryCommand.GetPropertyValue(mshObject, "EndExecutionTime");
                            switch (propertyValue3)
                            {
                            case DateTime endTime:
label_13:
                                return(new HistoryInfo(0L, propertyValue, status, startTime, endTime));

                            case string _:
                                try
                                {
                                    endTime = DateTime.Parse((string)propertyValue3, (IFormatProvider)CultureInfo.CurrentCulture);
                                    goto label_13;
                                }
                                catch (FormatException ex)
                                {
                                    AddHistoryCommand._trace.TraceException((Exception)ex);
                                    break;
                                }
                            }
                            break;

                        case string _:
                            try
                            {
                                startTime = DateTime.Parse((string)propertyValue2, (IFormatProvider)CultureInfo.CurrentCulture);
                                goto label_10;
                            }
                            catch (FormatException ex)
                            {
                                AddHistoryCommand._trace.TraceException((Exception)ex);
                                break;
                            }
                        }
                        break;

                    case PSObject _:
                        object baseObject = (propertyValue1 as PSObject).BaseObject;
                        if (baseObject is int)
                        {
                            status = (PipelineState)baseObject;
                            switch (status)
                            {
                            case PipelineState.NotStarted:
                            case PipelineState.Running:
                            case PipelineState.Stopping:
                            case PipelineState.Stopped:
                            case PipelineState.Completed:
                            case PipelineState.Failed:
                                goto label_7;
                            }
                        }
                        else
                        {
                            break;
                        }
                        break;

                    case string _:
                        try
                        {
                            status = (PipelineState)Enum.Parse(typeof(PipelineState), (string)propertyValue1);
                            goto label_7;
                        }
                        catch (ArgumentException ex)
                        {
                            AddHistoryCommand._trace.TraceException((Exception)ex);
                            break;
                        }
                    }
                }
                this.WriteError(new ErrorRecord((Exception) new InvalidDataException(ResourceManagerCache.FormatResourceString("History", "AddHistoryInvalidInput")), "AddHistoryInvalidInput", ErrorCategory.InvalidData, (object)mshObject));
                return((HistoryInfo)null);
            }
        }
 internal FormatTableLoadException(Collection <string> loadErrors)
     : base(ResourceManagerCache.FormatResourceString("FormatAndOut.XmlLoading", "FormattableLoadErrors"))
 {
     this.errors = loadErrors;
     this.SetDefaultErrorRecord();
 }
 internal TypeTableLoadException(Collection <string> loadErrors)
     : base(ResourceManagerCache.FormatResourceString("TypesXml", "TypeTableLoadErrors"))
 {
     this.errors = loadErrors;
     this.SetDefaultErrorRecord();
 }
Exemple #25
0
 internal void AddError(string resourceId, params object[] formatArguments) => this.errors.Add(ResourceManagerCache.FormatResourceString("TypesXml", "FileError", (object)this.PSSnapinName, (object)this.fileName, (object)ResourceManagerCache.FormatResourceString("TypesXml", resourceId, formatArguments)));
Exemple #26
0
        private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
        {
            bool flag1 = false;

            reason = (Exception)null;
            string path = script.Path;

            if (path.IndexOf('\\') < 0)
            {
                throw PSAuthorizationManager.tracer.NewArgumentException("path");
            }
            FileInfo fileInfo = path.LastIndexOf('\\') != path.Length - 1 ? new FileInfo(path) : throw PSAuthorizationManager.tracer.NewArgumentException("path");

            if (!fileInfo.Exists)
            {
                return(false);
            }
            if (!PSAuthorizationManager.IsSupportedExtension(fileInfo.Extension) || this.IsProductBinary(path))
            {
                return(true);
            }
            this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId);
            if (this.executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }
            if (SecuritySupport.GetSaferPolicy(path) == SaferPolicy.Disallowed)
            {
                string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DisallowedBySafer", (object)path);
                reason = (Exception) new UnauthorizedAccessException(message);
                return(false);
            }
            if (this.executionPolicy == ExecutionPolicy.Unrestricted)
            {
                if (!this.IsLocalFile(fileInfo.FullName))
                {
                    if (string.IsNullOrEmpty(script.ScriptContents))
                    {
                        string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path);
                        reason = (Exception) new UnauthorizedAccessException(message);
                        return(false);
                    }
                    System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                    if (withEncodingRetry.Status == SignatureStatus.Valid && this.IsTrustedPublisher(withEncodingRetry, path))
                    {
                        flag1 = true;
                    }
                    if (!flag1)
                    {
                        PSAuthorizationManager.RunPromptDecision runPromptDecision;
                        do
                        {
                            runPromptDecision = this.RemoteFilePrompt(path, host);
                            if (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend)
                            {
                                host.EnterNestedPrompt();
                            }
                        }while (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend);
                        switch (runPromptDecision - 1)
                        {
                        case PSAuthorizationManager.RunPromptDecision.DoNotRun:
                            flag1 = true;
                            break;

                        default:
                            flag1 = false;
                            string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DoNotRun", (object)path);
                            reason = (Exception) new UnauthorizedAccessException(message);
                            break;
                        }
                    }
                }
                else
                {
                    flag1 = true;
                }
            }
            else if (this.IsLocalFile(fileInfo.FullName) && this.executionPolicy == ExecutionPolicy.RemoteSigned)
            {
                flag1 = true;
            }
            else if (this.executionPolicy == ExecutionPolicy.AllSigned || this.executionPolicy == ExecutionPolicy.RemoteSigned)
            {
                if (string.IsNullOrEmpty(script.ScriptContents))
                {
                    string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path);
                    reason = (Exception) new UnauthorizedAccessException(message);
                    return(false);
                }
                System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                if (withEncodingRetry.Status == SignatureStatus.Valid)
                {
                    flag1 = this.IsTrustedPublisher(withEncodingRetry, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry);
                }
                else
                {
                    flag1 = false;
                    if (withEncodingRetry.Status == SignatureStatus.NotTrusted)
                    {
                        reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_NotTrusted", (object)path, (object)withEncodingRetry.SignerCertificate.SubjectName.Name));
                    }
                    else
                    {
                        reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_Unknown", (object)path, (object)withEncodingRetry.StatusMessage));
                    }
                }
            }
            else
            {
                flag1 = false;
                bool flag2 = false;
                if (string.Equals(fileInfo.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
                {
                    string[] strArray = new string[2]
                    {
                        Environment.GetFolderPath(Environment.SpecialFolder.System),
                        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
                    };
                    foreach (string str in strArray)
                    {
                        if (fileInfo.FullName.StartsWith(str, StringComparison.OrdinalIgnoreCase))
                        {
                            flag1 = true;
                        }
                    }
                    if (!flag1)
                    {
                        System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                        if (withEncodingRetry.Status == SignatureStatus.Valid)
                        {
                            if (this.IsTrustedPublisher(withEncodingRetry, path))
                            {
                                flag1 = true;
                            }
                            else
                            {
                                flag1 = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry);
                                flag2 = true;
                            }
                        }
                    }
                }
                if (!flag1 && !flag2)
                {
                    reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_RestrictedMode", (object)path));
                }
            }
            return(flag1);
        }
Exemple #27
0
        internal static Assembly LoadPSSnapInAssembly(
            PSSnapInInfo psSnapInInfo,
            out Dictionary <string, SessionStateCmdletEntry> cmdlets,
            out Dictionary <string, SessionStateProviderEntry> providers)
        {
            Assembly assembly1 = (Assembly)null;

            cmdlets   = (Dictionary <string, SessionStateCmdletEntry>)null;
            providers = (Dictionary <string, SessionStateProviderEntry>)null;
            PSSnapInHelpers._PSSnapInTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", (object)psSnapInInfo.AssemblyName);
            try
            {
                assembly1 = Assembly.Load(psSnapInInfo.AssemblyName);
            }
            catch (FileLoadException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            catch (BadImageFormatException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            if (assembly1 != null)
            {
                return(assembly1);
            }
            PSSnapInHelpers._PSSnapInTracer.WriteLine("Loading assembly from path: {0}", (object)psSnapInInfo.AssemblyName);
            try
            {
                Assembly assembly2 = Assembly.ReflectionOnlyLoadFrom(psSnapInInfo.AbsoluteModulePath);
                if (assembly2 == null)
                {
                    return((Assembly)null);
                }
                if (!string.Equals(assembly2.FullName, psSnapInInfo.AssemblyName, StringComparison.OrdinalIgnoreCase))
                {
                    string str = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInAssemblyNameMismatch", (object)psSnapInInfo.AbsoluteModulePath, (object)psSnapInInfo.AssemblyName);
                    PSSnapInHelpers._PSSnapInTracer.TraceError(str);
                    throw new PSSnapInException(psSnapInInfo.Name, str);
                }
                return(Assembly.LoadFrom(psSnapInInfo.AbsoluteModulePath));
            }
            catch (FileLoadException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
            catch (BadImageFormatException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
        }
 internal static string FormatResourceString(PSRemotingErrorId messageId, params object[] args) => ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", messageId.ToString(), args);
Exemple #29
0
 internal static void AnalyzePSSnapInAssembly(
     Assembly assembly,
     string name,
     PSSnapInInfo psSnapInInfo,
     out Dictionary <string, SessionStateCmdletEntry> cmdlets,
     out Dictionary <string, SessionStateProviderEntry> providers)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException(nameof(assembly));
     }
     if (PSSnapInHelpers._cmdletCache != null && PSSnapInHelpers._providerCache != null && (PSSnapInHelpers._cmdletCache.ContainsKey(assembly) && PSSnapInHelpers._providerCache.ContainsKey(assembly)))
     {
         cmdlets   = PSSnapInHelpers._cmdletCache[assembly];
         providers = PSSnapInHelpers._providerCache[assembly];
     }
     else
     {
         cmdlets   = (Dictionary <string, SessionStateCmdletEntry>)null;
         providers = (Dictionary <string, SessionStateProviderEntry>)null;
         PSSnapInHelpers._PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", (object)assembly.Location);
         string helpFile = PSSnapInHelpers.GetHelpFile(assembly.Location);
         Type[] types;
         try
         {
             types = assembly.GetTypes();
         }
         catch (ReflectionTypeLoadException ex)
         {
             string str = ex.Message + "\nLoader Exceptions: \n";
             if (ex.LoaderExceptions != null)
             {
                 foreach (Exception loaderException in ex.LoaderExceptions)
                 {
                     str = str + "\n" + loaderException.Message;
                 }
             }
             PSSnapInHelpers._PSSnapInTracer.TraceError(str);
             throw new PSSnapInException(name, str);
         }
         foreach (Type type in types)
         {
             if ((type.IsPublic || type.IsNestedPublic) && !type.IsAbstract)
             {
                 object[] customAttributes = type.GetCustomAttributes(false);
                 string   str1             = (string)null;
                 string   str2             = (string)null;
                 foreach (object obj in customAttributes)
                 {
                     if (obj.GetType() == typeof(CmdletAttribute))
                     {
                         str1 = PSSnapInHelpers.GetCmdletName(obj as CmdletAttribute);
                         break;
                     }
                     if (obj.GetType() == typeof(CmdletProviderAttribute))
                     {
                         str2 = PSSnapInHelpers.GetProviderName(obj as CmdletProviderAttribute);
                         break;
                     }
                 }
                 if (!string.IsNullOrEmpty(str1))
                 {
                     if (PSSnapInHelpers.IsCmdletClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (cmdlets != null && cmdlets.ContainsKey(str1))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateCmdlets", (object)str1, (object)name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(name, str3);
                         }
                         SessionStateCmdletEntry stateCmdletEntry = new SessionStateCmdletEntry(str1, type, helpFile);
                         if (psSnapInInfo != null)
                         {
                             stateCmdletEntry.SetPSSnapIn(psSnapInInfo);
                         }
                         if (cmdlets == null)
                         {
                             cmdlets = new Dictionary <string, SessionStateCmdletEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         cmdlets.Add(str1, stateCmdletEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", (object)str1, (object)type.FullName);
                         continue;
                     }
                     PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid cmdlet because it doesn't derive from the Cmdlet type or it doesn't have a default constructor.", (object)str1);
                 }
                 if (!string.IsNullOrEmpty(str2))
                 {
                     if (PSSnapInHelpers.IsProviderClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (providers != null && providers.ContainsKey(str2))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateProviders", (object)str2, (object)psSnapInInfo.Name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(psSnapInInfo.Name, str3);
                         }
                         SessionStateProviderEntry stateProviderEntry = new SessionStateProviderEntry(str2, type, helpFile);
                         stateProviderEntry.SetPSSnapIn(psSnapInInfo);
                         if (providers == null)
                         {
                             providers = new Dictionary <string, SessionStateProviderEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         providers.Add(str2, stateProviderEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", (object)str2, (object)type.FullName);
                     }
                     else
                     {
                         PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid provider because it doesn't derive from the provider type or it doesn't have a default constructor.", (object)str2);
                     }
                 }
             }
         }
         lock (PSSnapInHelpers._syncObject)
         {
             if (cmdlets != null)
             {
                 if (PSSnapInHelpers._cmdletCache == null)
                 {
                     PSSnapInHelpers._cmdletCache = new Dictionary <Assembly, Dictionary <string, SessionStateCmdletEntry> >();
                 }
                 PSSnapInHelpers._cmdletCache[assembly] = cmdlets;
             }
             if (providers == null)
             {
                 return;
             }
             if (PSSnapInHelpers._providerCache == null)
             {
                 PSSnapInHelpers._providerCache = new Dictionary <Assembly, Dictionary <string, SessionStateProviderEntry> >();
             }
             PSSnapInHelpers._providerCache[assembly] = providers;
         }
     }
 }
Exemple #30
0
 internal string GetMessage(PSRemotingErrorId errorId, params object[] args) => args == null?ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", errorId.ToString()) : ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", errorId.ToString(), args);