/// <summary> /// Checks if the specified version of PowerShell is installed. /// </summary> /// <param name="version"></param> internal static void CheckIfPowerShellVersionIsInstalled(Version version) { // Check if PowerShell 2.0 is installed if (version != null && version.Major == 2) { #if CORECLR // PowerShell 2.0 is not available for CoreCLR throw new ArgumentException( PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.PowerShellNotInstalled, version, "PSVersion")); #else // Because of app-compat issues, in Win8, we will have PS 2.0 installed by default but not .NET 2.0 // In such a case, it is not enough if we check just PowerShell registry keys. We also need to check if .NET 2.0 is installed. try { RegistryKey engineKey = PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key); // Also check for .NET 2.0 installation if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0)) { throw new ArgumentException( PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NetFrameWorkV2NotInstalled)); } } catch (PSArgumentException) { throw new ArgumentException( PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.PowerShellNotInstalled, version, "PSVersion")); } #endif } }
private CommandInfo GetOutDefaultCommandInfo(string moduleName, ref List <ErrorRecord> errors) { CommandInfo info = null; Assembly executingAssembly = Assembly.GetExecutingAssembly(); byte[] publicKeyToken = executingAssembly.GetName().GetPublicKeyToken(); if (publicKeyToken.Length == 0) { PSArgumentException exception = PSTraceSource.NewArgumentException("PublicKeyToken", "MshSnapinInfo", "PublicKeyTokenAccessFailed", new object[0]); errors.Add(new ErrorRecord(exception, "PublicKeyTokenAccessFailed", ErrorCategory.InvalidOperation, null)); return(info); } string str = PSSnapInReader.ConvertByteArrayToString(publicKeyToken); string str2 = "neutral"; string str3 = "MSIL"; if (LoadAssemblyHelper(string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", new object[] { "Microsoft.PowerShell.Commands.Utility", executingAssembly.GetName().Version, str2, str, str3 }), ref errors) != null) { Exception exception2; Type implementingType = LanguagePrimitives.ConvertStringToType("Microsoft.PowerShell.Commands.OutDefaultCommand", out exception2); if (exception2 != null) { errors.Add(new ErrorRecord(exception2, "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidType, null)); } if (implementingType != null) { return(new CmdletInfo("Out-Default", implementingType, null, null, this._engine.Context)); } errors.Add(new ErrorRecord(PSTraceSource.NewInvalidOperationException("RunspaceStrings", "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", new object[] { moduleName }), "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidOperation, null)); } return(info); }
/// <summary> /// Constructs a <see cref="System.Management.Automation.Runspaces.MshConsoleInfo"/> object for the /// current Monad version which is already started. /// </summary> /// <exception cref="PSSnapInException"> /// One or more default mshsnapins cannot be loaded because the /// registry is not populated correctly. /// </exception> internal static MshConsoleInfo CreateDefaultConfiguration() { // Steps: // 1. Get the current Monad Version // 2. Create MshConsoleInfo object. // 3. Read default mshsnapins. MshConsoleInfo consoleInfo = new MshConsoleInfo(PSVersionInfo.PSVersion); try { consoleInfo._defaultPSSnapIns = PSSnapInReader.ReadEnginePSSnapIns(); } catch (PSArgumentException ae) { string message = ConsoleInfoErrorStrings.CannotLoadDefaults; // If we were unable to load default mshsnapins throw PSSnapInException s_mshsnapinTracer.TraceError(message); throw new PSSnapInException(message, ae); } catch (System.Security.SecurityException se) { string message = ConsoleInfoErrorStrings.CannotLoadDefaults; // If we were unable to load default mshsnapins throw PSSnapInException s_mshsnapinTracer.TraceError(message); throw new PSSnapInException(message, se); } return(consoleInfo); }
public void TestReadCoreEngineSnapIn() { Skip.IfNot(Platform.IsWindows); PSSnapInInfo pSSnapInInfo = PSSnapInReader.ReadCoreEngineSnapIn(); Assert.Contains("PublicKeyToken=31bf3856ad364e35", pSSnapInInfo.AssemblyName); }
internal PSSnapInInfo AddPSSnapIn(string mshSnapInID) { if (string.IsNullOrEmpty(mshSnapInID)) { PSTraceSource.NewArgumentNullException("mshSnapInID"); } if (IsDefaultPSSnapIn(mshSnapInID, this.defaultPSSnapIns)) { _mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", new object[] { mshSnapInID }); throw PSTraceSource.NewArgumentException("mshSnapInID", "ConsoleInfoErrorStrings", "CannotLoadDefault", new object[0]); } if (this.IsActiveExternalPSSnapIn(mshSnapInID)) { _mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", new object[] { mshSnapInID }); throw PSTraceSource.NewArgumentException("mshSnapInID", "ConsoleInfoErrorStrings", "PSSnapInAlreadyExists", new object[] { mshSnapInID }); } PSSnapInInfo item = PSSnapInReader.Read(this.MajorVersion, mshSnapInID); if (!Utils.IsPSVersionSupported(item.PSVersion.ToString())) { _mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", new object[] { mshSnapInID }); throw PSTraceSource.NewArgumentException("mshSnapInID", "ConsoleInfoErrorStrings", "AddPSSnapInBadMonadVersion", new object[] { item.PSVersion.ToString(), this.psVersion.ToString() }); } this.externalPSSnapIns.Add(item); _mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", new object[] { mshSnapInID }); this.isDirty = true; return(item); }
internal Collection <PSSnapInInfo> GetPSSnapIn(string pattern, bool searchRegistry) { bool flag = WildcardPattern.ContainsWildcardCharacters(pattern); if (!flag) { PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern); } Collection <PSSnapInInfo> collection = searchRegistry ? PSSnapInReader.ReadAll() : this.PSSnapIns; Collection <PSSnapInInfo> collection2 = new Collection <PSSnapInInfo>(); if (collection != null) { if (!flag) { foreach (PSSnapInInfo info in collection) { if (string.Equals(info.Name, pattern, StringComparison.OrdinalIgnoreCase)) { collection2.Add(info); } } return(collection2); } WildcardPattern pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); foreach (PSSnapInInfo info2 in collection) { if (pattern2.IsMatch(info2.Name)) { collection2.Add(info2); } } } return(collection2); }
public void TestReadRegistryInfo() { Version someVersion = null; string someString = null; PSSnapInReader.ReadRegistryInfo(out someVersion, out someString, out someString, out someString, out someString, out someVersion); }
internal PSSnapInInfo AddPSSnapIn(string mshSnapInID) { using (MshConsoleInfo.tracer.TraceMethod()) { if (string.IsNullOrEmpty(mshSnapInID)) { MshConsoleInfo.tracer.NewArgumentNullException(nameof(mshSnapInID)); } if (this.IsDefaultPSSnapIn(mshSnapInID)) { MshConsoleInfo._mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", (object)mshSnapInID); throw MshConsoleInfo.tracer.NewArgumentException(nameof(mshSnapInID), "ConsoleInfoErrorStrings", "CannotLoadDefault"); } if (this.IsActiveExternalPSSnapIn(mshSnapInID)) { MshConsoleInfo._mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", (object)mshSnapInID); throw MshConsoleInfo.tracer.NewArgumentException(nameof(mshSnapInID), "ConsoleInfoErrorStrings", "PSSnapInAlreadyExists", (object)mshSnapInID); } PSSnapInInfo psSnapInInfo = PSSnapInReader.Read(this.MajorVersion, mshSnapInID); if (!Utils.IsVersionSupported(psSnapInInfo.PSVersion.ToString())) { MshConsoleInfo._mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", (object)mshSnapInID); throw MshConsoleInfo.tracer.NewArgumentException(nameof(mshSnapInID), "ConsoleInfoErrorStrings", "AddPSSnapInBadMonadVersion", (object)psSnapInInfo.PSVersion.ToString(), (object)this.psVersion.ToString()); } this.externalPSSnapIns.Add(psSnapInInfo); MshConsoleInfo._mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", (object)mshSnapInID); this.isDirty = true; return(psSnapInInfo); } }
public void TestReadRegistryInfo() { Skip.IfNot(Platform.IsWindows); Version someVersion = null; string someString = null; PSSnapInReader.ReadRegistryInfo(out someVersion, out someString, out someString, out someString, out someString, out someVersion); }
/// <summary> /// Searches for mshsnapin in either current console or registry as determined /// by <paramref name="searchRegistry"/>. /// </summary> /// <param name="pattern"> /// Id/WildcardPattern of the mshsnapin to search for. This can contain wildcard characters as /// represented by WildCardPattern. /// </param> /// <param name="searchRegistry"> /// A boolean which determines whether to search in the current console or registry. /// </param> /// <returns>A collection of mshsnapininfo objects.</returns> /// <exception cref="PSArgumentException"> /// 1.Unable to read registry entries for mshsnapins. /// 2.Pattern specified is not valid. If pattern doesnt contain /// wildcard characters, this function checks for the validity /// of the mshsnapin name. /// </exception> /// <exception cref="System.Security.SecurityException"> /// Caller doesn't have permission to read keys. /// </exception> internal Collection <PSSnapInInfo> GetPSSnapIn(string pattern, bool searchRegistry) { // We want to improve the search speed by noting whether we want // to perform wildcard search. bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern); if (!doWildCardSearch) { // Verify PSSnapInID.. // This will throw if it not a valid name PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern); } // Build the list to search..If searchRegistry is true get all mshsnapins available // from the registry, otherwise get mshsnapins from the current console. Collection <PSSnapInInfo> listToSearch = searchRegistry ? PSSnapInReader.ReadAll() : PSSnapIns; // Create a list to return.. Collection <PSSnapInInfo> listToReturn = new Collection <PSSnapInInfo>(); // If there is nothing to search.. if (listToSearch == null) { return(listToReturn); } if (!doWildCardSearch) { // We are not doing wildcard search.. foreach (PSSnapInInfo mshSnapIn in listToSearch) { if (string.Equals(mshSnapIn.Name, pattern, StringComparison.OrdinalIgnoreCase)) { listToReturn.Add(mshSnapIn); } } } else { WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); // We are doing WildCard search foreach (PSSnapInInfo mshSnapIn in listToSearch) { if (matcher.IsMatch(mshSnapIn.Name)) { listToReturn.Add(mshSnapIn); } } } // return whatever we found..may be 0.. return(listToReturn); }
protected internal Collection <PSSnapInInfo> GetSnapIns(string pattern) { if (this.Runspace != null) { if (pattern != null) { return(this.Runspace.ConsoleInfo.GetPSSnapIn(pattern, this._shouldGetAll)); } return(this.Runspace.ConsoleInfo.PSSnapIns); } WildcardPattern pattern2 = null; if (!string.IsNullOrEmpty(pattern)) { if (!WildcardPattern.ContainsWildcardCharacters(pattern)) { PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern); } pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); } Collection <PSSnapInInfo> collection = new Collection <PSSnapInInfo>(); if (this._shouldGetAll) { foreach (PSSnapInInfo info in PSSnapInReader.ReadAll()) { if ((pattern2 == null) || pattern2.IsMatch(info.Name)) { collection.Add(info); } } return(collection); } List <CmdletInfo> cmdlets = base.InvokeCommand.GetCmdlets(); Dictionary <PSSnapInInfo, bool> dictionary = new Dictionary <PSSnapInInfo, bool>(); foreach (CmdletInfo info2 in cmdlets) { PSSnapInInfo pSSnapIn = info2.PSSnapIn; if ((pSSnapIn != null) && !dictionary.ContainsKey(pSSnapIn)) { dictionary.Add(pSSnapIn, true); } } foreach (PSSnapInInfo info4 in dictionary.Keys) { if ((pattern2 == null) || pattern2.IsMatch(info4.Name)) { collection.Add(info4); } } return(collection); }
private static RegistryKey GetConfigurationProvidersRegistryKey() { try { return(PSSnapInReader.GetVersionRootKey(PSSnapInReader.GetMonadRootKey(), Utils.GetCurrentMajorVersion()).OpenSubKey("PSConfigurationProviders")); } catch (ArgumentException ex) { } catch (SecurityException ex) { } return((RegistryKey)null); }
protected override void ProcessRecord() { Collection <PSSnapInInfo> searchList = null; foreach (string str in this._pssnapins) { Exception innerException = null; Collection <string> snapInList = new Collection <string>(); try { if (WildcardPattern.ContainsWildcardCharacters(str)) { if (searchList == null) { searchList = PSSnapInReader.ReadAll(PSVersionInfo.RegistryVersion1Key); } snapInList = base.SearchListForPattern(searchList, str); if (snapInList.Count != 0) { goto Label_0088; } if (this._passThru) { base.WriteNonTerminatingError(str, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "NoPSSnapInsFound", new object[] { str }), ErrorCategory.InvalidArgument); } continue; } snapInList.Add(str); Label_0088: this.AddPSSnapIns(snapInList); } catch (PSArgumentException exception2) { innerException = exception2; } catch (SecurityException exception3) { innerException = exception3; } if (innerException != null) { base.WriteNonTerminatingError(str, "AddPSSnapInRead", innerException, ErrorCategory.InvalidArgument); } } }
internal static void CheckIfPowerShellVersionIsInstalled(Version version) { if ((version != null) && (version.Major == 2)) { try { PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key); if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.NetFrameWorkV2NotInstalled, new object[0])); } } catch (PSArgumentException) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PowerShellNotInstalled, new object[] { version, "PSVersion" })); } } }
/// <summary> /// Adds a mshsnapin specified by <paramref name="mshSnapInID"/> to the current list of /// mshsnapins. If the mshsnapin is successfully added, IsDirty property is set to true. /// </summary> /// <param name="mshSnapInID">ID of the mshsnapin which needs to be added.</param> /// <returns>A <see cref="PSSnapInInfo"/> object corresponding to mshSnapInID.</returns> /// <remarks>PSSnapIn information must be present in the registry for this call to succeed.</remarks> /// <exception cref="PSArgumentNullException"> /// mshSnapInID is empty or null. /// </exception> /// <exception cref="PSArgumentException"> /// PSSnapIn is already loaded. /// No PSSnapIn with given id found. /// PSSnapIn cannot be loaded. /// </exception> /// <exception cref="System.Security.SecurityException"> /// Caller doesn't have permission to read keys. /// </exception> internal PSSnapInInfo AddPSSnapIn(string mshSnapInID) { if (string.IsNullOrEmpty(mshSnapInID)) { PSTraceSource.NewArgumentNullException("mshSnapInID"); } // Check whether the mshsnapin is already present in defaultmshsnapins/externalMshSnapins if (IsDefaultPSSnapIn(mshSnapInID, _defaultPSSnapIns)) { s_mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotLoadDefault); } if (IsActiveExternalPSSnapIn(mshSnapInID)) { s_mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.PSSnapInAlreadyExists, mshSnapInID); } // Check whether the mshsnapin is present in the registry. PSSnapInInfo newPSSnapIn = PSSnapInReader.Read(this.MajorVersion, mshSnapInID); if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString())) { s_mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.AddPSSnapInBadMonadVersion, newPSSnapIn.PSVersion.ToString(), PSVersion.ToString()); } // new mshsnapin will never be null //if this is a valid new mshsnapin,add this to external mshsnapins _externalPSSnapIns.Add(newPSSnapIn); s_mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", mshSnapInID); //Set IsDirty to true IsDirty = true; return(newPSSnapIn); }
internal static MshConsoleInfo CreateDefaultConfiguration() { MshConsoleInfo info = new MshConsoleInfo(PSVersionInfo.PSVersion); try { info.defaultPSSnapIns = PSSnapInReader.ReadEnginePSSnapIns(); } catch (PSArgumentException exception) { string cannotLoadDefaults = ConsoleInfoErrorStrings.CannotLoadDefaults; _mshsnapinTracer.TraceError(cannotLoadDefaults, new object[0]); throw new PSSnapInException(cannotLoadDefaults, exception); } catch (SecurityException exception2) { string errorMessageFormat = ConsoleInfoErrorStrings.CannotLoadDefaults; _mshsnapinTracer.TraceError(errorMessageFormat, new object[0]); throw new PSSnapInException(errorMessageFormat, exception2); } return(info); }
internal static MshConsoleInfo CreateDefaultConfiguration() { using (MshConsoleInfo.tracer.TraceMethod()) { MshConsoleInfo mshConsoleInfo = new MshConsoleInfo(PSVersionInfo.PSVersion); try { mshConsoleInfo.defaultPSSnapIns = PSSnapInReader.ReadEnginePSSnapIns(); } catch (PSArgumentException ex) { string resourceString = ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "CannotLoadDefaults"); MshConsoleInfo._mshsnapinTracer.TraceError(resourceString); throw new PSSnapInException(resourceString, (Exception)ex); } catch (SecurityException ex) { string resourceString = ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "CannotLoadDefaults"); MshConsoleInfo._mshsnapinTracer.TraceError(resourceString); throw new PSSnapInException(resourceString, (Exception)ex); } return(mshConsoleInfo); } }
public void TestReadCoreEngineSnapIn() { PSSnapInInfo pSSnapInInfo = PSSnapInReader.ReadCoreEngineSnapIn(); Assert.Contains("PublicKeyToken=31bf3856ad364e35", pSSnapInInfo.AssemblyName); }
private void AddPSSnapIns(Collection <string> snapInList) { if (snapInList != null) { if (base.Context.RunspaceConfiguration == null) { Collection <PSSnapInInfo> snapIns = base.GetSnapIns(null); InitialSessionState state = InitialSessionState.Create(); bool flag = false; foreach (string str in snapInList) { if (InitialSessionState.IsEngineModule(str)) { base.WriteNonTerminatingError(str, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "LoadSystemSnapinAsModule", new object[] { str }), ErrorCategory.InvalidArgument); } else { try { PSSnapInInfo psSnapInInfo = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), str); PSSnapInInfo info2 = PSSnapInCommandBase.IsSnapInLoaded(snapIns, psSnapInInfo); if (info2 == null) { PSSnapInException exception; info2 = state.ImportPSSnapIn(str, out exception); flag = true; base.Context.InitialSessionState.ImportedSnapins.Add(info2.Name, info2); } if (this._passThru) { info2.LoadIndirectResources(base.ResourceReader); base.WriteObject(info2); } } catch (PSSnapInException exception2) { base.WriteNonTerminatingError(str, "AddPSSnapInRead", exception2, ErrorCategory.InvalidData); } } } if (flag) { state.Bind(base.Context, true); } } else { foreach (string str2 in snapInList) { Exception innerException = null; try { PSSnapInException warning = null; PSSnapInInfo sendToPipeline = base.Runspace.AddPSSnapIn(str2, out warning); if (warning != null) { base.WriteNonTerminatingError(str2, "AddPSSnapInRead", warning, ErrorCategory.InvalidData); } if (this._passThru) { sendToPipeline.LoadIndirectResources(base.ResourceReader); base.WriteObject(sendToPipeline); } } catch (PSArgumentException exception5) { innerException = exception5; } catch (PSSnapInException exception6) { innerException = exception6; } catch (SecurityException exception7) { innerException = exception7; } if (innerException != null) { base.WriteNonTerminatingError(str2, "AddPSSnapInRead", innerException, ErrorCategory.InvalidArgument); } } } } }
/// <summary> /// Routine to get the list of loaded snapins... /// </summary> /// <returns></returns> protected internal Collection <PSSnapInInfo> GetSnapIns(string pattern) { // If RunspaceConfiguration is not null, then return the list that it has if (Runspace != null) { if (pattern != null) { return(Runspace.ConsoleInfo.GetPSSnapIn(pattern, _shouldGetAll)); } else { return(Runspace.ConsoleInfo.PSSnapIns); } } WildcardPattern matcher = null; if (!String.IsNullOrEmpty(pattern)) { bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern); if (!doWildCardSearch) { // Verify PSSnapInID.. // This will throw if it not a valid name PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern); } matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); } Collection <PSSnapInInfo> snapins = new Collection <PSSnapInInfo>(); if (_shouldGetAll) { foreach (PSSnapInInfo snapinKey in PSSnapInReader.ReadAll()) { if (matcher == null || matcher.IsMatch(snapinKey.Name)) { snapins.Add(snapinKey); } } } else { // Otherwise, just scan through the list of cmdlets and rebuild the table. List <CmdletInfo> cmdlets = InvokeCommand.GetCmdlets(); Dictionary <PSSnapInInfo, bool> snapinTable = new Dictionary <PSSnapInInfo, bool>(); foreach (CmdletInfo cmdlet in cmdlets) { PSSnapInInfo snapin = cmdlet.PSSnapIn; if (snapin != null && !snapinTable.ContainsKey(snapin)) { snapinTable.Add(snapin, true); } } foreach (PSSnapInInfo snapinKey in snapinTable.Keys) { if (matcher == null || matcher.IsMatch(snapinKey.Name)) { snapins.Add(snapinKey); } } } return(snapins); }
/// <summary> /// Adds pssnapins to console file and loads the pssnapin dlls into /// the current monad runtime. /// </summary> /// <remarks> /// The new pssnapin information is not stored in the console file until /// the file is saved. /// </remarks> protected override void ProcessRecord() { // Cache for the information stored in the registry // update the cache the first time a wildcard is found.. Collection <PSSnapInInfo> listToSearch = null; foreach (string pattern in _pssnapins) { Exception exception = null; Collection <string> listToAdd = new Collection <string>(); try { // check whether there are any wildcard characters bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern); if (doWildCardSearch) { // wildcard found in the pattern // Get all the possible candidates for current monad version if (listToSearch == null) { // cache snapin registry information... // For 3.0 PowerShell, we still use "1" as the registry version key for // Snapin and Custom shell lookup/discovery. // For 3.0 PowerShell, we use "3" as the registry version key only for Engine // related data like ApplicationBase etc. listToSearch = PSSnapInReader.ReadAll(PSVersionInfo.RegistryVersion1Key); } listToAdd = SearchListForPattern(listToSearch, pattern); // listToAdd wont be null.. Diagnostics.Assert(listToAdd != null, "Pattern matching returned null"); if (listToAdd.Count == 0) { if (_passThru) { // passThru is specified and we have nothing to add... WriteNonTerminatingError(pattern, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(pattern, MshSnapInCmdletResources.NoPSSnapInsFound, pattern), ErrorCategory.InvalidArgument); } continue; } } else { listToAdd.Add(pattern); } // now add all the snapins for this pattern... AddPSSnapIns(listToAdd); } catch (PSArgumentException ae) { exception = ae; } catch (System.Security.SecurityException se) { exception = se; } if (exception != null) { WriteNonTerminatingError(pattern, "AddPSSnapInRead", exception, ErrorCategory.InvalidArgument); } } }
/// <summary> /// Adds one or more snapins /// </summary> /// <param name="snapInList">List of snapin IDs</param> /// <remarks> /// This is a helper method and should not throw any /// exceptions. All exceptions are caught and displayed /// to the user using write* methods /// </remarks> private void AddPSSnapIns(Collection <string> snapInList) { if (snapInList == null) { // nothing to add return; } //BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update // the set of cmdlets in a runspace if there is no RunspaceConfiguration object. // This is a temporary fix to unblock remoting tests and need to be corrected/completed // before we can ship... // If there is no RunspaceConfig object, then // use an InitialSessionState object to gather and // bind the cmdlets from the snapins... if (Context.RunspaceConfiguration == null) { Collection <PSSnapInInfo> loadedSnapins = base.GetSnapIns(null); InitialSessionState iss = InitialSessionState.Create(); bool isAtleastOneSnapinLoaded = false; foreach (string snapIn in snapInList) { if (InitialSessionState.IsEngineModule(snapIn)) { WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(snapIn, MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn), ErrorCategory.InvalidArgument); } else { PSSnapInException warning; try { // Read snapin data PSSnapInInfo newPSSnapIn = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn); PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn); // that means snapin is not already loaded ..so load the snapin // now. if (null == psSnapInInfo) { psSnapInInfo = iss.ImportPSSnapIn(snapIn, out warning); isAtleastOneSnapinLoaded = true; Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo); } // Write psSnapInInfo object only if passthru is specified. if (_passThru) { // Load the pssnapin info properties that are localizable and redirected in the registry psSnapInInfo.LoadIndirectResources(ResourceReader); WriteObject(psSnapInInfo); } } catch (PSSnapInException pse) { WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData); } } } if (isAtleastOneSnapinLoaded) { // Now update the session state with the new stuff... iss.Bind(Context, /*updateOnly*/ true); } return; } foreach (string psSnapIn in snapInList) { Exception exception = null; try { PSSnapInException warning = null; PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning); if (warning != null) { WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData); } // Write psSnapInInfo object only if passthru is specified. if (_passThru) { // Load the pssnapin info properties that are localizable and redirected in the registry psSnapInInfo.LoadIndirectResources(ResourceReader); WriteObject(psSnapInInfo); } } catch (PSArgumentException ae) { exception = ae; } catch (PSSnapInException sle) { exception = sle; } catch (System.Security.SecurityException se) { exception = se; } if (exception != null) { WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", exception, ErrorCategory.InvalidArgument); } } }
protected override void BeginProcessing() { if (this._pssnapins != null) { foreach (string str in this._pssnapins) { Exception innerException = null; try { Collection <PSSnapInInfo> snapIns = base.GetSnapIns(str); if (snapIns.Count == 0) { base.WriteNonTerminatingError(str, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "NoPSSnapInsFound", new object[] { str }), ErrorCategory.InvalidArgument); continue; } foreach (PSSnapInInfo info in snapIns) { info.LoadIndirectResources(base.ResourceReader); base.WriteObject(info); } } catch (SecurityException exception2) { innerException = exception2; } catch (PSArgumentException exception3) { innerException = exception3; } if (innerException != null) { base.WriteNonTerminatingError(str, "GetPSSnapInRead", innerException, ErrorCategory.InvalidArgument); } } } else if (base.ShouldGetAll) { Exception exception4 = null; try { foreach (PSSnapInInfo info2 in PSSnapInReader.ReadAll()) { info2.LoadIndirectResources(base.ResourceReader); base.WriteObject(info2); } } catch (SecurityException exception5) { exception4 = exception5; } catch (PSArgumentException exception6) { exception4 = exception6; } if (exception4 != null) { base.WriteNonTerminatingError(this, "GetPSSnapInRead", exception4, ErrorCategory.InvalidArgument); } } else { foreach (PSSnapInInfo info3 in base.GetSnapIns(null)) { info3.LoadIndirectResources(base.ResourceReader); base.WriteObject(info3); } } }
/// <summary> /// Constructs PSSnapInfo objects as requested by the user and writes them to the /// output buffer. /// </summary> protected override void BeginProcessing() { if (_pssnapins != null) { foreach (string psSnapIn in _pssnapins) { Exception exception = null; try { Collection <PSSnapInInfo> psSnapInInfoList = GetSnapIns(psSnapIn); // psSnapInInfoList wont be null.. Diagnostics.Assert(psSnapInInfoList != null, "ConsoleInfo.GetPSSnapIn returned null"); if (psSnapInInfoList.Count == 0) { WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(psSnapIn, MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn), ErrorCategory.InvalidArgument); continue; } foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList) { // Load the pssnapin info properties that are localizable and redirected in the registry pssnapinInfo.LoadIndirectResources(ResourceReader); WriteObject(pssnapinInfo); } } catch (System.Security.SecurityException se) { exception = se; } catch (PSArgumentException ae) { exception = ae; } if (exception != null) { WriteNonTerminatingError(psSnapIn, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument); } } } else if (ShouldGetAll) { Exception exception = null; try { Collection <PSSnapInInfo> psSnapInInfoList = PSSnapInReader.ReadAll(); foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList) { // Load the pssnapin info properties that are localizable and redirected in the registry pssnapinInfo.LoadIndirectResources(ResourceReader); WriteObject(pssnapinInfo); } } catch (System.Security.SecurityException se) { exception = se; } catch (PSArgumentException ae) { exception = ae; } if (exception != null) { WriteNonTerminatingError(this, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument); } } else { // this should never throw.. Collection <PSSnapInInfo> psSnapInInfoList = GetSnapIns(null); foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList) { // Load the pssnapin info properties that are localizable and redirected in the registry pssnapinInfo.LoadIndirectResources(ResourceReader); WriteObject(pssnapinInfo); } } }