} // end _Dump()

            public void Reload(CommandInvocationIntrinsics invokeCommand,
                               IList <string> appendScripts,
                               IList <string> prependScripts,
                               IPipelineCallback pipe)
            {
                m_scriptLoader.Reload(invokeCommand, appendScripts, prependScripts, "converter info", pipe);
            } // end Reload()
示例#2
0
        public static Collection <PSObject> InvokeRestCommand(
            this CommandInvocationIntrinsics commandInvocation,
            Uri uri,
            WebRequestMethod method,
            object body,
            IDictionary headers
            )
        {
            var powershellParams = new Dictionary <object, object> {
                { nameof(uri), uri },
                { nameof(method), method },
                { nameof(body), body },
                { nameof(headers), headers }
            };

            var paramString = GeneralUtils.FormatPowerShellParams(powershellParams);
            var scriptBlock = $"Invoke-RestMethod {paramString}";

            return(commandInvocation.InvokeScript(
                       scriptBlock,
                       false,
                       System.Management.Automation.Runspaces.PipelineResultTypes.Output,
                       null,
                       null
                       ));
        }
示例#3
0
            } // end Dump()

            internal void Reload(CommandInvocationIntrinsics invokeCommand,
                                 IList <string> appendScripts,
                                 IList <string> prependScripts,
                                 IPipelineCallback pipe)
            {
                m_scriptLoader.Reload(invokeCommand, appendScripts, prependScripts, "format data", pipe);
            } // end Reload()
        //public SymbolDetails GetSymbolDetails()

        #endregion

        #region Private Fields

        /// <summary>
        /// Gets all aliases found in the runspace
        /// </summary>
        private async Task GetAliases()
        {
            if (!this.areAliasesLoaded)
            {
                RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandle();

                CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand;
                IEnumerable <CommandInfo>   aliases       = invokeCommand.GetCommands("*", CommandTypes.Alias, true);

                runspaceHandle.Dispose();

                foreach (AliasInfo aliasInfo in aliases)
                {
                    if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition))
                    {
                        CmdletToAliasDictionary.Add(aliasInfo.Definition, new List <String>()
                        {
                            aliasInfo.Name
                        });
                    }
                    else
                    {
                        CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name);
                    }

                    AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition);
                }

                this.areAliasesLoaded = true;
            }
        }
示例#5
0
 public PowerShellPackageRepository(CommandInvocationIntrinsics commandInvocationIntrinsics)
 {
     if (commandInvocationIntrinsics == null)
     {
         throw new ArgumentNullException("commandInvocationIntrinsics");
     }
     _commandInvocationIntrinsics = commandInvocationIntrinsics;
 }
示例#6
0
        } // end ProcessRecord()

        internal static Collection <PSObject> InvokeScript(CommandInvocationIntrinsics invokeCommand,
                                                           ScriptBlock scriptBlock,
                                                           bool useNewChildScope)
        {
            return(invokeCommand.InvokeScript(useNewChildScope,
                                              scriptBlock,
                                              null,
                                              null));
        } // end InvokeScript
        public static void ReloadModules(CommandInvocationIntrinsics invokeCommand, params PSModuleInfo[] moduleInfos)
        {
            var modulePaths = GetCommaSeparatedQuotedList(moduleInfos.Select(GetModulePath).ToArray());

            if (!String.IsNullOrEmpty(modulePaths))
            {
                var command = $"Import-Module -Name {modulePaths} -Force";
                invokeCommand.NewScriptBlock(command).Invoke();
            }
        }
        public static PSModuleInfo[] GetModules(CommandInvocationIntrinsics invokeCommand, bool listAvailable = false, params string[] moduleNames)
        {
            string nameParameter          = $"-Name { (moduleNames != null && moduleNames.Any() ? GetCommaSeparatedQuotedList(moduleNames) : "Microsoft.Graph*" )}";
            string listAvailableParameter = listAvailable ? " -ListAvailable" : String.Empty;
            string command = $"Get-Module {nameParameter}{listAvailableParameter}";
            Collection <PSObject> modules = listAvailable ? PowerShell.Create().AddScript(command).Invoke <PSObject>() : invokeCommand.NewScriptBlock(command).Invoke();

            return(modules != null?modules.Select(m => m?.BaseObject as PSModuleInfo).Where(m => m != null).ToArray() : new PSModuleInfo[]
            {
            });
        }
示例#9
0
 public static void Reload(CommandInvocationIntrinsics invokeCommand,
                           IList <string> appendScripts,
                           IList <string> prependScripts,
                           IPipelineCallback pipe)
 {
     if (null == pipe)
     {
         pipe = new DummyPipelineCallback();
     }
     _Singleton.Reload(invokeCommand, appendScripts, prependScripts, pipe);
 }
示例#10
0
        internal static PSModuleInfo[] GetModules(CommandInvocationIntrinsics invokeCommand, bool listAvailable = false, params string[] moduleNames)
        {
            var command = "Get-Module";

            command += moduleNames != null && moduleNames.Any() ? $" -Name {CommaSeparatedQuotedList(moduleNames)}" : String.Empty;
            command += listAvailable ? " -ListAvailable" : String.Empty;
            var modules = listAvailable ? Pwsh.Create().AddScript(command).Invoke <PSObject>() : invokeCommand.NewScriptBlock(command).Invoke();

            return(modules != null?modules.Select(m => m?.BaseObject as PSModuleInfo).Where(m => m != null).ToArray() : new PSModuleInfo[]
            {
            });
        }
示例#11
0
        /// <summary>
        /// Gets all aliases found in the runspace
        /// </summary>
        private async Task GetAliases()
        {
            if (_areAliasesLoaded)
            {
                return;
            }

            try
            {
                RunspaceHandle runspaceHandle =
                    await _powerShellContext.GetRunspaceHandle(
                        new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token);

                CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand;
                IEnumerable <CommandInfo>   aliases       = invokeCommand.GetCommands("*", CommandTypes.Alias, true);

                runspaceHandle.Dispose();

                foreach (AliasInfo aliasInfo in aliases)
                {
                    if (!_cmdletToAliasDictionary.ContainsKey(aliasInfo.Definition))
                    {
                        _cmdletToAliasDictionary.Add(aliasInfo.Definition, new List <String> {
                            aliasInfo.Name
                        });
                    }
                    else
                    {
                        _cmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name);
                    }

                    _aliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition);
                }

                _areAliasesLoaded = true;
            }
            catch (PSNotSupportedException e)
            {
                _logger.Write(
                    LogLevel.Warning,
                    $"Caught PSNotSupportedException while attempting to get aliases from remote session:\n\n{e.ToString()}");

                // Prevent the aliases from being fetched again - no point if the remote doesn't support InvokeCommand.
                _areAliasesLoaded = true;
            }
            catch (TaskCanceledException)
            {
                // The wait for a RunspaceHandle has timed out, skip aliases for now
            }
        }
            public ActionQueue(CommandInvocationIntrinsics invokeCommand, BlockingCollection <Action> q)
            {
                if (null == invokeCommand)
                {
                    throw new ArgumentNullException("invokeCommand");
                }

                if (null == q)
                {
                    throw new ArgumentNullException("q");
                }

                m_invokeCommand = invokeCommand;
                m_q             = q;
                m_oldQ          = DbgProvider.CurrentActionQueue;

                DbgProvider.CurrentActionQueue = this;
            } // end constructor
        /// <summary>
        /// Gets all aliases found in the runspace
        /// </summary>
        private async Task GetAliases()
        {
            if (!this.areAliasesLoaded)
            {
                try
                {
                    RunspaceHandle runspaceHandle =
                        await this.powerShellContext.GetRunspaceHandle(
                            new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token);

                    CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand;
                    IEnumerable <CommandInfo>   aliases       = invokeCommand.GetCommands("*", CommandTypes.Alias, true);

                    runspaceHandle.Dispose();

                    foreach (AliasInfo aliasInfo in aliases)
                    {
                        if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition))
                        {
                            CmdletToAliasDictionary.Add(aliasInfo.Definition, new List <String>()
                            {
                                aliasInfo.Name
                            });
                        }
                        else
                        {
                            CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name);
                        }

                        AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition);
                    }

                    this.areAliasesLoaded = true;
                }
                catch (TaskCanceledException)
                {
                    // The wait for a RunspaceHandle has timed out, skip aliases for now
                }
            }
        }
示例#14
0
 public static void RunScript(CommandInvocationIntrinsics cii, string script)
 => RunScript <PSObject>(cii, script);
示例#15
0
 public static IEnumerable <T> RunScript <T>(CommandInvocationIntrinsics cii, string script)
 => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType <T>();
示例#16
0
 public static IEnumerable <T> RunScript <T>(CommandInvocationIntrinsics cii, string script) where T : class
 => cii.NewScriptBlock(script).Invoke().Select(o => o?.BaseObject as T).Where(m => m != null);
 public DefaultPowershellCommandInvoker(CommandInvocationIntrinsics invokeCommand, InvocationInfo myInvocation)
 {
     _invokeCommand = invokeCommand;
     _myInvocation  = myInvocation;
 }
示例#18
0
 internal ADPasswordUtil(CommandInvocationIntrinsics invokeCommand)
 {
     this._invokeCommand = invokeCommand;
 }
        } // end AddSourceFile()

        /// <summary>
        ///    Re-runs the list of registered source files, after clearing the internal
        ///    list of registered source files.
        /// </summary>
        /// <remarks>
        ///    It is assumed that when a script runs, it calls some command that causes
        ///    AddSourceFile to be called, thereby re-registering itself. If a script
        ///    produces an error, however, it is kept in the list of source files, so that
        ///    a user can fix the error and call this again without re-registering the
        ///    script.
        ///
        ///    If a script in appendScripts is already in the list, no change is made (the
        ///    script does not get added again to the end of the list, or moved). If a
        ///    script in prependScripts is already in the list, it gets moved from its
        ///    original position to the front.
        /// </remarks>
        public void Reload(CommandInvocationIntrinsics invokeCommand,
                           IList <string> appendScripts,
                           IList <string> prependScripts,
                           string dataDisplayName,  // for verbose messages
                           IPipelineCallback pipe)
        {
            if (null == pipe)
            {
                throw new ArgumentNullException("pipe");
            }

            pipe.WriteVerbose("Dumping old {0}...", dataDisplayName);
            m_DumpContent();

            if (null != appendScripts)
            {
                foreach (var newScript in appendScripts)
                {
                    // Unlike the prepend case, here we don't change the position of the
                    // script in the list if it's already in it.
                    if ((null != newScript) && m_sourceFilesSet.Add(newScript))
                    {
                        pipe.WriteVerbose("Appending script: {0}", newScript);
                        m_sourceFiles.AddLast(newScript);
                    }
                }
            }

            if (null != prependScripts)
            {
                foreach (var newScript in prependScripts)
                {
                    if (null != newScript)
                    {
                        if (m_sourceFilesSet.Remove(newScript))
                        {
                            pipe.WriteVerbose("Prepending (moving) script: {0}", newScript);
                            m_sourceFiles.Remove(newScript);
                        }
                        else
                        {
                            pipe.WriteVerbose("Prepending script: {0}", newScript);
                        }

                        m_sourceFiles.AddFirst(newScript);
                    }
                }
            }

            // It's possible that there's conditional logic in the scripts that causes
            // different scripts to run, so we'd better clear out the existing source
            // files list (after making a copy).
            var oldSourceFiles = m_sourceFiles.ToArray();

            m_sourceFiles.Clear();
            m_sourceFilesSet.Clear();
            foreach (string sourceScript in oldSourceFiles)
            {
                try
                {
                    // If there are errors parsing the file, then it won't be run, and if
                    // it doesn't get run, something won't call AddSourceFile, and if it
                    // doesn't call AddSourceFile, we won't save the script file to run
                    // again next time someone calls Reload. So we'll save the script name
                    // in the "files to run" /now/, instead of later.
                    pipe.WriteVerbose("Adding {0} from: {1}", dataDisplayName, sourceScript);
                    if (AddSourceFile(sourceScript))
                    {
                        ScriptBlockAst ast = InvokeScriptCommand.LoadScript(sourceScript);
                        // TODO: should I do anything with any output?
                        InvokeScriptCommand.InvokeScript(invokeCommand, ast.GetScriptBlock(), true);
                    }
                    else
                    {
                        // I don't think it should be possible to get here.
                        Util.Fail("How did we get here?");
                    }
                }
                catch (DbgProviderException dpe)
                {
                    pipe.WriteError(dpe.ErrorRecord);
                }
                catch (RuntimeException re)
                {
                    pipe.WriteError(re.ErrorRecord);
                }
            }
        } // end Reload()
 public static string[] GetProfiles(CommandInvocationIntrinsics invokeCommand, bool listAvailable = false, params string[] moduleNames)
 {
     return(GetModules(invokeCommand, listAvailable, moduleNames).SelectMany(GetProfiles).Distinct().ToArray());
 }