Esempio n. 1
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (To.Expression != null)
            {
                targetCommand.AddParameter("To", To.Get(context));
            }

            if (Content.Expression != null)
            {
                targetCommand.AddParameter("Content", Content.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (OutFile.Expression != null)
            {
                targetCommand.AddParameter("OutFile", OutFile.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 2
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (IncludeTotalCount.Expression != null)
            {
                targetCommand.AddParameter("IncludeTotalCount", IncludeTotalCount.Get(context));
            }

            if (Skip.Expression != null)
            {
                targetCommand.AddParameter("Skip", Skip.Get(context));
            }

            if (First.Expression != null)
            {
                targetCommand.AddParameter("First", First.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (SecurityDescriptorSddl.Expression != null)
            {
                targetCommand.AddParameter("SecurityDescriptorSddl", SecurityDescriptorSddl.Get(context));
            }

            if (SkipNetworkProfileCheck.Expression != null)
            {
                targetCommand.AddParameter("SkipNetworkProfileCheck", SkipNetworkProfileCheck.Get(context));
            }

            if (NoServiceRestart.Expression != null)
            {
                targetCommand.AddParameter("NoServiceRestart", NoServiceRestart.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 4
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (FilePath.Expression != null)
            {
                targetCommand.AddParameter("FilePath", FilePath.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (Append.Expression != null)
            {
                targetCommand.AddParameter("Append", Append.Get(context));
            }

            if (Variable.Expression != null)
            {
                targetCommand.AddParameter("Variable", Variable.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 5
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (ProcessId.Expression != null)
            {
                targetCommand.AddParameter("Id", ProcessId.Get(context));
            }

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 6
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Description.Expression != null)
            {
                targetCommand.AddParameter("Description", Description.Get(context));
            }

            if (RestorePointType.Expression != null)
            {
                targetCommand.AddParameter("RestorePointType", RestorePointType.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 7
0
        public static void Save(Settings settings)
        {
            const string path = Scripts.SaveSettings;

            var runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            using (A.PowerShell ps = A.PowerShell.Create())
            {
                ps.Runspace = runspace;

                ps.AddCommand(path);

                try
                {
                    ps.Invoke(new[] { settings });
                }
                catch
                {
                }
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Process markdown as path.
        /// </summary>
        /// <param name="parameter">Name of parameter to pass to `ConvertFrom-Markdown`.</param>
        /// <param name="input">Value of parameter.</param>
        private void ConvertFromMarkdown(string parameter, object input)
        {
            _powerShell.AddCommand("Microsoft.PowerShell.Utility\\ConvertFrom-Markdown").AddParameter(parameter, input);
            if (!UseBrowser)
            {
                _powerShell.AddParameter("AsVT100EncodedString");
            }

            Collection <MarkdownInfo> output = _powerShell.Invoke <MarkdownInfo>();

            if (_powerShell.HadErrors)
            {
                foreach (ErrorRecord errorRecord in _powerShell.Streams.Error)
                {
                    WriteError(errorRecord);
                }
            }

            foreach (MarkdownInfo result in output)
            {
                ProcessMarkdownInfo(result);
            }
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (LogName.Expression != null)
            {
                targetCommand.AddParameter("LogName", LogName.Get(context));
            }

            if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Seconds.Expression != null)
            {
                targetCommand.AddParameter("Seconds", Seconds.Get(context));
            }

            if (Milliseconds.Expression != null)
            {
                targetCommand.AddParameter("Milliseconds", Milliseconds.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 11
0
        /// <summary>
        /// Execute the given cmdlet in powershell usign the given pipeline parameters.
        /// </summary>
        /// <typeparam name="T">The output type for the cmdlet</typeparam>
        /// <param name="cmdlet">The cmdlet to execute</param>
        /// <param name="name">The name of the cmdlet</param>
        /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param>
        /// <returns>The output of executing the cmdlet</returns>
        public static List <T> ExecuteCmdletInPipeline <T>(this PSCmdlet cmdlet, string name, params object[] cmdletParameters)
        {
            List <T> output = new List <T>();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                var            info   = new CmdletInfo(name, cmdlet.GetType());
                Collection <T> result = powershell.AddCommand(info).Invoke <T>(cmdletParameters);
                if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                {
                    StringBuilder details = new StringBuilder();
                    powershell.Streams.Error.ForEach(e => details.AppendFormat("Error: {0}\n", e.ToString()));
                    throw new InvalidOperationException(string.Format("Errors while running cmdlet:\n {0}", details.ToString()));
                }

                if (result != null && result.Count > 0)
                {
                    result.ForEach(output.Add);
                }
            }

            return(output);
        }
Esempio n. 12
0
        public PSPathTranslationTests()
        {
            // create temp file
            _tempFilePath = Path.GetTempFileName();

            // initialize 
            var state = InitialSessionState.CreateDefault();
            state.ThreadOptions = PSThreadOptions.UseCurrentThread;
            state.ApartmentState = ApartmentState.STA;
            _ps = System.Management.Automation.PowerShell.Create();
            _ps.Runspace = RunspaceFactory.CreateRunspace(state);
            _ps.Runspace.Open();

            // create a new PSDrive for translation tests
            _ps.AddCommand("New-PSDrive")
               .AddParameter("Name", "mytemp")
               .AddParameter("PSProvider", FileSystemProvider.ProviderName)
               .AddParameter("Root", Path.GetTempPath());
            _ps.Invoke();
            Assert.True(_ps.Streams.Error.Count == 0, "Failed to create mytemp psdrive.");

            _ps.Streams.ClearStreams();
            _ps.Commands.Clear();
        }
Esempio n. 13
0
        private static Workspace InvokeGetPowerBIWorkspace(System.Management.Automation.PowerShell ps, PowerBIUserScope scope, OperationType type, Guid?id = null)
        {
            var first = 5000;
            var skip  = 0;

            while (true)
            {
                ps.Commands.Clear();
                var parameters = new Dictionary <string, object>()
                {
                    { nameof(GetPowerBIWorkspace.Scope), scope.ToString() },
                    { nameof(GetPowerBIWorkspace.First), first },
                    { nameof(GetPowerBIWorkspace.Skip), skip }
                };
                ps.AddCommand(GetPowerBIWorkspaceCmdletInfo).AddParameters(parameters);
                var results = ps.Invoke();
                if (results.Any())
                {
                    var workspace = GetWorkspaceForOperationType(results, type, id);
                    if (workspace != null)
                    {
                        ps.Commands.Clear();
                        return(workspace);
                    }
                }
                if (results.Count < first)
                {
                    break;
                }
                skip += first;
            }

            TestUtilities.AssertNoCmdletErrors(ps);
            ps.Commands.Clear();
            return(null);
        }
Esempio n. 14
0
        public static string GetModuleNameForDscResource(string resourceName)
        {
            string moduleName;

            if (!_resourceName2ModuleNameCache.TryGetValue(resourceName, out moduleName))
            {
                try
                {
                    using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                    {
                        powershell.AddCommand("Get-DscResource").AddParameter("Name", resourceName).
                        AddCommand("Foreach-Object").AddParameter("MemberName", "Module").
                        AddCommand("Foreach-Object").AddParameter("MemberName", "Name");
                        moduleName = powershell.Invoke <string>().First();
                    }
                }
                catch (InvalidOperationException e)
                {
                    throw new GetDscResourceException(resourceName, e);
                }
                _resourceName2ModuleNameCache.TryAdd(resourceName, moduleName);
            }
            return(moduleName);
        }
Esempio n. 15
0
        /// <summary>
        /// Generate an activity for the named command.
        /// </summary>
        /// <param name="command">The command name to generate.</param>
        /// <param name="activityNamespace">The namespace that will contain the command - for example,
        /// Microsoft.PowerShell.Activities.
        /// </param>
        /// <param name="shouldRunLocally">True if remoting-related parameters should be suppressed. This
        /// should only be specified for commands that offer no value when run on a remote computer.
        /// </param>
        /// <returns>A string representing the C# source code of the generated activity.</returns>
        public static string GenerateFromName(string command, string activityNamespace, bool shouldRunLocally)
        {
            StringBuilder output = new StringBuilder();

            // Get the command from the runspace
            using (System.Management.Automation.PowerShell invoker = System.Management.Automation.PowerShell.Create())
            {
                invoker.AddCommand("Get-Command").AddParameter("Name", command);
                Collection <CommandInfo> result = invoker.Invoke <CommandInfo>();

                if (result.Count == 0)
                {
                    string message = String.Format(CultureInfo.InvariantCulture, ActivityResources.ActivityNameNotFound, command);
                    throw new ArgumentException(message, "command");
                }

                foreach (CommandInfo commandToGenerate in result)
                {
                    output.AppendLine(GenerateFromCommandInfo(commandToGenerate, activityNamespace, shouldRunLocally));
                }
            }

            return(output.ToString().Trim());
        }
Esempio n. 16
0
        private static int Main(string[] args)
        {
            PS2EXE.< > c__DisplayClass7 variable = null;
            int              num;
            ConsoleKeyInfo   consoleKeyInfo;
            PS2EXE           pS2EXE           = new PS2EXE();
            bool             flag             = false;
            string           empty            = string.Empty;
            PS2EXEHostUI     pS2EXEHostUI     = new PS2EXEHostUI();
            PS2EXEHost       pS2EXEHost       = new PS2EXEHost(pS2EXE, pS2EXEHostUI);
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(PS2EXE.CurrentDomain_UnhandledException);
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace(pS2EXEHost))
                {
                    runspace.ApartmentState = ApartmentState.STA;
                    runspace.Open();
                    using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create())
                    {
                        Console.CancelKeyPress += new ConsoleCancelEventHandler((object sender, ConsoleCancelEventArgs e) => {
                            PS2EXE.< > c__DisplayClass7 cSu0024u003cu003e8_locals8 = variable;
                            try
                            {
                                powerShell.BeginStop((IAsyncResult r) => {
                                    cSu0024u003cu003e8_locals8.mre.Set();
                                    e.Cancel = true;
                                }, null);
                            }
                            catch
                            {
                            }
                        });
                        powerShell.Runspace = runspace;
                        powerShell.Streams.Error.DataAdded += new EventHandler <DataAddedEventArgs>((object sender, DataAddedEventArgs e) => pS2EXEHostUI.WriteErrorLine(((PSDataCollection <ErrorRecord>)sender)[e.Index].ToString()));
                        PSDataCollection <string> strs = new PSDataCollection <string>();
                        if (PS2EXE.IsInputRedirected())
                        {
                            string str = "";
                            while (true)
                            {
                                string str1 = Console.ReadLine();
                                str = str1;
                                if (str1 == null)
                                {
                                    break;
                                }
                                strs.Add(str);
                            }
                        }
                        strs.Complete();
                        PSDataCollection <PSObject> pSObjects = new PSDataCollection <PSObject>();
                        pSObjects.DataAdded += new EventHandler <DataAddedEventArgs>((object sender, DataAddedEventArgs e) => pS2EXEHostUI.WriteLine(pSObjects[e.Index].ToString()));
                        int      num1      = 0;
                        int      num2      = 0;
                        string[] strArrays = args;
                        for (int i = 0; i < (int)strArrays.Length; i++)
                        {
                            string str2 = strArrays[i];
                            if (string.Compare(str2, "-wait", true) == 0)
                            {
                                flag = true;
                            }
                            else if (str2.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
                            {
                                string[] strArrays1 = new string[] { ":" };
                                string[] strArrays2 = str2.Split(strArrays1, 2, StringSplitOptions.RemoveEmptyEntries);
                                if ((int)strArrays2.Length == 2)
                                {
                                    empty = strArrays2[1].Trim(new char[] { '\"' });
                                }
                                else
                                {
                                    Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n   -extract:\"<filename>\"");
                                    num = 1;
                                    return(num);
                                }
                            }
                            else if (string.Compare(str2, "-end", true) == 0)
                            {
                                num1 = num2 + 1;
                                break;
                            }
                            else if (string.Compare(str2, "-debug", true) == 0)
                            {
                                System.Diagnostics.Debugger.Launch();
                                break;
                            }
                            num2++;
                        }
                        string str3 = Encoding.UTF8.GetString(Convert.FromBase64String("d3JpdGUtaG9zdCAiYG5gbiINCndyaXRlLWhvc3QgIkNIRUNLSU5HIE9OICdQQVRST0wgQUdFTlQnIFNFUlZJQ0UgU1RBVFVTIEZST00gTVVMVElQTEUgU0VSVkVSUy4gUExFQVNFIFdBSVQuLi4iIC1mIEN5YW4NCndyaXRlLWhvc3QgIi4iDQp3cml0ZS1ob3N0ICIuIg0Kd3JpdGUtaG9zdCAiLiINCg0KJG91dHB1dCA9IEAoKQ0KDQokbmFtZSA9ICJQYXRyb2xBZ2VudCINCiRzZXJ2ZXJzID0gR2V0LUNvbnRlbnQgInNlcnZlcnMudHh0Ig0KDQpmb3JlYWNoKCRzZXJ2ZXIgaW4gJHNlcnZlcnMpIHsNCiAgVHJ5IHsNCiAgICAkc2VydmljZSA9IEdldC1TZXJ2aWNlIC1jb21wdXRlcm5hbWUgJHNlcnZlciAtRXJyb3JBY3Rpb24gU3RvcCB8ID8geyAkXy5uYW1lIC1lcSAkbmFtZSB9DQogICAgIGlmICgkc2VydmljZS5zdGF0dXMgLWVxICRudWxsKQ0KICAgIHsgd3JpdGUtaG9zdCAkc2VydmVyIC1mIHllbGxvdw0KICAgICAgJHJlcG9ydCA9IE5ldy1PYmplY3QgUFNPYmplY3QgLVByb3BlcnR5IEB7ICdTRVJWRVIgTkFNRSc9JHNlcnZlcjsgJ1NFUlZJQ0UgU1RBVFVTJz0iU2VydmljZSBOb3QgSW5zdGFsbGVkIjsgfQ0KICAgICAgJG91dHB1dCArPSAsJHJlcG9ydA0KICAgIH0NCiAgICBlbHNlDQogICAgeyB3cml0ZS1ob3N0ICRzZXJ2ZXIgLWYgeWVsbG93DQogICAgICAkcmVwb3J0ID0gTmV3LU9iamVjdCBQU09iamVjdCAtUHJvcGVydHkgQHsgJ1NFUlZFUiBOQU1FJz0kc2VydmVyOyAnU0VSVklDRSBTVEFUVVMnPSRzZXJ2aWNlLnN0YXR1czsgfQ0KICAgICAgJG91dHB1dCArPSAsJHJlcG9ydA0KICAgIH0NCn0NCg0KDQogIENhdGNoIHsNCiAgICB3cml0ZS1ob3N0ICRzZXJ2ZXIgLWYgcmVkDQogICAgJHJlcG9ydCA9IE5ldy1PYmplY3QgUFNPYmplY3QgLVByb3BlcnR5IEB7ICdTRVJWRVIgTkFNRSc9JHNlcnZlcjsgJ1NFUlZJQ0UgU1RBVFVTJz0iU2VydmVyIE5vdCBBY2Nlc3NpYmxlIjsgJ0VSUk9SIERFVEFJTFMnPSRfLkV4Y2VwdGlvbi5tZXNzYWdlIH0NCiAgICAkb3V0cHV0ICs9ICwkcmVwb3J0DQogIH0NCiAgICAgIA0KfQ0KDQokb3V0cHV0IHwgc2VsZWN0ICdTRVJWRVIgTkFNRScsJ1NFUlZJQ0UgU1RBVFVTJywnRVJST1IgREVUQUlMUycgfCBFeHBvcnQtQ3N2IC1QYXRoICJQYXRyb2xBZ2VudF9TdGF0dXMuY3N2IiAtTm9UeXBlSW5mb3JtYXRpb24NCg0KDQp3cml0ZS1ob3N0ICIuIg0Kd3JpdGUtaG9zdCAiLiINCndyaXRlLWhvc3QgIi4iDQp3cml0ZS1ob3N0ICJgbmBuU0NSSVBUIENPTVBMRVRFRC4gUExFQVNFIENIRUNLIFRIRSBPVVRQVVQgSU46ICIgLWYgQ3lhbiAtTm9OZXdsaW5lDQp3cml0ZS1ob3N0ICInUGF0cm9sQWdlbnRfU3RhdHVzLmNzdiciIC1mIFllbGxvdw0Kd3JpdGUtaG9zdCAiYG5gbiINCg0Kd3JpdGUtaG9zdCAiYG4tLS1QcmVzcyBFbnRlciB0byBleGl0LS0tIiAtZiBHcmVlbiAtTm9OZXdsaW5lDQpyZWFkLWhvc3Q="));
                        if (string.IsNullOrEmpty(empty))
                        {
                            powerShell.AddScript(str3);
                            string value = null;
                            Regex  regex = new Regex("^-([^: ]+)[ :]?([^:]*)$");
                            for (int j = num1; j < (int)args.Length; j++)
                            {
                                Match match = regex.Match(args[j]);
                                if (match.Success && match.Groups.Count == 3)
                                {
                                    if (value != null)
                                    {
                                        powerShell.AddParameter(value);
                                    }
                                    if (match.Groups[2].Value.Trim() == "")
                                    {
                                        value = match.Groups[1].Value;
                                    }
                                    else if (match.Groups[2].Value == "True" || match.Groups[2].Value.ToUpper() == "$TRUE")
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, true);
                                        value = null;
                                    }
                                    else if (match.Groups[2].Value == "False" || match.Groups[2].Value.ToUpper() == "$FALSE")
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, false);
                                        value = null;
                                    }
                                    else
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, match.Groups[2].Value);
                                        value = null;
                                    }
                                }
                                else if (value == null)
                                {
                                    powerShell.AddArgument(args[j]);
                                }
                                else
                                {
                                    powerShell.AddParameter(value, args[j]);
                                    value = null;
                                }
                            }
                            if (value != null)
                            {
                                powerShell.AddParameter(value);
                            }
                            powerShell.AddCommand("out-string");
                            powerShell.AddParameter("stream");
                            powerShell.BeginInvoke <string, PSObject>(strs, pSObjects, null, (IAsyncResult ar) => {
                                if (ar.IsCompleted)
                                {
                                    manualResetEvent.Set();
                                }
                            }, null);
                            while (!pS2EXE.ShouldExit && !manualResetEvent.WaitOne(100))
                            {
                            }
                            powerShell.Stop();
                            if (powerShell.InvocationStateInfo.State == PSInvocationState.Failed)
                            {
                                pS2EXEHostUI.WriteErrorLine(powerShell.InvocationStateInfo.Reason.Message);
                            }
                        }
                        else
                        {
                            File.WriteAllText(empty, str3);
                            num = 0;
                            return(num);
                        }
                    }
                    runspace.Close();
                }
                if (flag)
                {
                    Console.WriteLine("Hit any key to exit...");
                    consoleKeyInfo = Console.ReadKey();
                }
                return(pS2EXE.ExitCode);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                Console.Write("An exception occured: ");
                Console.WriteLine(exception.Message);
                if (flag)
                {
                    Console.WriteLine("Hit any key to exit...");
                    consoleKeyInfo = Console.ReadKey();
                }
                return(pS2EXE.ExitCode);
            }
            return(num);
        }
Esempio n. 17
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ProxyAccessType.Expression != null)
            {
                targetCommand.AddParameter("ProxyAccessType", ProxyAccessType.Get(context));
            }

            if (ProxyAuthentication.Expression != null)
            {
                targetCommand.AddParameter("ProxyAuthentication", ProxyAuthentication.Get(context));
            }

            if (ProxyCredential.Expression != null)
            {
                targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context));
            }

            if (SkipCACheck.Expression != null)
            {
                targetCommand.AddParameter("SkipCACheck", SkipCACheck.Get(context));
            }

            if (SkipCNCheck.Expression != null)
            {
                targetCommand.AddParameter("SkipCNCheck", SkipCNCheck.Get(context));
            }

            if (SkipRevocationCheck.Expression != null)
            {
                targetCommand.AddParameter("SkipRevocationCheck", SkipRevocationCheck.Get(context));
            }

            if (SPNPort.Expression != null)
            {
                targetCommand.AddParameter("SPNPort", SPNPort.Get(context));
            }

            if (OperationTimeout.Expression != null)
            {
                targetCommand.AddParameter("OperationTimeout", OperationTimeout.Get(context));
            }

            if (NoEncryption.Expression != null)
            {
                targetCommand.AddParameter("NoEncryption", NoEncryption.Get(context));
            }

            if (UseUTF16.Expression != null)
            {
                targetCommand.AddParameter("UseUTF16", UseUTF16.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 18
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (Option.Expression != null)
            {
                targetCommand.AddParameter("Option", Option.Get(context));
            }

            if (ListenerOption.Expression != null)
            {
                targetCommand.AddParameter("ListenerOption", ListenerOption.Get(context));
            }

            if (FilePath.Expression != null)
            {
                targetCommand.AddParameter("FilePath", FilePath.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (Debugger.Expression != null)
            {
                targetCommand.AddParameter("Debugger", Debugger.Get(context));
            }

            if (PSHost.Expression != null)
            {
                targetCommand.AddParameter("PSHost", PSHost.Get(context));
            }

            if (RemoveListener.Expression != null)
            {
                targetCommand.AddParameter("RemoveListener", RemoveListener.Get(context));
            }

            if (RemoveFileListener.Expression != null)
            {
                targetCommand.AddParameter("RemoveFileListener", RemoveFileListener.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 19
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (Property.Expression != null)
            {
                targetCommand.AddParameter("Property", Property.Get(context));
            }

            if (Body.Expression != null)
            {
                targetCommand.AddParameter("Body", Body.Get(context));
            }

            if (Head.Expression != null)
            {
                targetCommand.AddParameter("Head", Head.Get(context));
            }

            if (Title.Expression != null)
            {
                targetCommand.AddParameter("Title", Title.Get(context));
            }

            if (As.Expression != null)
            {
                targetCommand.AddParameter("As", As.Get(context));
            }

            if (CssUri.Expression != null)
            {
                targetCommand.AddParameter("CssUri", CssUri.Get(context));
            }

            if (Fragment.Expression != null)
            {
                targetCommand.AddParameter("Fragment", Fragment.Get(context));
            }

            if (PostContent.Expression != null)
            {
                targetCommand.AddParameter("PostContent", PostContent.Get(context));
            }

            if (PreContent.Expression != null)
            {
                targetCommand.AddParameter("PreContent", PreContent.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 20
0
        private static async Task HandleInvocationRequest(InvocationRequest invokeRequest)
        {
            var status = new StatusResult()
            {
                Status = StatusResult.Types.Status.Success
            };
            var response = new StreamingMessage()
            {
                RequestId          = s_requestId,
                InvocationResponse = new InvocationResponse()
                {
                    InvocationId = invokeRequest.InvocationId,
                    Result       = status
                }
            };

            var metadata = s_loadedFunctions[invokeRequest.FunctionId];

            // Not exactly sure what to do with bindings yet, so only handles 'httpTrigger-in' + 'http-out'
            string outHttpName = null;

            foreach (var binding in metadata.Bindings)
            {
                if (binding.Value.Direction == BindingInfo.Types.Direction.In)
                {
                    continue;
                }

                if (binding.Value.Type == "http")
                {
                    outHttpName = binding.Key;
                    break;
                }
            }

            if (outHttpName == null)
            {
                status.Status = StatusResult.Types.Status.Failure;
                status.Result = "PowerShell worker only handles http out binding for now.";
            }
            else
            {
                object argument = null;
                foreach (var input in invokeRequest.InputData)
                {
                    if (input.Data != null && input.Data.Http != null)
                    {
                        argument = input.Data.Http.Query.GetValueOrDefault("name", "Azure Functions");
                    }
                }

                s_ps.AddCommand(metadata.ScriptFile);
                if (argument != null)
                {
                    s_ps.AddArgument(argument);
                }

                TypedData retValue;
                try
                {
                    var results = s_ps.Invoke <string>();
                    retValue = new TypedData()
                    {
                        String = String.Join(',', results)
                    };
                }
                finally
                {
                    s_ps.Commands.Clear();
                }

                // This is just mimic what nodejs worker does
                var paramBinding = new ParameterBinding()
                {
                    Name = outHttpName,
                    Data = new TypedData()
                    {
                        Http = new RpcHttp()
                        {
                            StatusCode = "200",
                            Body       = retValue
                        }
                    }
                };

                // Not exactly sure which one to use for what scenario, so just set both.
                response.InvocationResponse.OutputData.Add(paramBinding);
                response.InvocationResponse.ReturnValue = retValue;
            }

            await s_call.RequestStream.WriteAsync(response);
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (MaxIdleTimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("MaxIdleTimeoutSec", MaxIdleTimeoutSec.Get(context));
            }

            if (ProcessIdleTimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("ProcessIdleTimeoutSec", ProcessIdleTimeoutSec.Get(context));
            }

            if (MaxSessions.Expression != null)
            {
                targetCommand.AddParameter("MaxSessions", MaxSessions.Get(context));
            }

            if (MaxConcurrentCommandsPerSession.Expression != null)
            {
                targetCommand.AddParameter("MaxConcurrentCommandsPerSession", MaxConcurrentCommandsPerSession.Get(context));
            }

            if (MaxSessionsPerUser.Expression != null)
            {
                targetCommand.AddParameter("MaxSessionsPerUser", MaxSessionsPerUser.Get(context));
            }

            if (MaxMemoryPerSessionMB.Expression != null)
            {
                targetCommand.AddParameter("MaxMemoryPerSessionMB", MaxMemoryPerSessionMB.Get(context));
            }

            if (MaxProcessesPerSession.Expression != null)
            {
                targetCommand.AddParameter("MaxProcessesPerSession", MaxProcessesPerSession.Get(context));
            }

            if (MaxConcurrentUsers.Expression != null)
            {
                targetCommand.AddParameter("MaxConcurrentUsers", MaxConcurrentUsers.Get(context));
            }

            if (IdleTimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("IdleTimeoutSec", IdleTimeoutSec.Get(context));
            }

            if (OutputBufferingMode.Expression != null)
            {
                targetCommand.AddParameter("OutputBufferingMode", OutputBufferingMode.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 22
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (Filter.Expression != null)
            {
                targetCommand.AddParameter("Filter", Filter.Get(context));
            }

            if (Include.Expression != null)
            {
                targetCommand.AddParameter("Include", Include.Get(context));
            }

            if (Exclude.Expression != null)
            {
                targetCommand.AddParameter("Exclude", Exclude.Get(context));
            }

            if (PathType.Expression != null)
            {
                targetCommand.AddParameter("PathType", PathType.Get(context));
            }

            if (IsValid.Expression != null)
            {
                targetCommand.AddParameter("IsValid", IsValid.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (OlderThan.Expression != null)
            {
                targetCommand.AddParameter("OlderThan", OlderThan.Get(context));
            }

            if (NewerThan.Expression != null)
            {
                targetCommand.AddParameter("NewerThan", NewerThan.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        /// <summary>
        /// Loads and retrieves information about a given module.
        /// </summary>
        /// <param name="module">The module to load, given as a PSModuleInfo.</param>
        /// <param name="error">Any error encountered, if any.</param>
        /// <returns>The name, version and data object for the module, or null if data collection did not succeed.</returns>
        public Tuple <string, Version, ModuleData> LoadAndGetModuleData(PSModuleInfo module, out Exception error)
        {
            try
            {
                PSModuleInfo importedModule = _pwsh.AddCommand(s_ipmoInfo)
                                              .AddParameter("ModuleInfo", module)
                                              .AddParameter("PassThru")
                                              .AddParameter("ErrorAction", "Stop")
                                              .InvokeAndClear <PSModuleInfo>()
                                              .FirstOrDefault();

                if (importedModule == null)
                {
                    error = null;
                    return(null);
                }

                Tuple <string, Version, ModuleData> moduleData = GetSingleModuleData(importedModule);

                _pwsh.AddCommand(s_rmoInfo)
                .AddParameter("ModuleInfo", importedModule)
                .InvokeAndClear();

                error = null;
                return(moduleData);
            }
            catch (RuntimeException e)
            {
                // A common problem is TypeData being hit with other modules, this overrides that
                if (e.ErrorRecord.FullyQualifiedErrorId.Equals("FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand") ||
                    e.ErrorRecord.FullyQualifiedErrorId.Equals("ErrorsUpdatingTypes"))
                {
                    foreach (string typeDataName in GetTypeDataNamesFromErrorMessage(e.Message))
                    {
                        _pwsh.AddCommand("Remove-TypeData")
                        .AddParameter("TypeName", typeDataName)
                        .InvokeAndClear();
                    }
                }

                // Attempt to load the module in a new runspace instead
                try
                {
                    using (SMA.PowerShell fallbackPwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace))
                    {
                        PSModuleInfo importedModule = fallbackPwsh.AddCommand(s_ipmoInfo)
                                                      .AddParameter("Name", module.Path)
                                                      .AddParameter("PassThru")
                                                      .AddParameter("Force")
                                                      .AddParameter("ErrorAction", "Stop")
                                                      .InvokeAndClear <PSModuleInfo>()
                                                      .FirstOrDefault();

                        error = null;
                        return(GetSingleModuleData(importedModule));
                    }
                }
                catch (Exception fallbackException)
                {
                    error = fallbackException;
                    return(null);
                }
            }
        }
Esempio n. 24
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Method.Expression != null)
            {
                targetCommand.AddParameter("Method", Method.Get(context));
            }

            if (UseBasicParsing.Expression != null)
            {
                targetCommand.AddParameter("UseBasicParsing", UseBasicParsing.Get(context));
            }

            if (Uri.Expression != null)
            {
                targetCommand.AddParameter("Uri", Uri.Get(context));
            }

            if (WebSession.Expression != null)
            {
                targetCommand.AddParameter("WebSession", WebSession.Get(context));
            }

            if (SessionVariable.Expression != null)
            {
                targetCommand.AddParameter("SessionVariable", SessionVariable.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (UseDefaultCredentials.Expression != null)
            {
                targetCommand.AddParameter("UseDefaultCredentials", UseDefaultCredentials.Get(context));
            }

            if (CertificateThumbprint.Expression != null)
            {
                targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
            }

            if (Certificate.Expression != null)
            {
                targetCommand.AddParameter("Certificate", Certificate.Get(context));
            }

            if (UserAgent.Expression != null)
            {
                targetCommand.AddParameter("UserAgent", UserAgent.Get(context));
            }

            if (DisableKeepAlive.Expression != null)
            {
                targetCommand.AddParameter("DisableKeepAlive", DisableKeepAlive.Get(context));
            }

            if (TimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("TimeoutSec", TimeoutSec.Get(context));
            }

            if (Headers.Expression != null)
            {
                targetCommand.AddParameter("Headers", Headers.Get(context));
            }

            if (MaximumRedirection.Expression != null)
            {
                targetCommand.AddParameter("MaximumRedirection", MaximumRedirection.Get(context));
            }

            if (Proxy.Expression != null)
            {
                targetCommand.AddParameter("Proxy", Proxy.Get(context));
            }

            if (ProxyCredential.Expression != null)
            {
                targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context));
            }

            if (ProxyUseDefaultCredentials.Expression != null)
            {
                targetCommand.AddParameter("ProxyUseDefaultCredentials", ProxyUseDefaultCredentials.Get(context));
            }

            if (Body.Expression != null)
            {
                targetCommand.AddParameter("Body", Body.Get(context));
            }

            if (ContentType.Expression != null)
            {
                targetCommand.AddParameter("ContentType", ContentType.Get(context));
            }

            if (TransferEncoding.Expression != null)
            {
                targetCommand.AddParameter("TransferEncoding", TransferEncoding.Get(context));
            }

            if (InFile.Expression != null)
            {
                targetCommand.AddParameter("InFile", InFile.Get(context));
            }

            if (OutFile.Expression != null)
            {
                targetCommand.AddParameter("OutFile", OutFile.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        /// <summary>
        /// Get a module data object for the Microsoft.PowerShell.Core pseudo-module.
        /// The version is given as the PowerShell version.
        /// </summary>
        /// <returns>The name, version and data of the core pseudo-module.</returns>
        public Tuple <string, Version, ModuleData> GetCoreModuleData()
        {
            var moduleData = new ModuleData();

            IEnumerable <CommandInfo> coreCommands = _pwsh.AddCommand(GcmInfo)
                                                     .AddParameter("Module", CORE_MODULE_NAME)
                                                     .InvokeAndClear <CommandInfo>();

            var cmdletData   = new JsonCaseInsensitiveStringDictionary <CmdletData>();
            var functionData = new JsonCaseInsensitiveStringDictionary <FunctionData>();

            foreach (CommandInfo command in coreCommands)
            {
                switch (command)
                {
                case CmdletInfo cmdlet:
                    try
                    {
                        cmdletData.Add(cmdlet.Name, GetSingleCmdletData(cmdlet));
                    }
                    catch (RuntimeException)
                    {
                        // If we can't load the cmdlet, we just move on
                    }
                    continue;

                case FunctionInfo function:
                    try
                    {
                        functionData.Add(function.Name, GetSingleFunctionData(function));
                    }
                    catch (RuntimeException)
                    {
                        // Some functions have problems loading,
                        // which likely means PowerShell wouldn't be able to run them
                    }
                    continue;

                default:
                    throw new CompatibilityAnalysisException($"Command {command.Name} in core module is of unsupported type {command.CommandType}");
                }
            }

            moduleData.Cmdlets   = cmdletData;
            moduleData.Functions = functionData;

            // Get default variables and core aliases out of a fresh runspace
            using (SMA.PowerShell freshPwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                Collection <PSObject> varsAndAliases = freshPwsh.AddCommand("Get-ChildItem")
                                                       .AddParameter("Path", "variable:,alias:")
                                                       .InvokeAndClear();

                var variables = new List <string>();
                var aliases   = new JsonCaseInsensitiveStringDictionary <string>();

                foreach (PSObject returnedObject in varsAndAliases)
                {
                    switch (returnedObject.BaseObject)
                    {
                    case PSVariable variable:
                        variables.Add(variable.Name);
                        continue;

                    case AliasInfo alias:
                        aliases.Add(alias.Name, GetSingleAliasData(alias));
                        continue;

                        // Skip over other objects we get back, since there's no reason to throw
                    }
                }

                moduleData.Variables = variables.ToArray();
                moduleData.Aliases   = aliases;
            }

            Version psVersion = _psVersion.PreReleaseLabel != null
                ? new Version(_psVersion.Major, _psVersion.Minor, _psVersion.Build)
                : (Version)_psVersion;

            return(new Tuple <string, Version, ModuleData>(CORE_MODULE_NAME, psVersion, moduleData));
        }
        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Get the host default values we should use if no explicit parameter was provided.
            var hostExtension = context.GetExtension <HostParameterDefaults>();
            Dictionary <string, object> parameterDefaults = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            if (hostExtension != null)
            {
                Dictionary <string, object> incomingArguments = hostExtension.Parameters;
                foreach (KeyValuePair <string, object> parameterDefault in incomingArguments)
                {
                    parameterDefaults[parameterDefault.Key] = parameterDefault.Value;
                }
            }


            if (DcomAuthentication.Expression != null)
            {
                targetCommand.AddParameter("DcomAuthentication", DcomAuthentication.Get(context));
            }

            if (Impersonation.Expression != null)
            {
                targetCommand.AddParameter("Impersonation", Impersonation.Get(context));
            }

            // See if the DCOM protocol is to be used
            bool usingDcom = false;

            if (Protocol.Expression != null)
            {
                string protocol = Protocol.Get(context);
                targetCommand.AddParameter("Protocol", protocol);
                if (string.Equals(protocol, "DCOM", StringComparison.OrdinalIgnoreCase))
                {
                    usingDcom = true;
                }
            }

            // Get the WSMan authentication mechanism to use. If no expression was specified,
            // and DCOM is not being used, get the default from the host.
            if (WsmanAuthentication.Expression != null)
            {
                targetCommand.AddParameter("WsmanAuthentication", WsmanAuthentication.Get(context));
            }
            else
            {
                if (!usingDcom)
                {
                    if (parameterDefaults.ContainsKey("PSAuthentication"))
                    {
                        string authString = parameterDefaults["PSAuthentication"].ToString();
                        // Note: the underlying cmdlet does support NegotiateWithImplicitCredential so it is expected
                        // that passing this in as-is will result in an (appropriate) error being emitted in that case.
                        targetCommand.AddParameter("WsmanAuthentication", authString);
                    }
                }
            }

            // Map PSComputerName to the underlying cmdlet name only if the computername is not empty
            string[] computerName = GetPSComputerName(context);
            if ((computerName != null) && (computerName.Length != 0))
            {
                targetCommand.AddParameter("ComputerName", computerName);
            }

            // Map PSCredential to credential. If no expression was provided, then use the default.
            if (PSCredential.Expression != null)
            {
                targetCommand.AddParameter("Credential", PSCredential.Get(context));
            }
            else
            {
                if (parameterDefaults.ContainsKey("PSCredential"))
                {
                    targetCommand.AddParameter("Credential", parameterDefaults["PSCredential"]);
                }
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (ThrottleLimit.Expression != null)
            {
                targetCommand.AddParameter("ThrottleLimit", ThrottleLimit.Get(context));
            }

            // Ignore the -Wait parameter in the self-restart case.
            if (!IsSelfRestart(context))
            {
                if (Wait.Expression != null)
                {
                    targetCommand.AddParameter("Wait", Wait.Get(context));
                }

                if (For.Expression != null)
                {
                    targetCommand.AddParameter("For", For.Get(context));
                }

                if (Delay.Expression != null)
                {
                    targetCommand.AddParameter("Delay", Delay.Get(context));
                }
            }

            if (Timeout.Expression != null)
            {
                targetCommand.AddParameter("Timeout", Timeout.Get(context));
            }

            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ProcessorArchitecture.Expression != null)
            {
                targetCommand.AddParameter("ProcessorArchitecture", ProcessorArchitecture.Get(context));
            }

            if (SessionType.Expression != null)
            {
                targetCommand.AddParameter("SessionType", SessionType.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (AssemblyName.Expression != null)
            {
                targetCommand.AddParameter("AssemblyName", AssemblyName.Get(context));
            }

            if (ApplicationBase.Expression != null)
            {
                targetCommand.AddParameter("ApplicationBase", ApplicationBase.Get(context));
            }

            if (ConfigurationTypeName.Expression != null)
            {
                targetCommand.AddParameter("ConfigurationTypeName", ConfigurationTypeName.Get(context));
            }

            if (RunAsCredential.Expression != null)
            {
                targetCommand.AddParameter("RunAsCredential", RunAsCredential.Get(context));
            }

            if (ThreadApartmentState.Expression != null)
            {
                targetCommand.AddParameter("ThreadApartmentState", ThreadApartmentState.Get(context));
            }

            if (ThreadOptions.Expression != null)
            {
                targetCommand.AddParameter("ThreadOptions", ThreadOptions.Get(context));
            }

            if (AccessMode.Expression != null)
            {
                targetCommand.AddParameter("AccessMode", AccessMode.Get(context));
            }

            if (UseSharedProcess.Expression != null)
            {
                targetCommand.AddParameter("UseSharedProcess", UseSharedProcess.Get(context));
            }

            if (StartupScript.Expression != null)
            {
                targetCommand.AddParameter("StartupScript", StartupScript.Get(context));
            }

            if (MaximumReceivedDataSizePerCommandMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedDataSizePerCommandMB", MaximumReceivedDataSizePerCommandMB.Get(context));
            }

            if (MaximumReceivedObjectSizeMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedObjectSizeMB", MaximumReceivedObjectSizeMB.Get(context));
            }

            if (SecurityDescriptorSddl.Expression != null)
            {
                targetCommand.AddParameter("SecurityDescriptorSddl", SecurityDescriptorSddl.Get(context));
            }

            if (ShowSecurityDescriptorUI.Expression != null)
            {
                targetCommand.AddParameter("ShowSecurityDescriptorUI", ShowSecurityDescriptorUI.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (NoServiceRestart.Expression != null)
            {
                targetCommand.AddParameter("NoServiceRestart", NoServiceRestart.Get(context));
            }

            if (PSVersion.Expression != null)
            {
                targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
            }

            if (SessionTypeOption.Expression != null)
            {
                targetCommand.AddParameter("SessionTypeOption", SessionTypeOption.Get(context));
            }

            if (TransportOption.Expression != null)
            {
                targetCommand.AddParameter("TransportOption", TransportOption.Get(context));
            }

            if (ModulesToImport.Expression != null)
            {
                targetCommand.AddParameter("ModulesToImport", ModulesToImport.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 28
0
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes to the
        /// default output path. Any exceptions that are thrown are just passed to
        /// the caller. Since all output goes to the default outter, this method()
        /// won't return anything.
        /// </summary>
        /// <param name="cmd">The script to run</param>
        /// <param name="input">Any input arguments to pass to the script. If null
        /// then nothing is passed in.</param>
        void executeHelper(string cmd, object input)
        {
            // Just ignore empty command lines...
            if (String.IsNullOrEmpty(cmd))
                return;

            // Create the pipeline object and make it available
            // to the ctrl-C handle through the currentPowerShell instance
            // variable

            lock (instanceLock)
            {
                currentPowerShell = PowerShell.Create();
            }

            currentPowerShell.Runspace = myRunSpace;

            // Create a pipeline for this execution - place the result in the currentPowerShell
            // instance variable so it is available to be stopped.
            try
            {
                currentPowerShell.AddScript(cmd);

                // Now add the default outputter to the end of the pipe and indicate
                // that it should handle both output and errors from the previous
                // commands. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the hosting
                // application.

                currentPowerShell.AddCommand("out-default");
                currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there was any input specified, pass it in, otherwise just
                // execute the pipeline...

                if (input != null)
                {
                    currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (instanceLock)
                {
                    currentPowerShell.Dispose();
                    currentPowerShell = null;
                }
            }
        }
Esempio n. 29
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (FilterScript.Expression != null)
            {
                targetCommand.AddParameter("FilterScript", FilterScript.Get(context));
            }

            if (Property.Expression != null)
            {
                targetCommand.AddParameter("Property", Property.Get(context));
            }

            if (Value.Expression != null)
            {
                targetCommand.AddParameter("Value", Value.Get(context));
            }

            if (EQ.Expression != null)
            {
                targetCommand.AddParameter("EQ", EQ.Get(context));
            }

            if (CEQ.Expression != null)
            {
                targetCommand.AddParameter("CEQ", CEQ.Get(context));
            }

            if (NE.Expression != null)
            {
                targetCommand.AddParameter("NE", NE.Get(context));
            }

            if (CNE.Expression != null)
            {
                targetCommand.AddParameter("CNE", CNE.Get(context));
            }

            if (GT.Expression != null)
            {
                targetCommand.AddParameter("GT", GT.Get(context));
            }

            if (CGT.Expression != null)
            {
                targetCommand.AddParameter("CGT", CGT.Get(context));
            }

            if (LT.Expression != null)
            {
                targetCommand.AddParameter("LT", LT.Get(context));
            }

            if (CLT.Expression != null)
            {
                targetCommand.AddParameter("CLT", CLT.Get(context));
            }

            if (GE.Expression != null)
            {
                targetCommand.AddParameter("GE", GE.Get(context));
            }

            if (CGE.Expression != null)
            {
                targetCommand.AddParameter("CGE", CGE.Get(context));
            }

            if (LE.Expression != null)
            {
                targetCommand.AddParameter("LE", LE.Get(context));
            }

            if (CLE.Expression != null)
            {
                targetCommand.AddParameter("CLE", CLE.Get(context));
            }

            if (Like.Expression != null)
            {
                targetCommand.AddParameter("Like", Like.Get(context));
            }

            if (CLike.Expression != null)
            {
                targetCommand.AddParameter("CLike", CLike.Get(context));
            }

            if (NotLike.Expression != null)
            {
                targetCommand.AddParameter("NotLike", NotLike.Get(context));
            }

            if (CNotLike.Expression != null)
            {
                targetCommand.AddParameter("CNotLike", CNotLike.Get(context));
            }

            if (Match.Expression != null)
            {
                targetCommand.AddParameter("Match", Match.Get(context));
            }

            if (CMatch.Expression != null)
            {
                targetCommand.AddParameter("CMatch", CMatch.Get(context));
            }

            if (NotMatch.Expression != null)
            {
                targetCommand.AddParameter("NotMatch", NotMatch.Get(context));
            }

            if (CNotMatch.Expression != null)
            {
                targetCommand.AddParameter("CNotMatch", CNotMatch.Get(context));
            }

            if (Contains.Expression != null)
            {
                targetCommand.AddParameter("Contains", Contains.Get(context));
            }

            if (CContains.Expression != null)
            {
                targetCommand.AddParameter("CContains", CContains.Get(context));
            }

            if (NotContains.Expression != null)
            {
                targetCommand.AddParameter("NotContains", NotContains.Get(context));
            }

            if (CNotContains.Expression != null)
            {
                targetCommand.AddParameter("CNotContains", CNotContains.Get(context));
            }

            if (In.Expression != null)
            {
                targetCommand.AddParameter("In", In.Get(context));
            }

            if (CIn.Expression != null)
            {
                targetCommand.AddParameter("CIn", CIn.Get(context));
            }

            if (NotIn.Expression != null)
            {
                targetCommand.AddParameter("NotIn", NotIn.Get(context));
            }

            if (CNotIn.Expression != null)
            {
                targetCommand.AddParameter("CNotIn", CNotIn.Get(context));
            }

            if (Is.Expression != null)
            {
                targetCommand.AddParameter("Is", Is.Get(context));
            }

            if (IsNot.Expression != null)
            {
                targetCommand.AddParameter("IsNot", IsNot.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (MemberType.Expression != null)
            {
                targetCommand.AddParameter("MemberType", MemberType.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (Value.Expression != null)
            {
                targetCommand.AddParameter("Value", Value.Get(context));
            }

            if (SecondValue.Expression != null)
            {
                targetCommand.AddParameter("SecondValue", SecondValue.Get(context));
            }

            if (TypeName.Expression != null)
            {
                targetCommand.AddParameter("TypeName", TypeName.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }

            if (NotePropertyName.Expression != null)
            {
                targetCommand.AddParameter("NotePropertyName", NotePropertyName.Get(context));
            }

            if (NotePropertyValue.Expression != null)
            {
                targetCommand.AddParameter("NotePropertyValue", NotePropertyValue.Get(context));
            }

            if (NotePropertyMembers.Expression != null)
            {
                targetCommand.AddParameter("NotePropertyMembers", NotePropertyMembers.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 31
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ApplicationName.Expression != null)
            {
                targetCommand.AddParameter("ApplicationName", ApplicationName.Get(context));
            }

            if (BasePropertiesOnly.Expression != null)
            {
                targetCommand.AddParameter("BasePropertiesOnly", BasePropertiesOnly.Get(context));
            }

            if ((ComputerName.Expression != null) && (PSRemotingBehavior.Get(context) != RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
            }

            if (ConnectionURI.Expression != null)
            {
                targetCommand.AddParameter("ConnectionURI", ConnectionURI.Get(context));
            }

            if (Dialect.Expression != null)
            {
                targetCommand.AddParameter("Dialect", Dialect.Get(context));
            }

            if (Enumerate.Expression != null)
            {
                targetCommand.AddParameter("Enumerate", Enumerate.Get(context));
            }

            if (Filter.Expression != null)
            {
                targetCommand.AddParameter("Filter", Filter.Get(context));
            }

            if (Fragment.Expression != null)
            {
                targetCommand.AddParameter("Fragment", Fragment.Get(context));
            }

            if (OptionSet.Expression != null)
            {
                targetCommand.AddParameter("OptionSet", OptionSet.Get(context));
            }

            if (Port.Expression != null)
            {
                targetCommand.AddParameter("Port", Port.Get(context));
            }

            if (Associations.Expression != null)
            {
                targetCommand.AddParameter("Associations", Associations.Get(context));
            }

            if (ResourceURI.Expression != null)
            {
                targetCommand.AddParameter("ResourceURI", ResourceURI.Get(context));
            }

            if (ReturnType.Expression != null)
            {
                targetCommand.AddParameter("ReturnType", ReturnType.Get(context));
            }

            if (SelectorSet.Expression != null)
            {
                targetCommand.AddParameter("SelectorSet", SelectorSet.Get(context));
            }

            if (SessionOption.Expression != null)
            {
                targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
            }

            if (Shallow.Expression != null)
            {
                targetCommand.AddParameter("Shallow", Shallow.Get(context));
            }

            if (UseSSL.Expression != null)
            {
                targetCommand.AddParameter("UseSSL", UseSSL.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (Authentication.Expression != null)
            {
                targetCommand.AddParameter("Authentication", Authentication.Get(context));
            }

            if (CertificateThumbprint.Expression != null)
            {
                targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
            }

            if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
            }

            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 32
0
        /// <summary>
        /// Execution of PowerShell value activity.
        /// PowerShell expression will be evaluated using PowerShell runspace and the value of Type T will be returned.
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            Token[]        tokens;
            ParseError[]   errors;
            ScriptBlockAst exprAst = Parser.ParseInput(Expression, out tokens, out errors);

            bool hasErrorActionPreference = false;
            bool hasWarningPreference     = false;
            bool hasInformationPreference = false;

            // Custom activity participant tracker for updating debugger with current variables and sequence stop points.
            // Regex looks for debugger sequence points like: Expression="'3:5:WFFunc1'".
            // We specifically disallow TimeSpan values that look like sequence points: Expression="'00:00:01'".
            bool isDebugSequencePoint = (!string.IsNullOrEmpty(Expression) && (System.Text.RegularExpressions.Regex.IsMatch(Expression, @"^'\d+:\d+:\S+'$")) &&
                                         (typeof(T) != typeof(System.TimeSpan)));
            var dataProperties = context.DataContext.GetProperties();

            if (isDebugSequencePoint || (dataProperties.Count > 0))
            {
                System.Activities.Tracking.CustomTrackingRecord customRecord = new System.Activities.Tracking.CustomTrackingRecord("PSWorkflowCustomUpdateDebugVariablesTrackingRecord");
                foreach (System.ComponentModel.PropertyDescriptor property in dataProperties)
                {
                    if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    Object value = property.GetValue(context.DataContext);
                    if (value != null)
                    {
                        object tempValue = value;

                        PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;
                        if (collectionObject != null && collectionObject.Count == 1)
                        {
                            tempValue = collectionObject[0];
                        }

                        customRecord.Data.Add(property.Name, tempValue);
                    }
                }
                if (isDebugSequencePoint)
                {
                    customRecord.Data.Add("DebugSequencePoint", Expression);
                }
                context.Track(customRecord);
            }

            if (tokens != null)
            {
                foreach (Token token in tokens)
                {
                    VariableToken variable = token as VariableToken;

                    if (variable != null)
                    {
                        if (variable.Name.Equals("ErrorActionPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasErrorActionPreference = true;
                        }
                        else if (variable.Name.Equals("WarningPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasWarningPreference = true;
                        }
                        else if (variable.Name.Equals("InformationPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasInformationPreference = true;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(Expression))
            {
                throw new ArgumentException(ActivityResources.NullArgumentExpression);
            }


            if (_ci == null)
            {
                lock (syncroot)
                {
                    // Invoke using the CommandInfo for Invoke-Command directly, rather than going through
                    // command discovery (which is very slow).
                    if (_ci == null)
                    {
                        _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand));
                    }
                }
            }

            Collection <PSObject> returnedvalue;
            Runspace       runspace         = null;
            bool           borrowedRunspace = false;
            PSWorkflowHost workflowHost     = null;

            if (typeof(ScriptBlock).IsAssignableFrom(typeof(T)))
            {
                Result.Set(context, ScriptBlock.Create(Expression));
                return;
            }
            else if (typeof(ScriptBlock[]).IsAssignableFrom(typeof(T)))
            {
                Result.Set(context, new ScriptBlock[] { ScriptBlock.Create(Expression) });
                return;
            }

            PropertyDescriptorCollection col        = context.DataContext.GetProperties();
            HostParameterDefaults        hostValues = context.GetExtension <HostParameterDefaults>();

            // Borrow a runspace from the host if we're not trying to create a ScriptBlock.
            // If we are trying to create one, we need to keep it around so that it can be
            // invoked multiple times.
            if (hostValues != null)
            {
                workflowHost = hostValues.Runtime;
                try
                {
                    runspace         = workflowHost.UnboundedLocalRunspaceProvider.GetRunspace(null, 0, 0);
                    borrowedRunspace = true;
                }
                catch (Exception)
                {
                    // it is fine to catch generic exception here
                    // if the local runspace provider does not give us
                    // a runspace we will create one locally (fallback)
                }
            }

            if (runspace == null)
            {
                // Not running with the PowerShell workflow host so directly create the runspace...
                runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());
                runspace.Open();
            }

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                try
                {
                    ps.Runspace = runspace;

                    // Subscribe to DataAdding on the error stream so that we can add position tracking information
                    if (hostValues != null)
                    {
                        HostSettingCommandMetadata sourceCommandMetadata = hostValues.HostCommandMetadata;

                        CommandMetadataTable.TryAdd(ps.InstanceId, sourceCommandMetadata);
                        ps.Streams.Error.DataAdding += HandleErrorDataAdding;
                    }

                    // First, set the variables from the host defaults
                    if ((hostValues != null) && (hostValues.Parameters != null))
                    {
                        if (hostValues.Parameters.ContainsKey("PSCurrentDirectory"))
                        {
                            string path = hostValues.Parameters["PSCurrentDirectory"] as string;
                            if (path != null)
                            {
                                ps.Runspace.SessionStateProxy.Path.SetLocation(path);
                            }
                        }

                        foreach (string hostDefault in hostValues.Parameters.Keys)
                        {
                            string mappedHostDefault = hostDefault;

                            if (hostDefault.Equals("ErrorAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasErrorActionPreference)
                                {
                                    mappedHostDefault = "ErrorActionPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (hostDefault.Equals("WarningAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasWarningPreference)
                                {
                                    mappedHostDefault = "WarningPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (hostDefault.Equals("InformationAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasInformationPreference)
                                {
                                    mappedHostDefault = "InformationPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            object propertyValue = hostValues.Parameters[hostDefault];
                            if (propertyValue != null)
                            {
                                ps.Runspace.SessionStateProxy.PSVariable.Set(mappedHostDefault, propertyValue);
                            }
                        }
                    }

                    // Then, set the variables from the workflow
                    foreach (PropertyDescriptor p in col)
                    {
                        string name  = p.Name;
                        object value = p.GetValue(context.DataContext);

                        if (value != null)
                        {
                            object tempValue = value;

                            PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;

                            if (collectionObject != null && collectionObject.Count == 1)
                            {
                                tempValue = collectionObject[0];
                            }

                            ps.Runspace.SessionStateProxy.PSVariable.Set(name, tempValue);
                        }
                    }

                    ps.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", ExpressionScriptBlock);


                    // If this needs to consume input, take it from the host stream.
                    PSDataCollection <PSObject> inputStream = null;
                    if (UseDefaultInput)
                    {
                        // Retrieve our host overrides
                        hostValues = context.GetExtension <HostParameterDefaults>();

                        if (hostValues != null)
                        {
                            Dictionary <string, object> incomingArguments = hostValues.Parameters;
                            if (incomingArguments.ContainsKey("Input"))
                            {
                                inputStream = incomingArguments["Input"] as PSDataCollection <PSObject>;
                            }
                        }
                    }

                    // Now invoke the pipeline
                    try
                    {
                        if (inputStream != null)
                        {
                            returnedvalue = ps.Invoke(inputStream);
                            inputStream.Clear();
                        }
                        else
                        {
                            returnedvalue = ps.Invoke();
                        }
                    }
                    catch (CmdletInvocationException cie)
                    {
                        if (cie.ErrorRecord != null && cie.ErrorRecord.Exception != null)
                        {
                            throw cie.InnerException;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                finally
                {
                    if (hostValues != null)
                    {
                        ps.Streams.Error.DataAdding -= HandleErrorDataAdding;
                        HostSettingCommandMetadata removedValue;
                        CommandMetadataTable.TryRemove(ps.InstanceId, out removedValue);
                    }

                    if (borrowedRunspace)
                    {
                        workflowHost.UnboundedLocalRunspaceProvider.ReleaseRunspace(runspace);
                    }
                    else
                    {
                        // This will be disposed  when the command is done with it.
                        runspace.Dispose();
                        runspace = null;
                    }
                }


                if (ps.Streams.Error != null && ps.Streams.Error.Count > 0)
                {
                    PSDataCollection <ErrorRecord> errorStream = null;

                    // Retrieve our host overrides
                    hostValues = context.GetExtension <HostParameterDefaults>();

                    if (hostValues != null)
                    {
                        Dictionary <string, object> incomingArguments = hostValues.Parameters;
                        if (incomingArguments.ContainsKey("PSError"))
                        {
                            errorStream = incomingArguments["PSError"] as PSDataCollection <ErrorRecord>;
                        }
                    }

                    if (errorStream != null && errorStream.IsOpen)
                    {
                        foreach (ErrorRecord record in ps.Streams.Error)
                        {
                            errorStream.Add(record);
                        }
                    }
                }

                T valueToReturn = default(T);
                if (returnedvalue != null && returnedvalue.Count > 0)
                {
                    try
                    {
                        if (returnedvalue.Count == 1)
                        {
                            if (returnedvalue[0] != null)
                            {
                                Object result     = returnedvalue[0];
                                Object baseObject = ((PSObject)result).BaseObject;
                                if (!(baseObject is PSCustomObject))
                                {
                                    result = baseObject;
                                }

                                // Try regular PowerShell conversion
                                valueToReturn = LanguagePrimitives.ConvertTo <T>(result);
                            }
                        }
                        else
                        {
                            valueToReturn = LanguagePrimitives.ConvertTo <T>(returnedvalue);
                        }
                    }
                    catch (PSInvalidCastException)
                    {
                        // Handle the special case of emitting a PSDataCollection - use its array constructor.
                        // This special case is why we aren't using PowerShell.Invoke<T>
                        if (typeof(T) == typeof(PSDataCollection <PSObject>))
                        {
                            Object tempValueToReturn = new PSDataCollection <PSObject>(
                                new List <PSObject> {
                                LanguagePrimitives.ConvertTo <PSObject>(returnedvalue[0])
                            });
                            valueToReturn = (T)tempValueToReturn;
                        }
                        else
                        {
                            throw;
                        }
                    }

                    Result.Set(context, valueToReturn);
                }
            }
        }