public void Invoke_RecieveCompositeKey() { var password = "******"; var file = Path.Combine(Util.Root, "Resources", "test.key"); var userAccount = false; PowerShell ps = PowerShell.Create(); var commandInfo = new CmdletInfo("New-KeePassCompsiteKey", typeof(NewKeePassCompositeKeyCommand)); ps.AddCommand(commandInfo); var args = new List<object>() { password, file, userAccount }; ps.AddParameter("KeyPassword", password); ps.AddParameter("KeyFile", file); ps.AddParameter("UserAccount", userAccount); var enumerator = ps.Invoke().GetEnumerator(); enumerator.MoveNext(); var result = enumerator.Current; Assert.NotNull(result); Assert.IsType(typeof(CompositeKey), result.BaseObject); var compositeKey = (CompositeKey)result.BaseObject; var kcpPassword = (KcpPassword)compositeKey.GetUserKey(typeof(KcpPassword)); var kcpKeyFile = (KcpKeyFile)compositeKey.GetUserKey(typeof(KcpKeyFile)); Assert.NotNull(kcpPassword); Assert.NotNull(kcpKeyFile); Assert.Equal(userAccount, compositeKey.ContainsType(typeof(KcpUserAccount))); Assert.Equal(password, kcpPassword.Password.ReadString()); Assert.Equal(file, kcpKeyFile.Path); }
public static void IncrementData(CmdletInfo cmdlet) { if (isWinSQMEnabled && ((cmdlet.PSSnapIn != null) && cmdlet.PSSnapIn.IsDefault)) { IncrementDataPoint(cmdlet.Name); } }
/// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal CmdletInfo(CmdletInfo other) : base(other) { _verb = other._verb; _noun = other._noun; _implementingType = other._implementingType; _helpFilePath = other._helpFilePath; _PSSnapin = other._PSSnapin; _options = ScopedItemOptions.ReadOnly; }
public void ClearVariableOutputTypeDefinedInCmdletInfo() { var info = new CmdletInfo("Clear-Variable", typeof(TestOutputTypeCommand), null); Assert.AreEqual(2, info.OutputType.Count); PSTypeName stringType = info.OutputType.Single(type => type.Type == typeof(string)); PSTypeName boolType = info.OutputType.Single(type => type.Type == typeof(bool)); Assert.AreEqual("System.String", stringType.Name); Assert.AreEqual("System.Boolean", boolType.Name); }
private void DelayedInternalInitialize() { this.pp = new PipelineProcessor(); CmdletInfo cmdletInfo = new CmdletInfo(this.commandName, this.commandType, null, null, this.context); CommandProcessor commandProcessor = new CommandProcessor(cmdletInfo, this.context); foreach (CommandParameterInternal internal2 in this.commandParameterList) { commandProcessor.AddParameter(internal2); } this.pp.Add(commandProcessor); }
internal CmdletInfo(CmdletInfo other) : base(other) { this.verb = string.Empty; this.noun = string.Empty; this.helpFilePath = string.Empty; this.verb = other.verb; this.noun = other.noun; this.implementingType = other.implementingType; this.helpFilePath = other.helpFilePath; this._PSSnapin = other._PSSnapin; this.options = ScopedItemOptions.ReadOnly; }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = new Collection<CommandParameterSetInfo>(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _commonParameters = (from parameter in CommonCmdletParameters.CommonParameterSetInfo.Parameters select parameter.MemberInfo).ToList(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); }
internal CmdletInfo AddCmdletInfoToCache(string name, CmdletInfo newCmdletInfo, bool isGlobal) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (newCmdletInfo == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (isGlobal) { return this._context.EngineSessionState.ModuleScope.AddCmdletToCache(newCmdletInfo.Name, newCmdletInfo, CommandOrigin.Internal, this._context); } return this._context.EngineSessionState.CurrentScope.AddCmdletToCache(newCmdletInfo.Name, newCmdletInfo, CommandOrigin.Internal, this._context); }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _bindDestinationLookup = new Dictionary<MemberInfo, object>(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); // make sure common parameters are set in the CommonParameter member object, not the cmdlet itself AddBindDestionations(CommonCmdletParameters.ParameterDiscovery, _cmdlet.CommonParameters); }
private void Init(CmdletInfo cmdletInformation) { Cmdlet cmdlet = null; Exception exception = null; string str = null; string cmdletDoesNotDeriveFromCmdletType = null; try { cmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (cmdlet == null) { exception = new InvalidCastException(); str = "CmdletDoesNotDeriveFromCmdletType"; cmdletDoesNotDeriveFromCmdletType = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException exception2) { exception = exception2; } catch (TypeLoadException exception3) { exception = exception3; } catch (Exception exception4) { CommandProcessorBase.CheckForSevereException(exception4); CmdletInvocationException exception5 = new CmdletInvocationException(exception4, null); MshLog.LogCommandHealthEvent(base._context, exception5, Severity.Warning); throw exception5; } if (exception != null) { MshLog.LogCommandHealthEvent(base._context, exception, Severity.Warning); CommandNotFoundException exception6 = new CommandNotFoundException(cmdletInformation.Name, exception, str ?? "CmdletNotFoundException", cmdletDoesNotDeriveFromCmdletType ?? DiscoveryExceptions.CmdletNotFoundException, new object[] { exception.Message }); throw exception6; } base.Command = cmdlet; base.CommandScope = base.Context.EngineSessionState.CurrentScope; this.InitCommon(); }
internal void AddCmdletInfoToCache(CmdletInfo newCmdletInfo) => CommandDiscovery.AddCmdletInfoToCache(this._context.EngineSessionState, newCmdletInfo);
/// <summary> /// Initializes the command's request object /// </summary> /// /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> /// private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (null != initError) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); }
/// <summary> /// Initializes the command's request object /// </summary> /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (initError != null) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); }
private static string GetFullName(CmdletInfo cmdletInfo) => CmdletInfo.GetFullName(cmdletInfo.ModuleName, cmdletInfo.Name);
public CommandProcessor(CmdletInfo cmdletInfo) : base(cmdletInfo) { _cmdletInfo = cmdletInfo; _beganProcessing = false; }
/// <summary> /// Gets the full name of the cmdlet including the PSSnapin name. /// </summary> private static string GetFullName(CmdletInfo cmdletInfo) { return(GetFullName(cmdletInfo.ModuleName, cmdletInfo.Name)); }
/// <summary> /// We want to import the PKI module explicitly because a type for X509Certificate /// is defined in the PKI module that add new properties to the X509Certificate2 /// objects. We want to show those new properties to the user without requiring /// someone to force the loading of this module. /// </summary> private void AttemptToImportPkiModule() { const string moduleName = "pki"; if (Runspaces.Runspace.DefaultRunspace == null) { // // Requires default runspace. Only import the module. // when a default runspace is available. // return; } CommandInfo commandInfo = new CmdletInfo( "Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand)); Runspaces.Command importModuleCommand = new Runspaces.Command(commandInfo); s_tracer.WriteLine("Attempting to load module: {0}", moduleName); try { System.Management.Automation.PowerShell ps = null; ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace) .AddCommand(importModuleCommand) .AddParameter("Name", moduleName) .AddParameter("Scope", StringLiterals.Global) .AddParameter("ErrorAction", ActionPreference.Ignore) .AddParameter("WarningAction", ActionPreference.Ignore) .AddParameter("InformationAction", ActionPreference.Ignore) .AddParameter("Verbose", false) .AddParameter("Debug", false); ps.Invoke(); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } _hasAttemptedToLoadPkiModule = true; }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { bool flag = false; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; flag = true; } try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException) { } catch (ProviderNotFoundException) { } catch (DriveNotFoundException) { } catch (ProviderInvocationException) { } if (this.configHash != null) { if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables)) { Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable; if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { string introduced76 = entry.Key.ToString(); this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args); } } } if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions)) { Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]); if (hashtableArray != null) { foreach (Hashtable hashtable2 in hashtableArray) { if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken)) { string str2 = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken); ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock; if (!string.IsNullOrEmpty(str2) && (block != null)) { block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState; PowerShell powershell = PowerShell.Create(); powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope"); powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2); this.InvokePowerShell(powershell, args); } } } } } if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess)) { string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]); if (strArray != null) { foreach (string str3 in strArray) { if (!string.IsNullOrEmpty(str3)) { this.InvokeScript(new Command(str3, true, false), args); } } } } bool flag2 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases)) { string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]); if (strArray2 != null) { flag2 = true; foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable()) { bool flag3 = false; foreach (string str4 in strArray2) { if (!string.IsNullOrEmpty(str4)) { IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4); if (this.MatchKeyPattern(patternList, pair.Key)) { pair.Value.Visibility = SessionStateEntryVisibility.Public; flag3 = true; } } } if (!flag3) { pair.Value.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets)) { string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]); if (strArray3 != null) { flag2 = true; foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable()) { bool flag4 = false; foreach (string str5 in strArray3) { if (!string.IsNullOrEmpty(str5)) { IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5); if (this.MatchKeyPattern(enumerable2, pair2.Key)) { foreach (CmdletInfo info in pair2.Value) { info.Visibility = SessionStateEntryVisibility.Public; flag4 = true; } } } } if (!flag4) { foreach (CmdletInfo info2 in pair2.Value) { info2.Visibility = SessionStateEntryVisibility.Private; } } } } } List <string> list = new List <string>(); bool flag5 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions)) { string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]); if (strArray4 != null) { flag2 = true; flag5 = true; list.AddRange(strArray4); } } if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions)) { Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]); if (hashtableArray2 != null) { foreach (Hashtable hashtable3 in hashtableArray2) { string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken); if (!string.IsNullOrEmpty(str6)) { list.Add(str6); } } } } string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType); if (!string.IsNullOrEmpty(str7)) { SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true); if (type == SessionType.RestrictedRemoteServer) { list.Add("Get-Command"); list.Add("Get-FormatData"); list.Add("Select-Object"); list.Add("Get-Help"); list.Add("Measure-Object"); list.Add("Out-Default"); list.Add("Exit-PSSession"); } } if (list.Count > 0) { foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable()) { bool flag6 = false; string key = entry2.Key.ToString(); FunctionInfo info3 = entry2.Value as FunctionInfo; if (info3 != null) { foreach (string str9 in list) { if (!string.IsNullOrEmpty(str9)) { IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9); if (this.MatchKeyPattern(enumerable3, key)) { info3.Visibility = SessionStateEntryVisibility.Public; flag6 = true; } } } if (!flag6 && flag5) { info3.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders)) { string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]); if (strArray5 != null) { flag2 = true; IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers; Collection <string> collection = new Collection <string>(); foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers) { bool flag7 = false; foreach (string str10 in strArray5) { if (!string.IsNullOrEmpty(str10)) { IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10); if (this.MatchKeyPattern(enumerable4, pair3.Key)) { flag7 = true; } } } if (!flag7) { collection.Add(pair3.Key); } } foreach (string str11 in collection) { args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11); } } } if (flag2) { CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable(); PSModuleAutoLoadingPreference preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private); bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private); if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None)) { throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders })); } } if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode)) { PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true); if (flag && (mode != PSLanguageMode.ConstrainedLanguage)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState); } args.Runspace.ExecutionContext.LanguageMode = mode; } if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy)) { ExecutionPolicy policy = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true); string shellID = args.Runspace.ExecutionContext.ShellID; SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID); } } Command cmdToRun = null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { cmdToRun = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (cmdToRun != null) { this.InvokeScript(cmdToRun, args); if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert != null) { this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null); } } } }
internal static void MountDefaultDrive(string name, System.Management.Automation.ExecutionContext context) { if (CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference") != PSModuleAutoLoadingPreference.None) { string str = null; if (string.Equals("Cert", name, StringComparison.OrdinalIgnoreCase) || string.Equals("Certificate", name, StringComparison.OrdinalIgnoreCase)) { str = "Microsoft.PowerShell.Security"; } else if (string.Equals("WSMan", name, StringComparison.OrdinalIgnoreCase)) { str = "Microsoft.WSMan.Management"; } if (!string.IsNullOrEmpty(str)) { tracer.WriteLine("Auto-mounting built-in drive: {0}", new object[] { name }); CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context); Command command = new Command(commandInfo); tracer.WriteLine("Attempting to load module: {0}", new object[] { str }); try { PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } }
private PSModuleInfo ImportModule_LocallyViaName(ModuleCmdletBase.ImportModuleOptions importModuleOptions, string name) { try { if (name.Equals("PSWorkflow", StringComparison.OrdinalIgnoreCase) && Utils.IsRunningFromSysWOW64()) { throw new NotSupportedException(AutomationExceptions.WorkflowDoesNotSupportWOW64); } bool found = false; PSModuleInfo module = null; string str = null; string str2 = null; if (((this.MinimumVersion == null) && (this.RequiredVersion == null)) && (PSModuleInfo.UseAppDomainLevelModuleCache && !base.BaseForce)) { str = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name); } if (!string.IsNullOrEmpty(str)) { if (File.Exists(str)) { str2 = str; } else { PSModuleInfo.RemoveFromAppDomainLevelCache(name); } } if (str2 == null) { str2 = ModuleCmdletBase.ResolveRootedFilePath(name, base.Context); } bool flag2 = false; if (!string.IsNullOrEmpty(str2)) { if (!base.BaseForce && base.Context.Modules.ModuleTable.ContainsKey(str2)) { PSModuleInfo info2 = base.Context.Modules.ModuleTable[str2]; if (((this.RequiredVersion == null) || info2.Version.Equals(this.RequiredVersion)) || (((base.BaseMinimumVersion == null) || (info2.ModuleType != ModuleType.Manifest)) || (info2.Version >= base.BaseMinimumVersion))) { flag2 = true; ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, info2); base.ImportModuleMembers(info2, base.BasePrefix, importModuleOptions); if (base.BaseAsCustomObject) { if (info2.ModuleType != ModuleType.Script) { InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, info2.Path)); ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_CantUseAsCustomObjectWithBinaryModule", ErrorCategory.PermissionDenied, null); base.WriteError(errorRecord); } else { base.WriteObject(info2.AsCustomObject()); } } else if (base.BasePassThru) { base.WriteObject(info2); } found = true; module = info2; } } if (!flag2) { if (File.Exists(str2)) { PSModuleInfo info3; if (base.Context.Modules.ModuleTable.TryGetValue(str2, out info3)) { base.RemoveModule(info3); } module = base.LoadModule(str2, null, base.BasePrefix, null, ref importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found); } else if (Directory.Exists(str2)) { str2 = Path.Combine(str2, Path.GetFileName(str2)); module = base.LoadUsingExtensions(null, str2, str2, null, null, base.BasePrefix, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found); } } } else { if (InitialSessionState.IsEngineModule(name)) { CmdletInfo cmdlet = base.Context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-PSSnapIn"); if ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)) { CommandInfo commandInfo = new CmdletInfo("Get-PSSnapIn", typeof(GetPSSnapinCommand), null, null, base.Context); Command command = new Command(commandInfo); Collection<PSSnapInInfo> collection = null; try { using (PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace)) { shell.AddCommand(command).AddParameter("Name", name).AddParameter("ErrorAction", ActionPreference.Ignore); collection = shell.Invoke<PSSnapInInfo>(); } } catch (Exception exception2) { CommandProcessorBase.CheckForSevereException(exception2); } if ((collection != null) && (collection.Count == 1)) { string text = string.Format(CultureInfo.InvariantCulture, Modules.ModuleLoadedAsASnapin, new object[] { collection[0].Name }); base.WriteWarning(text); found = true; return module; } } } if (ModuleCmdletBase.IsRooted(name)) { if (!string.IsNullOrEmpty(Path.GetExtension(name))) { module = base.LoadModule(name, null, base.BasePrefix, null, ref importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found); } else { module = base.LoadUsingExtensions(null, name, name, null, null, base.BasePrefix, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found); } } else { IEnumerable<string> modulePath = ModuleIntrinsics.GetModulePath(false, base.Context); if ((this.MinimumVersion == null) && (this.RequiredVersion == null)) { base.AddToAppDomainLevelCache = true; } found = base.LoadUsingModulePath(found, modulePath, name, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out module); } } if (!found) { ErrorRecord record2 = null; string message = null; if (base.BaseRequiredVersion != null) { message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, base.BaseRequiredVersion); } else if (base.BaseMinimumVersion != null) { message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, base.BaseMinimumVersion); } if ((base.BaseRequiredVersion != null) || (base.BaseMinimumVersion != null)) { FileNotFoundException exception3 = new FileNotFoundException(message); record2 = new ErrorRecord(exception3, "Modules_ModuleWithVersionNotFound", ErrorCategory.ResourceUnavailable, name); } else { FileNotFoundException exception4 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, name)); record2 = new ErrorRecord(exception4, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, name); } base.WriteError(record2); } return module; } catch (PSInvalidOperationException exception5) { ErrorRecord record3 = new ErrorRecord(exception5.ErrorRecord, exception5); base.WriteError(record3); } return null; }
internal static void ExportModuleMembers( PSCmdlet cmdlet, SessionStateInternal sessionState, List <WildcardPattern> functionPatterns, List <WildcardPattern> cmdletPatterns, List <WildcardPattern> aliasPatterns, List <WildcardPattern> variablePatterns) { sessionState.UseExportList = true; if (functionPatterns != null) { foreach (KeyValuePair <string, FunctionInfo> keyValuePair in (IEnumerable <KeyValuePair <string, FunctionInfo> >)sessionState.ModuleScope.FunctionTable) { if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)functionPatterns, false)) { string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingFunction", (object)keyValuePair.Key); cmdlet.WriteVerbose(text); sessionState.ExportedFunctions.Add(keyValuePair.Value); } } ModuleIntrinsics.SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, (Converter <FunctionInfo, string>)(ci => ci.Name)); } if (cmdletPatterns != null) { IDictionary <string, List <CmdletInfo> > cmdletCache = (IDictionary <string, List <CmdletInfo> >)sessionState.CmdletCache; if (sessionState.Module.CompiledExports.Count > 0) { CmdletInfo[] array = sessionState.Module.CompiledExports.ToArray(); sessionState.Module.CompiledExports.Clear(); foreach (CmdletInfo cmdletInfo1 in array) { if (SessionStateUtilities.MatchesAnyWildcardPattern(cmdletInfo1.Name, (IEnumerable <WildcardPattern>)cmdletPatterns, false)) { string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)cmdletInfo1.Name); cmdlet.WriteVerbose(text); CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context); cmdletInfo2.SetModule(sessionState.Module); sessionState.Module.CompiledExports.Add(cmdletInfo2); } } } foreach (KeyValuePair <string, List <CmdletInfo> > keyValuePair in (IEnumerable <KeyValuePair <string, List <CmdletInfo> > >)cmdletCache) { if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)cmdletPatterns, false)) { string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)keyValuePair.Key); cmdlet.WriteVerbose(text); CmdletInfo cmdletInfo1 = keyValuePair.Value[0]; CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context); cmdletInfo2.SetModule(sessionState.Module); sessionState.Module.CompiledExports.Add(cmdletInfo2); } } ModuleIntrinsics.SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, (Converter <CmdletInfo, string>)(ci => ci.Name)); } if (variablePatterns != null) { foreach (KeyValuePair <string, PSVariable> variable in (IEnumerable <KeyValuePair <string, PSVariable> >)sessionState.ModuleScope.Variables) { if (!variable.Value.IsAllScope && Array.IndexOf <string>(PSModuleInfo.builtinVariables, variable.Key) == -1 && SessionStateUtilities.MatchesAnyWildcardPattern(variable.Key, (IEnumerable <WildcardPattern>)variablePatterns, false)) { string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingVariable", (object)variable.Key); cmdlet.WriteVerbose(text); sessionState.ExportedVariables.Add(variable.Value); } } ModuleIntrinsics.SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, (Converter <PSVariable, string>)(v => v.Name)); } if (aliasPatterns == null) { return; } foreach (AliasInfo aliasInfo in sessionState.ModuleScope.AliasTable) { if ((aliasInfo.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None && SessionStateUtilities.MatchesAnyWildcardPattern(aliasInfo.Name, (IEnumerable <WildcardPattern>)aliasPatterns, false)) { string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingAlias", (object)aliasInfo.Name); cmdlet.WriteVerbose(text); sessionState.ExportedAliases.Add(aliasInfo); } } ModuleIntrinsics.SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, (Converter <AliasInfo, string>)(ci => ci.Name)); }
internal static Dictionary <string, List <CommandTypes> > GetExportedCommands(string modulePath, bool testOnly, System.Management.Automation.ExecutionContext context) { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PSDisableModuleAutoLoadingMemoryCache"))) { AnalysisCacheIndexEntry entry = null; if ((itemCache.ContainsKey(modulePath) && (savedCacheIndex != null)) && savedCacheIndex.Entries.TryGetValue(modulePath, out entry)) { lock (itemCache) { if (itemCache.ContainsKey(modulePath)) { DateTime lastWriteTime = new FileInfo(modulePath).LastWriteTime; if ((lastWriteTime == entry.LastWriteTime) && (itemCache[modulePath] != null)) { return(itemCache[modulePath]); } ModuleIntrinsics.Tracer.WriteLine(string.Concat(new object[] { "Cache entry for ", modulePath, " was out of date. Cached on ", entry.LastWriteTime, ", last updated on ", lastWriteTime, ". Re-analyzing." }), new object[0]); itemCache.Remove(modulePath); } } } } string basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Windows\PowerShell\CommandAnalysis\"); ModuleIntrinsics.Tracer.WriteLine("Entering mutex PowerShell_CommandAnalysis_Lock", new object[0]); Dictionary <string, List <CommandTypes> > dictionary = null; using (Mutex mutex = new Mutex(false, "PowerShell_CommandAnalysis_Lock")) { mutex.WaitOne(); try { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(modulePath); dictionary = Get(basePath, modulePath); if (!testOnly && (dictionary == null)) { try { if (modulesBeingAnalyzed.Contains(modulePath)) { ModuleIntrinsics.Tracer.WriteLine(modulePath + " is already being analyzed. Exiting.", new object[0]); return(null); } ModuleIntrinsics.Tracer.WriteLine("Registering " + modulePath + " for analysis.", new object[0]); modulesBeingAnalyzed.Add(modulePath); CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context); Command command = new Command(commandInfo); ModuleIntrinsics.Tracer.WriteLine("Listing modules.", new object[0]); PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("List", true).AddParameter("Name", fileNameWithoutExtension).AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke <PSModuleInfo>(); } catch (Exception exception) { ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: " + exception.ToString(), new object[0]); CommandProcessorBase.CheckForSevereException(exception); } finally { ModuleIntrinsics.Tracer.WriteLine("Unregistering " + modulePath + " for analysis.", new object[0]); modulesBeingAnalyzed.Remove(modulePath); } dictionary = Get(basePath, modulePath); } if (dictionary != null) { lock (itemCache) { ModuleIntrinsics.Tracer.WriteLine("Caching " + dictionary.Count + " exported commands.", new object[0]); itemCache[modulePath] = dictionary; goto Label_037E; } } ModuleIntrinsics.Tracer.WriteLine("Detected an error while retrieving exported commands.", new object[0]); } finally { ModuleIntrinsics.Tracer.WriteLine("Releasing mutex.", new object[0]); mutex.ReleaseMutex(); } } Label_037E: if (dictionary != null) { ModuleIntrinsics.Tracer.WriteLine("Returning " + dictionary.Count + " exported commands.", new object[0]); return(dictionary); } ModuleIntrinsics.Tracer.WriteLine("Returning NULL for exported commands", new object[0]); return(dictionary); }
private CmdletInfo GetNextCmdlet() { CmdletInfo result = (CmdletInfo)null; if (this.matchingCmdlet == null) { Collection <CmdletInfo> matchingCmdlets; if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != SearchResolutionOptions.None) { matchingCmdlets = new Collection <CmdletInfo>(); PSSnapinQualifiedName instance = PSSnapinQualifiedName.GetInstance(this.commandName); if (instance == null) { return(result); } WildcardPattern wildcardPattern = new WildcardPattern(instance.ShortName, WildcardOptions.IgnoreCase); Dictionary <string, List <CmdletInfo> > cmdletCache = this._context.EngineSessionState.CmdletCache; while (true) { lock (cmdletCache) { foreach (List <CmdletInfo> cmdletInfoList in cmdletCache.Values) { foreach (CmdletInfo cmdletInfo in cmdletInfoList) { if (wildcardPattern.IsMatch(cmdletInfo.Name) && (string.IsNullOrEmpty(instance.PSSnapInName) || instance.PSSnapInName.Equals(cmdletInfo.ModuleName, StringComparison.OrdinalIgnoreCase))) { matchingCmdlets.Add(cmdletInfo); } } } } if (cmdletCache != this._context.TopLevelSessionState.CmdletCache) { cmdletCache = this._context.TopLevelSessionState.CmdletCache; } else { break; } } } else { matchingCmdlets = this._context.CommandDiscovery.GetCmdletInfo(this.commandName); if (matchingCmdlets.Count > 1) { if ((this.commandResolutionOptions & SearchResolutionOptions.ReturnFirstDuplicateCmdletName) != SearchResolutionOptions.None) { this.matchingCmdlet = matchingCmdlets.GetEnumerator(); while (this.matchingCmdlet.MoveNext()) { if (result == null) { result = this.matchingCmdlet.Current; } } return(this.traceResult(result)); } if ((this.commandResolutionOptions & SearchResolutionOptions.AllowDuplicateCmdletNames) == SearchResolutionOptions.None) { throw this.NewAmbiguousCmdletName(this.commandName, matchingCmdlets); } } } this.matchingCmdlet = matchingCmdlets.GetEnumerator(); } if (!this.matchingCmdlet.MoveNext()) { this.currentState = CommandSearcher.SearchState.CmdletResolution; this.matchingCmdlet = (IEnumerator <CmdletInfo>)null; } else { result = this.matchingCmdlet.Current; } return(this.traceResult(result)); }
private static string GetFullName(CmdletInfo cmdletInfo) { return GetFullName(cmdletInfo.ModuleName, cmdletInfo.Name); }
internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { string item = helpRequest.Target; Collection <string> iteratorVariable1 = new Collection <string>(); WildcardPattern pattern = null; bool iteratorVariable3 = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target); if (!searchOnlyContent) { if (iteratorVariable3) { if (item.IndexOf('-') >= 0) { iteratorVariable1.Add(item + "*"); } else { iteratorVariable1.Add("*" + item + "*"); } } else { iteratorVariable1.Add(item); } } else { iteratorVariable1.Add("*"); string target = helpRequest.Target; if (iteratorVariable3) { target = "*" + helpRequest.Target + "*"; } pattern = new WildcardPattern(target, WildcardOptions.IgnoreCase | WildcardOptions.Compiled); } int iteratorVariable4 = 0; Hashtable iteratorVariable5 = new Hashtable(StringComparer.OrdinalIgnoreCase); Hashtable iteratorVariable6 = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (string iteratorVariable7 in iteratorVariable1) { CommandSearcher commandSearcherForSearch = this.GetCommandSearcherForSearch(iteratorVariable7, this._context); while (commandSearcherForSearch.MoveNext()) { if (this._context.CurrentPipelineStopping) { break; } CommandInfo current = commandSearcherForSearch.Current; CmdletInfo cmdletInfo = current as CmdletInfo; HelpInfo helpInfo = null; string key = null; if (cmdletInfo != null) { helpInfo = this.GetHelpInfo(cmdletInfo, !iteratorVariable3); key = cmdletInfo.FullName; } else { IScriptCommandInfo scriptCommandInfo = current as IScriptCommandInfo; if (scriptCommandInfo != null) { key = current.Name; helpInfo = this.GetHelpInfo(scriptCommandInfo, !iteratorVariable3, searchOnlyContent); } } if (helpInfo != null) { if (!SessionState.IsVisible(helpRequest.CommandOrigin, current)) { if (!iteratorVariable6.ContainsKey(key)) { iteratorVariable6.Add(key, null); } } else if ((!iteratorVariable5.ContainsKey(key) && Match(helpInfo, helpRequest, current)) && (!searchOnlyContent || helpInfo.MatchPatternInContent(pattern))) { iteratorVariable5.Add(key, null); iteratorVariable4++; yield return(helpInfo); if ((iteratorVariable4 < helpRequest.MaxResults) || (helpRequest.MaxResults <= 0)) { continue; } break; } } } if (this.HelpCategory == (System.Management.Automation.HelpCategory.Cmdlet | System.Management.Automation.HelpCategory.Alias)) { foreach (CommandInfo iteratorVariable13 in ModuleUtils.GetMatchingCommands(iteratorVariable7, this._context, helpRequest.CommandOrigin, false)) { if (this._context.CurrentPipelineStopping) { break; } if (SessionState.IsVisible(helpRequest.CommandOrigin, iteratorVariable13)) { CmdletInfo iteratorVariable14 = iteratorVariable13 as CmdletInfo; HelpInfo iteratorVariable15 = null; string fullName = null; if (iteratorVariable14 != null) { iteratorVariable15 = this.GetHelpInfo(iteratorVariable14, !iteratorVariable3); fullName = iteratorVariable14.FullName; } else { IScriptCommandInfo info2 = iteratorVariable13 as IScriptCommandInfo; if (info2 != null) { fullName = iteratorVariable13.Name; iteratorVariable15 = this.GetHelpInfo(info2, !iteratorVariable3, searchOnlyContent); } } if ((((iteratorVariable15 != null) && !iteratorVariable5.ContainsKey(fullName)) && (!iteratorVariable6.ContainsKey(fullName) && Match(iteratorVariable15, helpRequest, iteratorVariable13))) && (!searchOnlyContent || iteratorVariable15.MatchPatternInContent(pattern))) { iteratorVariable5.Add(fullName, null); iteratorVariable4++; yield return(iteratorVariable15); if ((iteratorVariable4 >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0)) { break; } } } } } } }
internal static CmdletInfo NewCmdletInfo(SessionStateCmdletEntry entry, ExecutionContext context) { CmdletInfo info = new CmdletInfo(entry.Name, entry.ImplementingType, entry.HelpFileName, entry.PSSnapIn, context) { Visibility = entry.Visibility }; info.SetModule(entry.Module); return info; }
private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, CommandInfo result, ref Exception lastError) { int length = commandName.IndexOfAny(new char[] { ':', '\\' }); if ((length == -1) || (commandName[length] == ':')) { return null; } string str = commandName.Substring(0, length); string str2 = commandName.Substring(length + 1, (commandName.Length - length) - 1); if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || str.EndsWith(".", StringComparison.Ordinal)) { return null; } try { discoveryTracer.WriteLine("Executing module-qualified search: {0}", new object[] { commandName }); context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName); CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public))) { List<PSModuleInfo> modules = context.Modules.GetModules(new string[] { str }, false); PSModuleInfo info2 = null; if ((modules == null) || (modules.Count == 0)) { CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) { Visibility = cmdlet.Visibility }; Command command = new Command(commandInfo); Collection<PSModuleInfo> collection = null; discoveryTracer.WriteLine("Attempting to load module: {0}", new object[] { str }); try { collection = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke<PSModuleInfo>(); } catch (Exception exception) { discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message }); lastError = exception; CommandProcessorBase.CheckForSevereException(exception); } if ((collection == null) || (collection.Count == 0)) { string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportModule, str); CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoLoadModule", resourceStr, new object[0]); throw exception2; } info2 = collection[0]; } else { info2 = modules[0]; } if (info2.ExportedCommands.ContainsKey(str2)) { result = info2.ExportedCommands[str2]; } } return result; } catch (CommandNotFoundException) { throw; } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName); } return result; }
internal void AddExportedCmdlet(CmdletInfo cmdlet) { this._compiledExports.Add(cmdlet); }
internal void AddExportedCmdlet(CmdletInfo cmdlet) { this._compiledExports.Add(cmdlet); }
// TODO: separate providers from cmdlets internal Collection<CmdletInfo> LoadCmdletsFromPSSnapin(string strType, out Collection<SnapinProviderPair> providers) { Collection<CmdletInfo> collection = new Collection<CmdletInfo>(); providers = new Collection<SnapinProviderPair>(); try { Type snapinType = Type.GetType(strType, true); Assembly assembly = snapinType.Assembly; PSSnapIn snapin = Activator.CreateInstance(snapinType) as PSSnapIn; PSSnapInInfo snapinInfo = new PSSnapInInfo(snapin.Name, false, string.Empty, assembly.GetName().Name, string.Empty, new Version(1, 0), null, null, null, snapin.Description, snapin.Vendor); foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(Cmdlet))) { foreach (CmdletAttribute cmdletAttribute in type.GetCustomAttributes(typeof(CmdletAttribute), true)) { CmdletInfo cmdletInfo = new CmdletInfo(cmdletAttribute.ToString(), type, null, snapinInfo, _context); collection.Add(cmdletInfo); } continue; } if (type.IsSubclassOf(typeof(CmdletProvider))) { foreach (CmdletProviderAttribute providerAttr in type.GetCustomAttributes(typeof(CmdletProviderAttribute), true)) { providers.Add(new SnapinProviderPair() { snapinInfo = snapinInfo, providerType = type, providerAttr = providerAttr }); } continue; } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } return collection; }
public CommandProcessor(CmdletInfo cmdletInfo) : base(cmdletInfo) { _cmdletInfo = cmdletInfo; _beganProcessing = false; }
internal CommandProcessor(CmdletInfo cmdletInfo, ExecutionContext context) : base(cmdletInfo) { this._firstCallToRead = true; base._context = context; this.Init(cmdletInfo); }
/// <summary> /// Initializes the new instance of CommandProcessor class. /// </summary> /// <param name="cmdletInfo"> /// The information about the cmdlet. /// </param> /// <param name="context"> /// PowerShell engine execution context for this command. /// </param> /// <exception cref="CommandNotFoundException"> /// If there was a failure creating an instance of the cmdlet type. /// </exception> internal CommandProcessor(CmdletInfo cmdletInfo, ExecutionContext context) : base(cmdletInfo) { this._context = context; Init(cmdletInfo); }
internal static void AddCmdletInfoToCache( SessionStateInternal sessionState, CmdletInfo newCmdletInfo) { bool flag = false; try { lock (sessionState.CmdletCache) { if (sessionState.CmdletCache.ContainsKey(newCmdletInfo.Name)) { List <CmdletInfo> cmdletInfoList = sessionState.CmdletCache[newCmdletInfo.Name]; if (!string.IsNullOrEmpty(newCmdletInfo.ModuleName)) { foreach (CmdletInfo cmdletInfo in cmdletInfoList) { if (string.Equals(newCmdletInfo.FullName, cmdletInfo.FullName, StringComparison.OrdinalIgnoreCase)) { if (newCmdletInfo.ImplementingType == cmdletInfo.ImplementingType) { return; } flag = true; break; } } } else { using (List <CmdletInfo> .Enumerator enumerator = cmdletInfoList.GetEnumerator()) { if (enumerator.MoveNext()) { CmdletInfo current = enumerator.Current; if (newCmdletInfo.ImplementingType == current.ImplementingType) { return; } flag = true; } } } if (!flag) { sessionState.CmdletCache[newCmdletInfo.Name].Insert(0, newCmdletInfo); } } else { sessionState.CmdletCache.Add(newCmdletInfo.Name, new List <CmdletInfo>() { newCmdletInfo }); } } } catch (ArgumentException ex) { flag = true; } if (flag) { throw CommandDiscovery.tracer.NewNotSupportedException("DiscoveryExceptions", "DuplicateCmdletName", (object)newCmdletInfo.Name); } }
private static void CallGetModuleDashList(ExecutionContext context, string modulePath) { CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context); Command getModuleCommand = new Command(commandInfo); try { PowerShell.Create(RunspaceMode.CurrentRunspace) .AddCommand(getModuleCommand) .AddParameter("List", true) .AddParameter("ErrorAction", ActionPreference.Ignore) .AddParameter("WarningAction", ActionPreference.Ignore) .AddParameter("InformationAction", ActionPreference.Ignore) .AddParameter("Verbose", false) .AddParameter("Debug", false) .AddParameter("Name", modulePath) .Invoke(); } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e); // Catch-all OK, third-party call-out. CommandProcessorBase.CheckForSevereException(e); } }
/// <summary> /// Initializes the new instance of CommandProcessor class. /// </summary> /// /// <param name="cmdletInfo"> /// The information about the cmdlet. /// </param> /// /// <param name="context"> /// PowerShell engine execution context for this command. /// </param> /// /// <exception cref="CommandNotFoundException"> /// If there was a failure creating an instance of the cmdlet type. /// </exception> /// internal CommandProcessor(CmdletInfo cmdletInfo, ExecutionContext context) : base(cmdletInfo) { this._context = context; Init(cmdletInfo); }
private static CommandInfo TryModuleAutoDiscovery(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError) { CommandInfo info = null; try { CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module"); if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public))) { cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public))) { discoveryTracer.WriteLine("Executing non module-qualified search: {0}", new object[] { commandName }); context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName); foreach (string str in ModuleUtils.GetDefaultAvailableModuleFiles(true, true, context)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str); Dictionary<string, List<CommandTypes>> dictionary = AnalysisCache.GetExportedCommands(str, false, context); if (dictionary != null) { if (dictionary.ContainsKey(commandName)) { CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) { Visibility = cmdlet.Visibility }; Command command = new Command(commandInfo); discoveryTracer.WriteLine("Found in module: {0}", new object[] { str }); PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("PassThru").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false); Collection<PSModuleInfo> collection = null; try { collection = shell.Invoke<PSModuleInfo>(); } catch (Exception exception) { discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message }); lastError = exception; CommandProcessorBase.CheckForSevereException(exception); } if ((collection == null) || (collection.Count == 0)) { string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, fileNameWithoutExtension); CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoloadMatchingModule", resourceStr, new object[0]); throw exception2; } info = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context); } if (info != null) { return info; } } } } return info; } return info; } catch (CommandNotFoundException) { throw; } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName); } return info; }
private static void AddNoopCommandProcessor(PipelineProcessor pipelineProcessor, System.Management.Automation.ExecutionContext context) { CmdletInfo commandInfo = new CmdletInfo("Out-Null", typeof(OutNullCommand)); CommandProcessorBase commandProcessor = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, false, null); pipelineProcessor.Add(commandProcessor); }
internal CmdletInfo AddCmdletToCache(string name, CmdletInfo cmdlet, CommandOrigin origin, System.Management.Automation.ExecutionContext context) { bool flag = false; try { List<CmdletInfo> list; if (!this.GetCmdlets().TryGetValue(name, out list)) { list = new List<CmdletInfo> { cmdlet }; this.GetCmdlets().Add(name, list); if ((cmdlet.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None) { this.GetAllScopeCmdlets()[name].Insert(0, cmdlet); } } else { if (!string.IsNullOrEmpty(cmdlet.ModuleName)) { foreach (CmdletInfo info in list) { if (string.Equals(cmdlet.FullName, info.FullName, StringComparison.OrdinalIgnoreCase)) { if (cmdlet.ImplementingType == info.ImplementingType) { return null; } flag = true; break; } } } else { foreach (CmdletInfo info2 in list) { if (cmdlet.ImplementingType == info2.ImplementingType) { return null; } flag = true; break; } } if (!flag) { list.Insert(0, cmdlet); } } } catch (ArgumentException) { flag = true; } if (flag) { throw PSTraceSource.NewNotSupportedException("DiscoveryExceptions", "DuplicateCmdletName", new object[] { cmdlet.Name }); } return this.GetCmdlets()[name][0]; }
internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context) { RemotePipeline remotePipeline = cmd as RemotePipeline; if (remotePipeline != null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = host }; PSDataCollection<PSObject> input = new PSDataCollection<PSObject>(); CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context); Command outDefaultCommand = new Command(commandInfo); ps.AddCommand(outDefaultCommand); IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null); RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; if (remoteDebugger != null) { // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. remoteDebugger.SendBreakpointUpdatedEvents(); if (!inDebugMode) { // Enter debug mode if remote runspace is in debug stop mode. remoteDebugger.CheckStateAndRaiseStopEvent(); } } // Wait for debugged cmd to complete. while (!remotePipeline.Output.EndOfPipeline) { remotePipeline.Output.WaitHandle.WaitOne(); while (remotePipeline.Output.Count > 0) { input.Add(remotePipeline.Output.Read()); } } input.Complete(); ps.EndInvoke(async); } } }
internal static IAstToWorkflowConverter GetAstToWorkflowConverterAndEnsureWorkflowModuleLoaded(ExecutionContext context) { IAstToWorkflowConverter converter = null; Type type = null; if (IsRunningFromSysWOW64()) { throw new NotSupportedException(AutomationExceptions.WorkflowDoesNotSupportWOW64); } if (((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)) { throw new NotSupportedException(Modules.CannotDefineWorkflowInconsistentLanguageMode); } if ((context != null) && !context.PSWorkflowModuleLoadingInProgress) { context.PSWorkflowModuleLoadingInProgress = true; List<PSModuleInfo> modules = context.Modules.GetModules(new string[] { "PSWorkflow" }, false); if ((modules == null) || (modules.Count == 0)) { CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context); Command command = new Command(commandInfo); try { PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", "PSWorkflow").AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke<PSModuleInfo>(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { converter = (IAstToWorkflowConverter) type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); } if (converter == null) { throw new NotSupportedException(StringUtil.Format(AutomationExceptions.CantLoadWorkflowType, "Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "PSWorkflow")); } return converter; }
private void AttemptToImportPkiModule() { if (Runspace.DefaultRunspace != null) { CommandInfo cmdletInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand)); Command command = new Command(cmdletInfo); object[] objArray = new object[1]; objArray[0] = "pki"; CertificateProvider.tracer.WriteLine("Attempting to load module: {0}", objArray); try { System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", "pki").AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false); powerShell.Invoke(); } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); } this._hasAttemptedToLoadPkiModule = true; return; } else { return; } }
public void LoadCmdInfo() { info = TestParameterCommand.CreateCmdletInfo(); }
internal static void ExportModuleMembers(PSCmdlet cmdlet, SessionStateInternal sessionState, List <WildcardPattern> functionPatterns, List <WildcardPattern> cmdletPatterns, List <WildcardPattern> aliasPatterns, List <WildcardPattern> variablePatterns, List <string> doNotExportCmdlets) { sessionState.UseExportList = true; if (functionPatterns != null) { foreach (KeyValuePair <string, FunctionInfo> pair in sessionState.ModuleScope.FunctionTable) { if (((pair.Value.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, functionPatterns, false)) { string str; if (pair.Value.CommandType == CommandTypes.Workflow) { str = StringUtil.Format(Modules.ExportingWorkflow, pair.Key); sessionState.ExportedWorkflows.Add((WorkflowInfo)pair.Value); } else { str = StringUtil.Format(Modules.ExportingFunction, pair.Key); sessionState.ExportedFunctions.Add(pair.Value); } cmdlet.WriteVerbose(str); } } SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, ci => ci.Name); SortAndRemoveDuplicates <WorkflowInfo>(sessionState.ExportedWorkflows, ci => ci.Name); } if (cmdletPatterns != null) { IDictionary <string, List <CmdletInfo> > cmdletTable = sessionState.ModuleScope.CmdletTable; if (sessionState.Module.CompiledExports.Count > 0) { CmdletInfo[] infoArray = sessionState.Module.CompiledExports.ToArray(); sessionState.Module.CompiledExports.Clear(); CmdletInfo[] infoArray2 = infoArray; for (int i = 0; i < infoArray2.Length; i++) { Predicate <string> match = null; CmdletInfo element = infoArray2[i]; if (doNotExportCmdlets != null) { if (match == null) { match = cmdletName => string.Equals(element.FullName, cmdletName, StringComparison.OrdinalIgnoreCase); } if (doNotExportCmdlets.Exists(match)) { continue; } } if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, cmdletPatterns, false)) { string text = StringUtil.Format(Modules.ExportingCmdlet, element.Name); cmdlet.WriteVerbose(text); CmdletInfo item = new CmdletInfo(element.Name, element.ImplementingType, element.HelpFile, null, element.Context); item.SetModule(sessionState.Module); sessionState.Module.CompiledExports.Add(item); } } } foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in cmdletTable) { CmdletInfo cmdletToImport = pair2.Value[0]; if (((doNotExportCmdlets == null) || !doNotExportCmdlets.Exists(cmdletName => string.Equals(cmdletToImport.FullName, cmdletName, StringComparison.OrdinalIgnoreCase))) && SessionStateUtilities.MatchesAnyWildcardPattern(pair2.Key, cmdletPatterns, false)) { string str3 = StringUtil.Format(Modules.ExportingCmdlet, pair2.Key); cmdlet.WriteVerbose(str3); CmdletInfo info2 = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType, cmdletToImport.HelpFile, null, cmdletToImport.Context); info2.SetModule(sessionState.Module); sessionState.Module.CompiledExports.Add(info2); } } SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, ci => ci.Name); } if (variablePatterns != null) { foreach (KeyValuePair <string, PSVariable> pair3 in sessionState.ModuleScope.Variables) { if ((!pair3.Value.IsAllScope && (Array.IndexOf <string>(PSModuleInfo._builtinVariables, pair3.Key) == -1)) && SessionStateUtilities.MatchesAnyWildcardPattern(pair3.Key, variablePatterns, false)) { string str4 = StringUtil.Format(Modules.ExportingVariable, pair3.Key); cmdlet.WriteVerbose(str4); sessionState.ExportedVariables.Add(pair3.Value); } } SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, v => v.Name); } if (aliasPatterns != null) { foreach (AliasInfo info3 in sessionState.ModuleScope.AliasTable) { if (((info3.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(info3.Name, aliasPatterns, false)) { string str5 = StringUtil.Format(Modules.ExportingAlias, info3.Name); cmdlet.WriteVerbose(str5); sessionState.ExportedAliases.Add(info3); } } SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, ci => ci.Name); } }