public void GetCommandListForFileTask_LinkToExistsMoveFileNoOverWrite_MoveFileCommandAdded() { FakeFile linkTo = new FakeFile("LinkTo"); linkTo.ExistsReturnValue = true; FakeFile linkFrom = new FakeFile("LinkFrom"); var commandFactory = MockRepository.GenerateMock <ICommandFactory>(); var commandDiscovery = new CommandDiscovery(commandFactory, f => new FakeFile(f), f => new FakeFolder(f)); var commandList = commandDiscovery.GetCommandListForFileTask(linkTo, linkFrom, true, false); Assert.AreEqual(2, commandList.Count); commandFactory.AssertWasCalled(cf => cf.MoveFileCommand(Arg <IFile> .Is.Equal(linkTo), Arg <IFile> .Is.Equal(linkFrom), Arg <Boolean> .Is.Equal(false))); commandFactory.AssertWasCalled(cf => cf.CreateFileLinkCommand(Arg <IFile> .Is.Equal(linkTo), Arg <IFile> .Is.Equal(linkFrom))); }
private CommandProcessorBase _CreateCommand(string commandName, CommandOrigin commandOrigin, bool?useLocalScope) { if (_context == null) { throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.ExecutionContextNotSet); } // Look for a cmdlet... CommandDiscovery discovery = _context.CommandDiscovery; if (discovery == null) { throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.CommandDiscoveryMissing); } // Look for the command using command discovery mechanisms. This will resolve // aliases, functions, filters, cmdlets, scripts, and applications. return(discovery.LookupCommandProcessor(commandName, commandOrigin, useLocalScope)); }
private static string GetBaseFolder(RunspaceConfiguration runspaceConfiguration, Collection <string> independentErrors) { string shellPathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId); if (shellPathFromRegistry == null) { return(Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName)); } if (OSHelper.IsWindows) { shellPathFromRegistry = Path.GetDirectoryName(shellPathFromRegistry); } if (!Directory.Exists(shellPathFromRegistry)) { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string item = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, new object[] { shellPathFromRegistry, Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), @"\Path", directoryName }); independentErrors.Add(item); shellPathFromRegistry = directoryName; } return(shellPathFromRegistry); }
public void GetCommandListForFolderTask_TargetExistsOneFiles_MoveFileThenDeleteFolderThenCreateLinkReturned() { ICommandFactory factory = new MockCommandFactory(); FakeFolder linkTo = new FakeFolder(); linkTo.FileList = new List <IFile> { Helpers.CreateStubHelpers.GetIFileStub("1.txt", @"c:\path") }; linkTo.FolderExistsReturnValue = true; FakeFolder linkFrom = new FakeFolder(@"c:\dest\"); linkFrom.FolderExistsReturnValue = true; ICommandDiscovery discoverer = new CommandDiscovery(factory, (f) => new FakeFile(f), f => new FakeFolder(f)); List <ICommand> taskList = discoverer.GetCommandListForFolderTask(linkTo, linkFrom, true, false); Assert.IsTrue(taskList.Count() == 3, "There should be three items in the list"); Assert.IsTrue(((MockCommand)taskList[0]).CommandName.Equals("MoveFileCommand")); Assert.IsTrue(((MockCommand)taskList[1]).CommandName.Equals("DeleteFolderCommand")); Assert.IsTrue(((MockCommand)taskList[2]).CommandName.Equals("CreateLinkCommand")); }
private static string GetBaseFolder( RunspaceConfiguration runspaceConfiguration, Collection <string> independentErrors) { string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId); string path; if (pathFromRegistry == null) { path = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName); } else { path = Path.GetDirectoryName(pathFromRegistry); if (!Directory.Exists(path)) { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string str = ResourceManagerCache.FormatResourceString("TypesXml", "CannotFindRegistryKeyPath", (object)path, (object)Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), (object)"\\Path", (object)directoryName); independentErrors.Add(str); path = directoryName; } } return(path); }
private static string GetBaseFolder( RunspaceConfiguration runspaceConfiguration, Collection <string> independentErrors) { string returnValue = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId); if (returnValue == null) { returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); } else { returnValue = Path.GetDirectoryName(returnValue); if (!Directory.Exists(returnValue)) { string newReturnValue = Path.GetDirectoryName(typeof(FormatAndTypeDataHelper).GetTypeInfo().Assembly.Location); string error = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, returnValue, Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), "\\Path", newReturnValue); independentErrors.Add(error); returnValue = newReturnValue; } } return(returnValue); }
public void GetCommandListForFolderTask_TargetHasSubFolderWithOneWithOverwriteFile_SubfolderAndOneIsMovedCreatedInSource() { ICommandFactory factory = MockRepository.GenerateMock <ICommandFactory>(); FakeFolder subFolder = new FakeFolder(@"c:\target\subfolder\"); subFolder.FileList = new List <IFile> { Helpers.CreateStubHelpers.GetIFileStub("1.txt", @"c:\target\subfolder\") }; FakeFolder linkTo = new FakeFolder(@"c:\target\") { FolderExistsReturnValue = true }; linkTo.SubFolderList = new List <IFolder> { subFolder }; FakeFolder linkFrom = new FakeFolder(@"c:\destination\") { FolderExistsReturnValue = true }; ICommandDiscovery discoverer = new CommandDiscovery(factory, f => new FakeFile(f), f => new FakeFolder(f) { FolderExistsReturnValue = false }); discoverer.GetCommandListForFolderTask(linkTo, linkFrom, true, true); factory.AssertWasCalled(f => f.MoveFileCommand( Arg <IFile> .Matches(source => source.FullFilePath.Equals(@"c:\target\subfolder\1.txt")), Arg <IFile> .Matches(target => target.FullFilePath.Equals(@"c:\destination\subfolder\1.txt")), Arg <Boolean> .Is.Equal(true) )); }
/// <summary> /// 1. Set the throttling limit and reset operations complete /// 2. Create helper objects /// 3. For async case, write the async result object down the /// pipeline. /// </summary> protected override void BeginProcessing() { if (!File.Exists(PowerShellProcessInstance.PwshExePath)) { // The pwsh executable file is not found under $PSHOME. // This means that PowerShell is currently being hosted in another application, // and 'Start-Job' is not supported by design in that scenario. string message = StringUtil.Format( RemotingErrorIdStrings.IPCPwshExecutableNotFound, PowerShellProcessInstance.PwshExePath); var errorRecord = new ErrorRecord( new PSNotSupportedException(message), "IPCPwshExecutableNotFound", ErrorCategory.NotInstalled, PowerShellProcessInstance.PwshExePath); ThrowTerminatingError(errorRecord); } if (RunAs32.IsPresent && Environment.Is64BitProcess) { // We cannot start a 32-bit 'pwsh' process from a 64-bit 'pwsh' installation. string message = RemotingErrorIdStrings.RunAs32NotSupported; var errorRecord = new ErrorRecord( new PSNotSupportedException(message), "RunAs32NotSupported", ErrorCategory.InvalidOperation, targetObject: null); ThrowTerminatingError(errorRecord); } if (WorkingDirectory != null && !Directory.Exists(WorkingDirectory)) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory); var errorRecord = new ErrorRecord( new DirectoryNotFoundException(message), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, targetObject: null); ThrowTerminatingError(errorRecord); } if (WorkingDirectory is null) { try { WorkingDirectory = SessionState.Internal.CurrentLocation.Path; } catch (PSInvalidOperationException) { } } CommandDiscovery.AutoloadModulesWithJobSourceAdapters(this.Context, this.CommandOrigin); if (ParameterSetName == DefinitionNameParameterSet) { return; } // since jobs no more depend on WinRM // we will have to skip the check for the same SkipWinRMCheck = true; base.BeginProcessing(); }
/// <summary> /// Gets a list of matching commands. /// </summary> /// <param name="pattern">Command pattern.</param> /// <param name="context">Execution context.</param> /// <param name="commandOrigin">Command origin.</param> /// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param> /// <param name="moduleVersionRequired">Specific module version to be required.</param> /// <param name="useFuzzyMatching">Use fuzzy matching.</param> /// <param name="useAbbreviationExpansion">Use abbreviation expansion for matching.</param> /// <returns>Returns matching CommandInfo IEnumerable.</returns> internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) && ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) { foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context)) { // Skip modules that have already been loaded so that we don't expose private commands. string moduleName = Path.GetFileNameWithoutExtension(modulePath); List <PSModuleInfo> modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true); PSModuleInfo tempModuleInfo = null; if (modules.Count != 0) { // 1. We continue to the next module path if we don't want to re-discover those imported modules // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, // then we don't do re-discovery if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers)) { continue; } if (modules.Count == 1) { PSModuleInfo psModule = modules[0]; tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null); tempModuleInfo.SetModuleBase(psModule.ModuleBase); foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name) || (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase))) { CommandInfo current = null; switch (entry.Value.CommandType) { case CommandTypes.Alias: current = new AliasInfo(entry.Value.Name, definition: null, context); break; case CommandTypes.Function: current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Filter: current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Configuration: current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Cmdlet: current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context); break; default: Dbg.Assert(false, "cannot be hit"); break; } current.Module = tempModuleInfo; yield return(current); } } continue; } } string moduleShortName = Path.GetFileNameWithoutExtension(modulePath); IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context); if (exportedCommands == null) { continue; } tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null); if (InitialSessionState.IsEngineModule(moduleShortName)) { tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase); } // moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved. if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath)); tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath)); } foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands) { string commandName = pair.Key; CommandTypes commandTypes = pair.Value; if (commandPattern.IsMatch(commandName) || (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase))) { bool shouldExportCommand = true; // Verify that we don't already have it represented in the initial session state. if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName]) { string moduleCompareName = null; if (commandEntry.Module != null) { moduleCompareName = commandEntry.Module.Name; } else if (commandEntry.PSSnapIn != null) { moduleCompareName = commandEntry.PSSnapIn.Name; } if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase)) { if (commandEntry.Visibility == SessionStateEntryVisibility.Private) { shouldExportCommand = false; } } } } if (shouldExportCommand) { if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias) { yield return(new AliasInfo(commandName, null, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Function) == CommandTypes.Function) { yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration) { yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } } } } } } }
/// <summary> /// All remoting cmdlets other than Start-PSJob should /// continue to work even if PowerShell remoting is not /// enabled. This is because jobs are based out of APIs /// and there can be other job implementations like /// eventing or WMI which are not based on PowerShell /// remoting. /// </summary> protected override void BeginProcessing() { CommandDiscovery.AutoloadModulesWithJobSourceAdapters(this.Context, this.CommandOrigin); // intentionally left blank to avoid // check being performed in base.BeginProcessing() }
public bool MoveNext() { try { int num = this.__1__state; if (num != 0) { if (num == 3) { this.__1__state = 2; this.__m__Finally1e(); } if (num == 7) { this.__1__state = 5; this.__m__Finally22(); } } else { this.__1__state = -1; this._commandPattern_5__b = new WildcardPattern(this.pattern, WildcardOptions.IgnoreCase); this._cmdletInfo_5__c = this.context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module"); aa__ = CommandDiscovery.GetCommandDiscoveryPreference(this.context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((aa__ != PSModuleAutoLoadingPreference.None) && ((this.commandOrigin == CommandOrigin.Internal) || ((this._cmdletInfo_5__c != null) && (this._cmdletInfo_5__c.Visibility == SessionStateEntryVisibility.Public)))) { this.__7__wrap1b = ModuleUtils.GetDefaultAvailableModuleFiles(true, false, this.context).GetEnumerator(); this.__1__state = 1; while (this.__7__wrap1b.MoveNext()) { this._modulePath_5__e = this.__7__wrap1b.Current; this._moduleName_5__f = Path.GetFileNameWithoutExtension(this._modulePath_5__e); this._modules_5__10 = this.context.Modules.GetExactMatchModules(this._moduleName_5__f, false, true); this._tempModuleInfo_5__11 = null; if (this._modules_5__10.Count != 0) { if (!this.rediscoverImportedModules) { continue; } if (this._modules_5__10.Exists(new Predicate <PSModuleInfo>(ModuleUtils.GetMatchingCommands_b__8))) { continue; } if (this._modules_5__10.Count == 1) { this._psModule_5__12 = this._modules_5__10[0]; this._tempModuleInfo_5__11 = new PSModuleInfo(this._psModule_5__12.Name, this._psModule_5__12.Path, null, null); this._tempModuleInfo_5__11.SetModuleBase(this._psModule_5__12.ModuleBase); this.__7__wrap1d = this._psModule_5__12.ExportedCommands.GetEnumerator(); this.__1__state = 2; while (this.__7__wrap1d.MoveNext()) { this._entry_5__13 = this.__7__wrap1d.Current; if (!this._commandPattern_5__b.IsMatch(this._entry_5__13.Value.Name)) { continue; } this._current_5__14 = null; switch (this._entry_5__13.Value.CommandType) { case CommandTypes.Alias: this._current_5__14 = new AliasInfo(this._entry_5__13.Value.Name, null, this.context); break; case CommandTypes.Function: this._current_5__14 = new FunctionInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context); break; case CommandTypes.Filter: this._current_5__14 = new FilterInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context); break; case CommandTypes.Cmdlet: this._current_5__14 = new CmdletInfo(this._entry_5__13.Value.Name, null, null, null, this.context); break; case CommandTypes.Workflow: this._current_5__14 = new WorkflowInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context); break; } this._current_5__14.SetModule(this._tempModuleInfo_5__11); this.__2__current = this._current_5__14; this.__1__state = 3; return(true); this.__1__state = 2; } this.__m__Finally1e(); continue; } } this._moduleShortName_5__15 = Path.GetFileNameWithoutExtension(this._modulePath_5__e); this._exportedCommands_5__16 = AnalysisCache.GetExportedCommands(this._modulePath_5__e, false, this.context); if (this._exportedCommands_5__16 != null) { this._tempModuleInfo_5__11 = new PSModuleInfo(this._moduleShortName_5__15, this._modulePath_5__e, null, null); if (InitialSessionState.IsEngineModule(this._moduleShortName_5__15)) { this._tempModuleInfo_5__11.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID)); } this.__7__wrap1f = this._exportedCommands_5__16.Keys.GetEnumerator(); this.__1__state = 4; while (this.__7__wrap1f.MoveNext()) { this._exportedCommand_5__17 = this.__7__wrap1f.Current; if (this._commandPattern_5__b.IsMatch(this._exportedCommand_5__17)) { this.__7__wrap21 = this._exportedCommands_5__16[this._exportedCommand_5__17].GetEnumerator(); this.__1__state = 5; while (this.__7__wrap21.MoveNext()) { this._commandType_5__18 = this.__7__wrap21.Current; this._shouldExportCommand_5__19 = true; if ((this.context.InitialSessionState != null) && (this.commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry entry in this.context.InitialSessionState.Commands[this._exportedCommand_5__17]) { string b = null; if (entry.Module != null) { b = entry.Module.Name; } else if (entry.PSSnapIn != null) { b = entry.PSSnapIn.Name; } if (string.Equals(this._moduleShortName_5__15, b, StringComparison.OrdinalIgnoreCase) && (entry.Visibility == SessionStateEntryVisibility.Private)) { this._shouldExportCommand_5__19 = false; } } } if (!this._shouldExportCommand_5__19) { continue; } this._current_5__1a = null; switch (this._commandType_5__18) { case CommandTypes.Alias: this._current_5__1a = new AliasInfo(this._exportedCommand_5__17, null, this.context); break; case CommandTypes.Function: this._current_5__1a = new FunctionInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context); break; case CommandTypes.Cmdlet: this._current_5__1a = new CmdletInfo(this._exportedCommand_5__17, null, null, null, this.context); break; case CommandTypes.Workflow: this._current_5__1a = new WorkflowInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context); break; } if (this._current_5__1a != null) { this._current_5__1a.SetModule(this._tempModuleInfo_5__11); } this.__2__current = this._current_5__1a; this.__1__state = 7; return(true); Label_060F: this.__1__state = 5; } this.__m__Finally22(); } } this.__m__Finally20(); } } this.__m__Finally1c(); } } return(false); } finally { (this as IDisposable).Dispose(); } }
public void OnGUI() { #region Events if (EditorWindow.focusedWindow == this) { Event e = Event.current; // the current event switch (e.type) { //this Event makes it posible todo Copy and Paste case EventType.ValidateCommand: //Debug.Log("CommandName: " + e.commandName); if (e.commandName == "Paste") { currentLine.Append(clipboard); // paste from clipboard } else if (e.commandName == "Copy") { clipboard = currentLine.ToString(); // set new clipboard } e.Use(); // use the event Repaint(); break; case EventType.KeyDown: switch (e.keyCode) { case KeyCode.Backspace: if (currentLine.Length > 0) // fixes so you cant remove nothing { currentLine = currentLine.Remove(currentLine.Length - 1, 1); } break; case KeyCode.Return: if (currentLine.Length == 0) // dont execute nothing, and/or make a new empty line { return; } previousCommands.Add("> " + currentLine.ToString()); CommandDiscovery.Build().Invoke(currentLine.ToString()); // sorry for changing, but i added a function that gets All the Project Assemblies inside this unity project, but if we cant get an Assembly we can manualy add it currentLine = currentLine.Remove(0, currentLine.Length); if (ScrollToBottomOnNewCommand) // scrolls the scrollView to the bottom so we can see what we executed :) { scrollPosition = new Vector2(scrollPosition.x, float.MaxValue); // <- this actualy works :D } break; default: currentLine = currentLine.Append(e.character); if (ScrollToBottomOnNewCommand) // scrolls the scrollView to the bottom so we can see what we typed :) { scrollPosition = new Vector2(scrollPosition.x, float.MaxValue); // <- this actualy works :D } break; } //Debug.Log("Current Keycode: " + Event.current.keyCode.ToString() + " Character: " + // Event.current.character); currentLine.Replace("\n", ""); currentLine.Replace("\0", ""); e.Use(); this.Repaint(); break; case EventType.KeyUp: e.Use(); break; } } #endregion #region GUILayout //GUI.skin = layout; //globaly sets the GUISkin #region Mini ToolBar //TODO: make the toolbar using the custom GUISkin, instead of default unity EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); if (GUILayout.Button("Clear", EditorStyles.toolbarButton, GUILayout.Width(45f))) { ClearLog(); } if (GUILayout.Button("Save", EditorStyles.toolbarButton, GUILayout.Width(45f))) { //save not added atm } ConsoleLogEnabled = GUILayout.Toggle(ConsoleLogEnabled, "Console Log", EditorStyles.toolbarButton, GUILayout.Width(100f)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); #endregion #region ScrollArea Rect ContentRect = new Rect(0, 16, position.width, position.height - 16); // 16 + 16 = 32 and 3 from the left. GUILayout.BeginArea(ContentRect); scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true, this.layout.horizontalScrollbar, this.layout.verticalScrollbar, this.layout.scrollView); GUILayout.BeginVertical(); foreach (var previous in previousCommands) { GUILayout.Label(previous, this.layout.label); } GUILayout.Label("> " + currentLine.ToString(), this.layout.label); GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndArea(); #endregion #endregion }
private void AccumulateMatchingCommands(IEnumerable <string> commandNames) { SearchResolutionOptions none = SearchResolutionOptions.None; if (this.All != false) { none = SearchResolutionOptions.SearchAllScopes; } if ((this.CommandType & CommandTypes.Alias) != 0) { none |= SearchResolutionOptions.ResolveAliasPatterns; } if ((this.CommandType & (CommandTypes.Workflow | CommandTypes.Filter | CommandTypes.Function)) != 0) { none |= SearchResolutionOptions.ResolveFunctionPatterns; } foreach (string str in commandNames) { try { string str2 = null; string pattern = str; bool flag = false; if ((str.IndexOf('\\') > 0) && (str.Split(new char[] { '\\' }).Length == 2)) { string[] strArray = str.Split(new char[] { '\\' }, 2); str2 = strArray[0]; pattern = strArray[1]; flag = true; } if ((this.Module.Length == 1) && !WildcardPattern.ContainsWildcardCharacters(this.Module[0])) { str2 = this.Module[0]; } bool isPattern = WildcardPattern.ContainsWildcardCharacters(pattern); if (isPattern) { none |= SearchResolutionOptions.CommandNameIsPattern; } int currentCount = 0; bool flag3 = this.FindCommandForName(none, str, isPattern, true, ref currentCount); if (!flag3 || isPattern) { if (!isPattern || !string.IsNullOrEmpty(str2)) { string commandName = str; if (!flag && !string.IsNullOrEmpty(str2)) { commandName = str2 + @"\" + str; } try { CommandDiscovery.LookupCommandInfo(commandName, base.MyInvocation.CommandOrigin, base.Context); } catch (CommandNotFoundException) { } flag3 = this.FindCommandForName(none, str, isPattern, false, ref currentCount); } else if ((this.ListImported == false) && ((this.TotalCount < 0) || (currentCount < this.TotalCount))) { foreach (CommandInfo info in ModuleUtils.GetMatchingCommands(pattern, base.Context, base.MyInvocation.CommandOrigin, true)) { CommandInfo current = info; if ((this.IsCommandMatch(ref current) && !this.IsCommandInResult(current)) && this.IsParameterMatch(current)) { this.accumulatedResults.Add(current); currentCount++; if ((this.TotalCount >= 0) && (currentCount >= this.TotalCount)) { break; } } } } } if (!flag3 && !isPattern) { CommandNotFoundException replaceParentContainsErrorRecordException = new CommandNotFoundException(str, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]); base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException)); } } catch (CommandNotFoundException exception2) { base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2)); } } }
protected override void BeginProcessing() { string str; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.ErrorDialog = false; try { CommandInfo commandInfo = CommandDiscovery.LookupCommandInfo(this._path, CommandTypes.ExternalScript | CommandTypes.Application, SearchResolutionOptions.None, CommandOrigin.Internal, base.Context); processStartInfo.FileName = commandInfo.Definition; } catch (CommandNotFoundException commandNotFoundException) { processStartInfo.FileName = this._path; } if (this._argumentlist != null) { StringBuilder stringBuilder = new StringBuilder(); string[] strArrays = this._argumentlist; for (int i = 0; i < (int)strArrays.Length; i++) { string str1 = strArrays[i]; stringBuilder.Append(str1); stringBuilder.Append(' '); } processStartInfo.Arguments = stringBuilder.ToString(); } if (this._workingdirectory == null) { processStartInfo.WorkingDirectory = this.ResolveFilePath(base.SessionState.Path.CurrentFileSystemLocation.Path); } else { this._workingdirectory = this.ResolveFilePath(this._workingdirectory); if (Directory.Exists(this._workingdirectory)) { processStartInfo.WorkingDirectory = this._workingdirectory; } else { str = StringUtil.Format(ProcessResources.InvalidInput, "WorkingDirectory"); ErrorRecord errorRecord = new ErrorRecord(new DirectoryNotFoundException(str), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); return; } } if (!base.ParameterSetName.Equals("Default")) { if (base.ParameterSetName.Equals("UseShellExecute")) { processStartInfo.UseShellExecute = true; if (this._verb != null) { processStartInfo.Verb = this._verb; } processStartInfo.WindowStyle = this._windowstyle; } } else { if (this.IsDefaultSetParameterSpecified) { processStartInfo.UseShellExecute = false; } if (this._UseNewEnvironment) { processStartInfo.EnvironmentVariables.Clear(); this.LoadEnvironmentVariable(processStartInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); this.LoadEnvironmentVariable(processStartInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); } if (!this._nonewwindow || !this._windowstyleSpecified) { if (this._nonewwindow) { processStartInfo.CreateNoWindow = this._nonewwindow; } processStartInfo.WindowStyle = this._windowstyle; processStartInfo.LoadUserProfile = this._loaduserprofile; if (this._credential != null) { NetworkCredential networkCredential = this._credential.GetNetworkCredential(); processStartInfo.UserName = networkCredential.UserName; if (!string.IsNullOrEmpty(networkCredential.Domain)) { processStartInfo.Domain = networkCredential.Domain; } else { processStartInfo.Domain = "."; } processStartInfo.Password = this._credential.Password; } if (this._redirectstandardinput != null) { this._redirectstandardinput = this.ResolveFilePath(this._redirectstandardinput); if (!File.Exists(this._redirectstandardinput)) { str = StringUtil.Format(ProcessResources.InvalidInput, string.Concat("RedirectStandardInput '", this.RedirectStandardInput, "'")); ErrorRecord errorRecord1 = new ErrorRecord(new FileNotFoundException(str), "FileNotFoundException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); return; } } if (this._redirectstandardinput != null && this._redirectstandardoutput != null) { this._redirectstandardinput = this.ResolveFilePath(this._redirectstandardinput); this._redirectstandardoutput = this.ResolveFilePath(this._redirectstandardoutput); if (this._redirectstandardinput.Equals(this._redirectstandardoutput, StringComparison.CurrentCultureIgnoreCase)) { str = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardOutput"); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); return; } } if (this._redirectstandardinput != null && this._redirectstandarderror != null) { this._redirectstandardinput = this.ResolveFilePath(this._redirectstandardinput); this._redirectstandarderror = this.ResolveFilePath(this._redirectstandarderror); if (this._redirectstandardinput.Equals(this._redirectstandarderror, StringComparison.CurrentCultureIgnoreCase)) { str = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardError"); ErrorRecord errorRecord3 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); return; } } if (this._redirectstandardoutput != null && this._redirectstandarderror != null) { this._redirectstandarderror = this.ResolveFilePath(this._redirectstandarderror); this._redirectstandardoutput = this.ResolveFilePath(this._redirectstandardoutput); if (this._redirectstandardoutput.Equals(this._redirectstandarderror, StringComparison.CurrentCultureIgnoreCase)) { str = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardOutput", "RedirectStandardError"); ErrorRecord errorRecord4 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord4); return; } } } else { str = StringUtil.Format(ProcessResources.ContradictParametersSpecified, "-NoNewWindow", "-WindowStyle"); ErrorRecord errorRecord5 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord5); return; } } Process process = this.start(processStartInfo); if (this._passthru.IsPresent) { if (process == null) { str = StringUtil.Format(ProcessResources.CannotStarttheProcess, new object[0]); ErrorRecord errorRecord6 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.ThrowTerminatingError(errorRecord6); } else { base.WriteObject(process); } } if (this._wait.IsPresent) { if (process == null) { str = StringUtil.Format(ProcessResources.CannotStarttheProcess, new object[0]); ErrorRecord errorRecord7 = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.ThrowTerminatingError(errorRecord7); } else { process.EnableRaisingEvents = true; if (!process.HasExited) { ProcessCollection processCollection = new ProcessCollection(process); processCollection.Start(); processCollection.WaitOne(); return; } } } }